Reputation: 445
I want to find the max count/per year.
I have a table with this kind of data:
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
Expected output:
Years shipvia count
---------------------
2002 3 58
2003 2 152
2004 2 117
I have tried the query below, but it gives me wrong data:
SELECT Years,
ShipVia,
max(count)
FROM table
GROUP BY Years, ShipVia
Upvotes: 1
Views: 60
Reputation: 70648
Assuming 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
Upvotes: 2