1

我在 CS 问题网站上遇到了这个问题,但我不知道该怎么做。

问题

我的第一个解决方案在这段代码中陷入了死胡同

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

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

4

1 回答 1

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;
于 2017-03-28T07:51:59.727 回答