我想找到每年的最大数量。
我有一张包含此类数据的表格:
Years shipvia count
---------------------
2002 1 38
2002 2 56
2002 3 58
2003 1 134
2003 2 152
2003 3 122
2004 1 78
2004 2 117
2004 3 75
预期产出:
Years shipvia count
---------------------
2002 3 58
2003 2 152
2004 2 117
我已尝试过以下查询,但它给了我错误的数据:
SELECT Years,
ShipVia,
max(count)
FROM table
GROUP BY Years, ShipVia
答案 0 :(得分:2)
假设SQL Server 2005 +:
;WITH CTE AS
(
SELECT *,
RN = ROW_NUMBER() OVER(PARTITION BY [Years] ORDER BY [Count] DESC)
FROM YourTable
)
SELECT [Years], shipvia, [count]
FROM CTE
WHERE RN = 1