选择按两列分组的最大值

时间:2015-05-20 22:12:12

标签: sql postgresql greatest-n-per-group

我有一个像这样的简单表

firstname, lastname , nb_payments
a, b , 10
a, b , 20
b, a , 30
b, a , 40
b, b , 50

我想选择按夫妻名字,姓氏

分组的3笔最高付款额

所需的输出就像这样

firstname, lastname , top3
b, a , 70
b, b , 50
a, b , 30

我做了这个查询:SELECT firstname, lastname , nb_payments as top3 FROM account ORDER BY nb_payments DESC LIMIT 3

但它并没有加上按夫妻名字,姓氏

分组的nb_payments

任何帮助将不胜感激 非常感谢你

3 个答案:

答案 0 :(得分:1)

您需要按firstnamelastname

对付款和分组进行汇总
SELECT   firstname, lastname , SUM(nb_payments) 
FROM     account 
GROUP BY firstname, lastname
ORDER BY 3 DESC LIMIT 3

答案 1 :(得分:1)

我认为这会产生你想要的输出:

select firstname, lastname, sum(nb_payments)
from (select t.*,
             row_number() over (partition by firstname, lastname
                                order by nb_payments desc) as seqnum
      from table t
     ) t
where seqnum <= 3
group by firstname, lastname;

答案 2 :(得分:1)

如果有帮助,这就是我在oracle中写的方式。还有其他方法。

select * from(
    SELECT firstname, lastname , sum(nb_payments) as top3 FROM test group by firstname,lastname ORDER BY top3 desc )
    where rownum <=3