有多種方式可以通過使用窗口功能(如row_number()
)來獲得您想要的方式。 row_number函數允許你爲每一行使用一個分區創建一個唯一的數字,在你的情況下,分區是dh_type
,然後通過你的dh_createDT
命令創建數字。那麼最終的結果將是一個ROW_NUMBER = 1:
select dh_type,
dh_product
from
(
SELECT
dh_type,
dh_product,
rn = row_number() over(partition by dh_type order by dh_createDT desc)
FROM myProducts
WHERE dh_productid = '08-BLD4011603S0'
AND dh_type IN ('New','Old','Ref')
) d
where rn = 1;
另一種方式來獲得的結果將是使用子查詢得到max(dh_createDT)
每個dh_type
和dh_product
行,然後加入該回你表:
select
dh_type,
dh_product
from myProducts p
inner join
(
select
dh_type,
dh_product,
MaxDate = max(dh_createDT)
from myProducts
where h_productid = '08-BLD4011603S0'
and dh_type IN ('New','Old','Ref')
group by dh_type, dh_product
) p1
on p.dh_type = p1.dh_type
and p.dh_product = p1.dh_product
and p.dh_createDT = p1.MaxDate
where p.h_productid = '08-BLD4011603S0'
and p.dh_type IN ('New','Old','Ref')
添加一些示例表格數據和預期結果 - 以及格式化文本。 – jarlh