根据聚合函数标准删除记录

时间:2014-09-16 13:19:30

标签: sql sqlite aggregate-functions sql-delete

我使用的是SQLite3(版本3.8.6),我在数据库中有一个事务列表。我想DELETE有少于10个关联交易的ID的记录。

我可以用它来列出id及其计数值:

SELECT id,count(id) AS cnt FROM purchases GROUP BY id HAVING cnt < 10;

我尝试将此用于DELETE条记录:

DELETE 
    FROM purchases 
WHERE 
    id IN 
    (SELECT id,count(id) AS cnt FROM purchases GROUP BY id HAVING cnt < 10);

然而,这给了我一个错误:

Error: only a single result allowed for a SELECT that is part of an expression

有没有一种优雅的方法来实现这一目标?

3 个答案:

答案 0 :(得分:1)

试试这个:

DELETE 
    FROM purchases 
WHERE 
    id IN 
    (SELECT id FROM purchases GROUP BY id HAVING count(*) < 10);

答案 1 :(得分:1)

SQLite应该怎么做?

id in (select id, count(id) from ...)

IN运算符需要列表,而不是行集。省略指定的count(id)列并直接在count(*)子句中使用having

id in (select id from purchases group by id having count(*) < 10)

答案 2 :(得分:1)

问题出现在id IN (SELECT id,count(id) AS cnt FROM purchases GROUP BY id HAVING cnt < 10);

您使用了SELECT idcount(id),基本上它会返回2列结果。使用IN关键字时,您需要:id IN '001', '002', '003'...

要解决您的问题,您需要重新排列语法:

DELETE 
FROM purchases 
WHERE 
id IN 
(SELECT id FROM purchases GROUP BY id HAVING count(id) < 10);