在MSSQL中选择每年的最大项目数

时间:2014-03-05 14:56:33

标签: sql sql-server tsql

我想找到每年的最大数量。

我有一张包含此类数据的表格:

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

1 个答案:

答案 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