简体   繁体   中英

Find all records that match a GROUP BY result HAVING count > 1 in SQLite

The GROUP BY and HAVING isn't the hard part. This query results the summary:

SELECT date, account, amount, COUNT(1) AS num
FROM "transactions"
GROUP BY date, account, amount
HAVING num > 1

Something like:

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

But I dont want the summary (4 records). I want all the relevant records (so 2 + 2 + 2 + 3 = 9 records). If the GROUP BY was on 1 column, that wouldn't be hard either, but with 3 columns...

How do I get the actual records with those values? 1 query must be possible. Do I need 3 subqueries?

One way to do it is to join back to 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)

Here is a SQLFiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM