如何选择具有特定列之和的前N行满足SQLite中的一些要求?

时间:2012-09-29 05:00:50

标签: sql sqlite

如果我们有一个表有一个名为X的列包含int。现在我想选择(实际上我想删除)最旧的N行,其中X的总和尽可能多但不超过300?

  _id|X
    1|50
    2|150
    3|80
    4|100
    5|200
    6|70

1是最老的,6是最新的。所以我想得到第1,2,3行,其X的总和是280.是否有可能通过一个选择语句实现这一点?

1 个答案:

答案 0 :(得分:1)

这应该做:

.mode columns
.headers on

CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, value INT);
INSERT INTO foo (value) VALUES (50), (150), (80), (100), (200), (70);

SELECT t1.id, t1.value
FROM foo t1 INNER JOIN foo t2 ON t2.id <= t1.id
GROUP BY t1.id, t1.value
HAVING SUM(t2.value) <= 300
ORDER BY t1.id;

SELECT返回:

id          value
----------  ----------
1           50
2           150
3           80

删除所选记录:

DELETE FROM foo WHERE id IN (
    SELECT t1.id
    FROM foo t1 INNER JOIN foo t2 ON t2.id <= t1.id
    GROUP BY t1.id, t1.value
    HAVING SUM(t2.value) <= 300);