这是一个我无法弄清楚的问题。如何找到收件人在前三次转账中总共收到1024美元。
create table transfers (
sender varchar not null,
recipient varchar not null,
amount integer not null
);
insert into receivers values ("TFC", "Apple", 2014);
insert into receivers values ("TFC", "Google", 100);
insert into receivers values ("TFC", "Google", 345);
insert into receivers values ("Facebook", "Facebook", 834);
insert into receivers values ("Facebook", "Google", 56);
insert into receivers values ("VMware", "Google", 12);
insert into receivers values ("VMware", "Google", 300);
insert into receivers values ("Google", "Facebook", 20);
insert into receivers values ("Google", "Facebook", 100);
insert into receivers values ("Google", "Facebook", 1000);
P.S。 我找到了解决方案。 困难在于如何根据名称获取最高额记录。而不是构造完成查询,实际上有很好的功能。
答案 0 :(得分:1)
首先,根据transfers
获取每个recipient
的前3 amount
,然后检查SUM
> = 1024:
SELECT
t1.recipient
FROM transfers AS t1
WHERE (
SELECT COUNT(*)
FROM transfers t2
WHERE
t2.recipient = t1.recipient
AND t2.amount >= t1.amount
) <= 3
GROUP BY t1.recipient
HAVING SUM(t1.amount) >= 1024
ORDER BY t1.recipient;