每组中一列中三个最大值的总和

时间:2017-03-28 01:20:53

标签: sqlite aggregate-functions limit-per-group

我在CS问题网站上遇到了这个问题,我无法弄清楚如何做到这一点。

Problem

我的第一个解决方案是使用此代码进入死胡同

SELECT 
 recipient
FROM 
 transfers
GROUP BY
 recipient
HAVING
 sum(amount) >= 1024
ORDER BY
 recipient ASC;

但是没有办法对总和进行限制以将最大的3个值相加。

另一个想法是创建一个子查询并加入这两个表。

喜欢这样

SELECT
recipient,
(   SELECT SUM(amount)
    FROM transfer t1
    WHERE t1.recipient = t.recipient ORDER BY amount DESC LIMIT 3) as summedValue
FROM
transfer t

然而,这总结了所有的价值而不仅仅是前三名。

1 个答案:

答案 0 :(得分:0)

对于一个特定的收件人,以下查询获得(最多)三个最大的转移:

SELECT *
FROM transfers
WHERE recipient = ?
ORDER BY amount DESC
LIMIT 3;

要获得这些传输的全部数量,请将其包装到子查询中(否则,LIMIT将在聚合后执行):

SELECT sum(amount)
FROM (SELECT *
      FROM transfers
      WHERE recipient = ?
      ORDER BY amount DESC
      LIMIT 3);

然后使用它来过滤帐户(DISTINCT子查询确保每个帐户只检查一次):

SELECT recipient
FROM (SELECT DISTINCT recipient
      FROM transfers) AS r
WHERE (SELECT sum(amount)
       FROM (SELECT *
             FROM transfers
             WHERE recipient = r.recipient
             ORDER BY amount DESC
             LIMIT 3)
      ) >= 1024;