简体   繁体   English

选择其他列为组的最大值的列值

[英]Select column value where other column is max of group

I am trying to select two columns into a table (ID and state). 我试图在表中选择两列(ID和状态)。 The table should show the state with the maximum value for each ID. 该表应显示每个ID的最大值的状态。 I've tried a few other examples but nothing seems to work. 我尝试过其他几个例子但似乎没什么用。

Original data structure: 原始数据结构:

ID  state    value (FLOAT)
1   TX   921,294,481 
1   SC   21,417,296 
1   FL   1,378,132,290 
1   AL   132,556,895 
1   NC   288,176 
1   GA   1,270,986,631 
2   FL   551,374,452 
2   LA   236,645,530 
2   MS   2,524,536,050 
2   AL   4,128,682,333 
2   FL   1,503,991,028

The resulting data structure should therefore look like this: 因此,结果数据结构应如下所示:

ID  STATE (Max Value)
1   FL
2   AL

Florida and Alabama having the largest values in their ID groups. 佛罗里达州和阿拉巴马州的ID群体价值最高。

Any help would be greatly appreciated on this. 任何帮助将不胜感激。 I did find a SO answer here already, but could not make the answers work for me. 我确实在这里找到了答案,但无法让答案对我有用。

For SQL Server (and other products with windowed functions): 对于SQL Server(以及具有窗口函数的其他产品):

SELECT *
FROM
(
   SELECT
     *,
     ROW_NUMBER() OVER (PARTITION BY ID ORDER BY value desc) as rn
   FROM
     UnnamedTable
) t
WHERE
   t.rn = 1

A solution, based on the assumption that value is numeric: 一种解决方案,基于value数字的假设:

SELECT
  [ID],
  [State],
  [Value]
FROM
(
  SELECT 
    [ID],
    [State],
    [Value],
    Rank() OVER (PARTITION BY [ID] ORDER BY [Value] DESC) AS [Rank]
  FROM [t1]
) AS [sub]
WHERE [sub].[Rank] = 1
ORDER BY
  [ID] ASC,
  [State] ASC

If multiple State s with the same ID have the same Value , they would all get the same Rank . 如果具有相同ID多个State具有相同的Value ,则它们将获得相同的Rank This is different from using Row_Number , which return unique row numbers, but the order is chosen arbitrarily. 这与使用返回唯一行号的Row_Number不同,但是顺序是任意选择的。 (See also: SQL RANK() versus ROW_NUMBER() ) (另请参阅: SQL RANK()与ROW_NUMBER()

You can use a subquery to get this result: 您可以使用子查询来获得此结果:

select t1.id, t1.[state] MaxValue
from yourtable t1
inner join
(
  select id, max(value) MaxVal
  from yourtable
  group by id
) t2
  on t1.id = t2.id
  and t1.value = t2.maxval
order by t1.id

See SQL Fiddle with Demo 请参阅SQL Fiddle with Demo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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