查找与GROUP BY结果相匹配的所有记录HAVING count> SQLite中有1个

时间:2015-01-13 22:16:15

标签: sql sqlite group-by

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个子查询吗?

1 个答案:

答案 0 :(得分:0)

一种方法是加入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 演示