简体   繁体   中英

select the maximum item per year in MSSQL

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM