我有兩個表如下。
表格1:
| ID | 藝術編號 | 日期 | 價格 |
|---|---|---|---|
| 1 | 第1條 | 07.05.2022 | 100.00 |
| 2 | 第二條 | 07.05.2022 | 100.00 |
| 3 | 第1條 | 2022 年 5 月 10 日 | 100.00 |
| 4 | 第二條 | 2022 年 5 月 10 日 | 100.00 |
表 2
| ID | 藝術編號 | 價格 |
|---|---|---|
| 1 | 第1條 | 80.00 |
| 2 | 第二條 | 120.00 |
我想為表 1 提供每個 ArtNumber 的最新(日期)價格。但也想再檢查一下價格是否超過表2。(Table1.Price<Table2.Price)
預期結果:
| 藝術編號 | 價格 |
|---|---|
| 第二條 | 120.00 |
我嘗試了很多GROUP BY, ORDER BY,MAX()和DISTINCT組合都沒有成功。
uj5u.com熱心網友回復:
您可以使用簡單的每個組最大 n 查詢:
with cte as (
select *, row_number() over (partition by artnumber order by date desc) as rn
from table1
)
select *
from cte
join table2 on cte.artnumber = table2.artnumber
where rn = 1 and cte.price < table2.price
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/474652.html
