如何根据一列的最大值在表格中选择不同的数据?

时间:2014-10-03 23:10:09

标签: sql postgresql

我有下表:

A        B         C        D         E        F 
James    Michael   123      Hello     World    1
James    Michael   123      Hello     World    5
James    Michael   123      Hello     World    7
Harold   Reynolds  345      There     Poop     1
John     Lowland   555      Woh       Pop      1
Howard   Yow       255      Man       That     1

我希望能够根据F的MAX值选择所有行。

结果应该是:

James    Michael   123      Hello     World 
Harold   Reynolds  345      There     Poop     
John     Lowland   555      Woh       Pop      
Howard   Yow       255      Man       That     

3 个答案:

答案 0 :(得分:3)

您可以使用ROW_NUMBER()功能执行此操作:

;with cte AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY "C" ORDER BY "F" DESC) AS RN
              FROM Table1)
SELECT "A", "B", "C", "D", "E"
FROM cte
WHERE RN = 1

演示:SQL Fiddle

ROW_NUMBER()函数为PARTITION BY子句中使用的每组字段(可选)从1开始为每一行生成一个数字,顺序由ORDER BY子句确定(必需的)。

注意:我假设您的C字段足以识别行,但如果情况不是这样,您可能需要向PARTITION BY子句添加字段。

答案 1 :(得分:2)

我们可以使用row_number并对结果进行分区,并从分区中只获取1行

   Select * from 
   ( select *, row_number() over (    partition by A, B, C,D ,E order by F desc ) as seq from tableA) T
   Where T.seq =1

答案 2 :(得分:2)

因为这是pg DISTINCT ON是正确的方法:

SELECT * FROM(
  SELECT DISTINCT ON ("A","B","C","D","E") "A","B","C","D","E","F"
FROM table1
ORDER BY "A","B","C","D","E","F" DESC) AS q
ORDER BY "F" DESC;

外部查询就是把詹姆斯放在首位。

fiddle