SQL选择另一列中具有最大值的列

时间:2017-02-16 17:11:05

标签: sql sql-server

我有一个看起来像这样的表:

Name  Group   Value
A     1       0
B     1       2
C     1       5
D     2       6
E     2       0
F     3       3

我想在每个组中选择具有最大值的名称。例如,有3组,因此结果将是:

Name
C     (because it has the maximum value (5) within group 1)
D     (because it has the maximum value (6) within group 2)
F     (because it has the maximum value (3) within group 3)

我尝试写这样的东西:

SELECT name FROM table
WHERE value = (SELECT max(value) FROM table)
GROUP BY group

但是max(value)返回整个表的全局最大值(在本例中类似于(6))。我该如何解决这个问题?

4 个答案:

答案 0 :(得分:3)

你有点亲近。在外部查询中需要相关子查询而不是聚合:

SELECT t.*
FROM table t
WHERE value = (SELECT max(t2.value) FROM table t2 WHERE t2.group = t.group);

这是标准SQL,可以在任何数据库中使用。您可以选择name,如果这就是您想要的,但我认为group也很有用。

在大多数数据库中,您可以使用row_number()来实现此目的。

在SQL Server中,更典型的做法是:

select t.*
from (select t.*,
             row_number() over (partition by group order by value desc) as seqnum
      from t
     ) t
where seqnum = 1;

如果存在关系(最大值),则返回一行(通常是所需的)。如果您想要所有这些行,请改用rank()dense_rank()

答案 1 :(得分:2)

有很多方法可以做到这一点,其中一些是:

所有这些的rextester:http://rextester.com/DTWB67044

max() over()版本:

with cte as (
  select *, MaxValue = max([Value]) over (partition by [Group])
  from t
)
select Name
from cte
where [Value] = MaxValue;

inner join版本:

select t.Name
from t
  inner join (
    select MaxValue=max(value), [Group]
    from t
    group by [Group]
    ) as m
      on t.[Group] = m.[Group]
     and t.[Value] = m.MaxValue;

cross apply()版本:

select t.Name
from t
  cross apply (
    select top 1
        [Value]
      from t as i
      where i.[Group] = t.[Group]
      order by i.[Value] desc
     ) as x
  where t.[Value] = x.[Value];

如果您只为每个组返回一个值,那么这些也可以使用:

使用 common table expression

row_number()

with cte as (
select *, rn = row_number() over (partition by [Group] order by [Value] desc)
from t
)
select Name
from cte
where rn = 1;

top with ties 版本:

select top 1 with ties 
  t.Name
from t
order by row_number() over (partition by [Group] order by [Value] desc);

答案 2 :(得分:0)

这将为您提供所需的输出。

Select name, max(value) from table group by group order by group 

输出:

C | 5
D | 6
F | 3

答案 3 :(得分:0)

Gordon's解决方案适用于user3685285中的示例:

SELECT t.Name FROM table t WHERE Value = (SELECT max(tt.Value) FROM table tt WHERE tt.Group = t.Group);