如何根据另一列的类别信息从列中提取最高记录

时间:2016-06-03 01:26:24

标签: sql

这是一个我无法弄清楚的问题。如何找到收件人在前三次转账中总共收到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。 我找到了解决方案。 困难在于如何根据名称获取最高额记录。而不是构造完成查询,实际上有很好的功能。

  • 在postgresql中,功能OVER(PARTITION BY)专门针对此问题。
  • 在mysql中,它有点难,但你可以使用诸如 group_concat + substr,substr来组合记录需要排序, 然后group_concat到内部排序。

1 个答案:

答案 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;