CarID Date Shift
1 2016-08-20 3
1 2016-08-21 1
1 2016-08-21 2
2 2016-08-20 1
3 2016-08-21 3
预期结果
CarID Date Shift
1 2016-08-21 2
2 2016-08-20 1
3 2016-08-21 3
如何编写此类查询以获得最大日期和最大班次组合的每辆车的前1条记录?
答案 0 :(得分:6)
您可以使用排名函数ROW_NUMBER
,例如在CTE中:
WITH CTE AS
(
SELECT RN = ROW_NUMBER() OVER (PARTITION BY CarID ORDER BY Date DESC, Shift DESC), *
FROM dbo.TableName t
)
SELECT * FROM CTE
WHERE RN = 1
答案 1 :(得分:2)
如果您想要同一行中的Date和Shift的最大值:
select top 1 with ties CarId, [Date], Shift
from myTable
order by row_number() over (partition by CarId order by [Date] desc, Shift desc);
答案 2 :(得分:0)
使用OUTER APPLY的另一种方法:
SELECT DISTINCT b.*
FROM YourTable a
OUTER APPLY (
SELECT TOP 1 *
FROM YourTable
WHERE CarID=a.CarID
ORDER BY [Date] DESC, [Shift] DESC) as b
输出:
CarID Date Shift
1 2016-08-21 2
2 2016-08-20 1
3 2016-08-21 3