有多种方式可以通过使用窗口功能(如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