此screenshot是我的结果。
如何获取相同ID的最高记录? (查询结果有3条记录,但我想记录最高记录)
谢谢 我的代码İs但我有错误('CTE'多次指定了'ID'列。)
WITH CTE AS
(
SELECT RN = ROW_NUMBER() OVER (PARTITION BY dbo.Product.ID ORDER BY dbo.Picture.UpdatedDate ASC), *
FROM Dbo.Product
inner JOIN dbo.Product_Picture_Mapping on dbo.Product_Picture_Mapping.ProductID = dbo.Product.ID
inner join dbo.Picture on dbo.Picture.ID = dbo.Product_Picture_Mapping.PictureID
)
SELECT * FROM CTE WHERE RN = 1
ORDER BY dbo.Picture.UpdatedDate DESC
答案 0 :(得分:0)
没有固有的“顶部”或“底部”,因此您需要指定要排序的列。但是,您可以使用ROW_NUMBER
为每个ID获取一条记录。
例如(假设UPDATEDDATE
为order-column):
WITH CTE AS
(
SELECT RN = ROW_NUMBER() OVER (PARTITION BY ID ORDER BY UPDATEDDATE ASC), *
FROM rbo.Product INNER JOIN ....
)
SELECT * FROM CTE WHERE RN = 1
ORDER BY UPDATEDDATE DESC
(用联接替换....
,我不想从你的图像中输入它们)
答案 1 :(得分:0)
您可以使用top 1 with ties
选项。
select top 1 with ties *
from ...
order by id
答案 2 :(得分:0)
;with TempTb as (Select ID, Name,ShortDesc, Count =ROW_NUMBER()
over(PARTITION By ID Order By ID)
From YourTable
)
Select * from TempTb where Count =1