列总和限制

时间:2020-10-06 11:34:54

标签: mysql

我正在尝试根据一列的最大总数从数据库中获取有限的记录。
表格:

| id | count | name        |
|----|-------|-------------|
| 1  | 5     | Berlin      |
| 2  | 4     | New York    |
| 3  | 2     | Minsk       |
| 4  | 2     | London      |

count列之和的最大计数不应超过4,但至少应包含一条记录。

预期输出:(每次获取后,从表中删除该项目)

#1
| id | count | name        |
|----|-------|-------------|
| 1  | 5     | Berlin      |

#2
| id | count | name        |
|----|-------|-------------|
| 2  | 4     | New York    |

#3
| id | count | name        |
|----|-------|-------------|
| 3  | 2     | Minsk       |
| 4  | 2     | London      |

我根据以下线程尝试过此操作:at forums.mysql.com,但实际上并没有起作用。

我尝试过:

SET @sum=0;
SELECT id, count, @sum:=@sum + count as running_count FROM cities HAVING @sum <= 4;

编辑: 快到了。

WITH data as (
 SELECT *, sum(count) over (order by id) as running FROM cities
)

SELECT * FROM data WHERE running <= 4

2 个答案:

答案 0 :(得分:1)

假设id确定了顺序,则可以使用ORDER BYLIMIT获得“第一条”记录。

SELECT t1.id,
       t1.count,
       t1.name
       FROM elbat t1
       ORDER BY t1.id
       LIMIT 1;

然后,您可以UNION count总数不超过限制的所有记录。在MySQL 8+中,您可以使用sum()窗口函数。

SELECT x.id,
       x.count,
       x.name
       FROM (SELECT t2.id,
                    t2.count,
                    t2.name,
                    sum(t2.count) OVER (ORDER BY id) sum_count
                    FROM elbat t2) x
       WHERE x.sum_count <= 4;

在版本8之前的版本中,您可以使用相关的子查询和聚合。

SELECT t2.id,
       t2.count,
       t2.name
       FROM elbat t2
       WHERE (SELECT sum(t3.count)
                     FROM elbat t3
                     WHERE t3.id <= t2.id) <= 4;

这一切都能让您

(SELECT t1.id,
        t1.count,
        t1.name
        FROM elbat t1
        ORDER BY t1.id
        LIMIT 1)
UNION
(SELECT x.id,
        x.count,
        x.name
        FROM (SELECT t2.id,
                     t2.count,
                     t2.name,
                     sum(t2.count) OVER (ORDER BY id) sum_count
                     FROM elbat t2) x
        WHERE x.sum_count <= 4);

8岁以上和

(SELECT t1.id,
        t1.count,
        t1.name
        FROM elbat t1
        ORDER BY t1.id
        LIMIT 1)
UNION
(SELECT t2.id,
        t2.count,
        t2.name
        FROM elbat t2
        WHERE (SELECT sum(t3.count)
                      FROM elbat t3
                      WHERE t3.id <= t2.id) <= 4);

表示8-。

db<>fiddle

答案 1 :(得分:0)

WITH data as (
  SELECT
     *,
     sum(count) over (order by id) as running
  FROM
     cities
     
)

SELECT 
   *
FROM
   data
WHERE 
   (running <= 4) OR
   (running = (SELECT min(running) FROM data)

给我结果。