选择按两列分组的最大值
selecting max values grouped by two column
我有一个简单的table像这样
firstname, lastname , nb_payments
a, b , 10
a, b , 20
b, a , 30
b, a , 40
b, b , 50
我想select按夫妻名字、姓氏分组的 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 按夫妇名字、姓氏分组
如有任何帮助,我们将不胜感激
非常感谢
您需要按 firstname
和 lastname
对付款进行汇总和分组
SELECT firstname, lastname , SUM(nb_payments)
FROM account
GROUP BY firstname, lastname
ORDER BY 3 DESC LIMIT 3
我认为这会产生您想要的输出:
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;
这就是我在 oracle 中的写法,如果有帮助的话。还有其他方法。
select * from(
SELECT firstname, lastname , sum(nb_payments) as top3 FROM test group by firstname,lastname ORDER BY top3 desc )
where rownum <=3
我有一个简单的table像这样
firstname, lastname , nb_payments
a, b , 10
a, b , 20
b, a , 30
b, a , 40
b, b , 50
我想select按夫妻名字、姓氏分组的 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 按夫妇名字、姓氏分组
如有任何帮助,我们将不胜感激 非常感谢
您需要按 firstname
和 lastname
SELECT firstname, lastname , SUM(nb_payments)
FROM account
GROUP BY firstname, lastname
ORDER BY 3 DESC LIMIT 3
我认为这会产生您想要的输出:
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;
这就是我在 oracle 中的写法,如果有帮助的话。还有其他方法。
select * from(
SELECT firstname, lastname , sum(nb_payments) as top3 FROM test group by firstname,lastname ORDER BY top3 desc )
where rownum <=3