我有一个帐户表我希望获取在3个最大交易中获得大于或等于1024金额的所有收件人姓名。
我附加一张图片来展示表中的数据,这些结果将是两行,收件人名称为nutan和vicky
-
select recipient from accounts group by recipient having sum(amount) >= 1024 and count(*) <=3
答案 0 :(得分:1)
您需要获得前三个交易。可能最简单的方法是使用变量:
select recipient
from (select a.*,
(@rn := if(@r = recipient, @rn + 1,
if(@rn := recipient, 1, 1)
)
) as rn
from accounts a cross join
(select @rn := 0, @r := '') params
order by recipient, amount desc
) a
where rn <= 3
group by recipient
having sum(amount) >= 1024;
答案 1 :(得分:0)
我发现解决方案现在感觉像超级英雄。
set @num=1,@recp:='';
select
@recp:=recipient as recipient
from
(select recipient,amount from accounts order by recipient,amount desc) as accounts
where (@num:=if(@recp=recipient,@num+1,1))<4
group by recipient
having sum(amount)>=1024
order by recipient,amount desc;