获取具有SQL Server 2008列的MAX值的整个ROW

时间:2011-06-16 03:53:50

标签: sql sql-server tsql sql-server-2008 common-table-expression

Sample

我想在SQL Server 2008中执行上述操作。有什么想法吗?

1 个答案:

答案 0 :(得分:10)

喜欢这个吗?

设定:

declare @MyTable table(Year int, Month int, Day int, Total int)

insert @MyTable
values
    (2005, 9, 23, 12),
    (2005, 9, 26, 5),
    (2005, 9, 24, 1),
    (2005, 9, 15, 28),
    (2005, 9, 21, 1),
    (2005, 9, 13, 1),
    (2005, 10, 31, 5),
    (2005, 11, 18, 115),
    (2005, 11, 20, 1),
    (2005, 11, 11, 1),
    (2005, 11, 19, 1)

查询:

;with cte
as
(
    select *,
        row_number() over(partition by Year, Month order by Total desc) RowNumber
    from @MyTable
)
select Year, Month, Day, Total 
from cte
where RowNumber = 1

输出:

Year        Month       Day         Total
----------- ----------- ----------- -----------
2005        9           15          28
2005        10          31          5
2005        11          18          115