我有一张桌子A:
ID | ProductCatId | ProductCode | Price
1 | 1 | PROD0001 | 2
2 | 2 | PROD0005 | 2
3 | 2 | PROD0005 | 2
4 | 3 | PROD0008 | 2
5 | 5 | PROD0009 | 2
6 | 7 | PROD0012 | 2
我想选择ID,ProductCatId,ProductCode,Price with condition: “如果ProductCatId存在相同的值,那么请使用max(ID)”获取ProductCatId,如:
ID | ProductCatId | ProductCode | Price
1 | 1 | PROD0001 | 2
3 | 2 | PROD0005 | 2
4 | 3 | PROD0008 | 2
5 | 5 | PROD0009 | 2
6 | 7 | PROD0012 | 2
答案 0 :(得分:3)
转到窗口函数和row_number()
select ID , ProductCatId , ProductCode , Price
from (
select ID , ProductCatId , ProductCode , Price, row_number() over (partition by ProductCatId order by ID desc) as rn
from myTable
) as t
where t.rn = 1
答案 1 :(得分:2)
你可以试试这个,
Select Max(ID),ProductCatId,ProductCode,price
From TableName
Group By ProductCatId,ProductCode,price
答案 2 :(得分:1)
select
top 1 with ties
ID,ProductCatId,ProductCode,Price
from
table
order by
row_number() over (partition by productcatid order by id desc)
答案 3 :(得分:1)
可以使用row_number()
:
select t.*
from (select t.*,
row_number() over (partition by ProductCatId order by ID desc) as seqnum
from @Table t
) t
where seqnum = 1
order by ID;