SQL:如何获取SQL Server中具有列的最大值的行

时间:2015-12-31 09:01:39

标签: sql sql-server group-by greatest-n-per-group

我有一个数据集已经按PersonClass列分组,我将此查询用于此过程:

SELECT Person,Class, MAX(TimeSpent) as MaxTimeSpent 
FROM Persons 
GROUP BY Person,Class

输出:

Person   Class    MaxTimeSpent 
--------|--------|-------------|
MJ      |   0    | 0           |
MJ      |   1    | 659         |
MJ      |   2    | 515         |

我想要做的是获取此数据集中具有最大Class值的行(此示例的第3行)。

我该怎么做?任何帮助,将不胜感激。

4 个答案:

答案 0 :(得分:2)

试试这个

SELECT T.*
FROM
    (SELECT Person,
           Class,
           MAX(TimeSpent) AS MaxTimeSpent 
    FROM Persons AS P
    WHERE Person = 'MJ'
    GROUP BY Person, Class) AS T
WHERE T.class = (
      SELECT MAX(class) FROM Persons AS P
      WHERE P.person = T.person)

答案 1 :(得分:1)

你可以使用cte。

 declare @Persons table (person nvarchar(10),Class int ,TimeSpent int)

insert into @Persons
select 'MJ',0,0 union all
select 'MJ',1,659 union all
select 'MJ',2,515 


;with cte
as(
SELECT Person,Class,TimeSpent , row_number() over(partition by Person  order by Class desc )  as RN
FROM @Persons 
)
select * from cte where RN=1

解决方案2:使用Out Cte:

SELECT * FROM (
    SELECT Person
        ,Class
        ,TimeSpent
        ,row_number() OVER (PARTITION BY Person ORDER BY Class DESC) AS RN FROM @Persons
    ) t WHERE t.RN = 1

答案 2 :(得分:0)

尝试这个:

declare @t table (Person  varchar (20),Class    int ,MaxTimeSpent int )
insert into @t VALUES ('MJ',0,0)
insert into @t VALUES ('MJ',1,659)
insert into @t VALUES ('MJ',2,515)

SELECT TOP 1 * FROM @t ORDER BY 2 DESC

--OR
SELECT * FROM @t WHERE Class = (SELECT max(class) FROM @t)

-- OR
SELECT TOP 1 * FROM (
    SELECT *
        ,ROW_NUMBER() OVER (PARTITION BY person ORDER BY Class DESC) Record_Count FROM @t
    ) a

答案 3 :(得分:0)

将Top 1 Person,Class,MAX(TimeSpent)选为MaxTimeSpent 来自人 GROUP BY Person,Class desc的班级订单