在 SQLite 中查找与 GROUP BY 结果 HAVING count > 1 匹配的所有记录
Find all records that match a GROUP BY result HAVING count > 1 in SQLite
GROUP BY 和 HAVING 并不是最难的部分。此查询结果摘要:
SELECT date, account, amount, COUNT(1) AS num
FROM "transactions"
GROUP BY date, account, amount
HAVING num > 1
类似于:
date account amount num
2011-02-07 580416690 -6.4 2
2011-07-19 -50.0 2
2011-08-29 2445588 -22.0 2
2011-12-16 265113334 -0.1 3
但我不想要摘要(4 条记录)。我想要所有相关记录(所以 2 + 2 + 2 + 3 = 9 条记录)。如果 GROUP BY 在 1 列上,那也不难,但是有 3 列...
如何获取具有这些值的实际记录? 1 个查询必须是可能的。我需要 3 个子查询吗?
一种方法是重新加入 transactions
SELECT *
FROM transactions t JOIN
(
SELECT date, account, amount
FROM transactions
GROUP BY date, account, amount
HAVING COUNT(*) > 1
) d
ON (t.date = d.date
AND t.account = d.account
AND t.amount = d.amount) OR
(t.date = d.date
AND t.account IS NULL AND d.account IS NULL
AND t.amount = d.amount)
这是一个SQLFiddle演示
GROUP BY 和 HAVING 并不是最难的部分。此查询结果摘要:
SELECT date, account, amount, COUNT(1) AS num
FROM "transactions"
GROUP BY date, account, amount
HAVING num > 1
类似于:
date account amount num
2011-02-07 580416690 -6.4 2
2011-07-19 -50.0 2
2011-08-29 2445588 -22.0 2
2011-12-16 265113334 -0.1 3
但我不想要摘要(4 条记录)。我想要所有相关记录(所以 2 + 2 + 2 + 3 = 9 条记录)。如果 GROUP BY 在 1 列上,那也不难,但是有 3 列...
如何获取具有这些值的实际记录? 1 个查询必须是可能的。我需要 3 个子查询吗?
一种方法是重新加入 transactions
SELECT *
FROM transactions t JOIN
(
SELECT date, account, amount
FROM transactions
GROUP BY date, account, amount
HAVING COUNT(*) > 1
) d
ON (t.date = d.date
AND t.account = d.account
AND t.amount = d.amount) OR
(t.date = d.date
AND t.account IS NULL AND d.account IS NULL
AND t.amount = d.amount)
这是一个SQLFiddle演示