选择每个ID的最大值(包括一个ID的多个最大值的可能性!)

时间:2016-10-31 14:36:05

标签: postgresql max aggregate-functions greatest-n-per-group

我有一张桌子,上面写着ID和分数。我想为每个ID获得最高分。但是可能会发生我对一个ID有相同的分数,在这种情况下我想要两个值。所以,让我们说我有一张桌子

ID    score
1     10
1     10
2     8
2     6

我希望得到结果

ID    score
1     10
1     10
2     8

这将是

的组合
 SELECT ID, max(score) FROM tbl GROUP BY ID, score ORDER BY ID

select * from tbl where score = (select max (score) from tbl)

我试过

select * from tbl where score = (select max (score) from tbl GROUP BY ID)

但当然它说我在子​​查询中有多行。我想要那些我不想将它限制为1的行。

我试过

 SELECT * FROM tbl AS tbl1
 JOIN 
(select * from tbl where score = (select max (score) from tbl)) 
ON tbl1.ID=tbl.ID

但它说" FROM中的子查询必须有一个别名"我给所有子查询都给了别名,但我仍然有这个错误。

1 个答案:

答案 0 :(得分:2)

一种方法是使用CTE

WITH themaxes AS
(SELECT id, max(score) AS maxscore FROM tbl GROUP BY ID)
SELECT t.* FROM tbl t INNER JOIN themaxes m ON m.id = t.id AND m.maxscore = t.score;

另一种方法是使用window function(此示例使用带有别名的子查询):

SELECT id,score FROM 
(SELECT rank() OVER (PARTITION BY id ORDER BY score DESC) AS therank, * FROM tbl) t 
WHERE therank = 1
相关问题