【问题标题】:Find all records that match a GROUP BY result HAVING count > 1 in SQLite在 SQLite 中查找与 GROUP BY 结果 HAVING count > 1 匹配的所有记录
【发布时间】:2015-01-13 22:16:15
【问题描述】:

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

【问题讨论】:

  • 加入原表。

标签: sql sqlite group-by


【解决方案1】:

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

【讨论】:

  • 这不适用于NULL... account 有时是NULL 并且它们也必须与td 匹配。也许是 SQLite,也许是正常的,但显然是 NULL != NULL
  • @MikeSherrill'CatRecall' 设计错误是什么?我的数据库有 NIL?按 NIL 分组?查询 NIL 列?
  • @Rudie:允许帐号为 NULL 听起来像是设计错误。
  • @peterm:coalesce(account, 'no account') 可能比在 WHERE 子句中添加条件更好。
  • @Rudie 查看更新。虽然我必须管理 account 的 NULL 似乎至少很奇怪......
猜你喜欢
  • 2019-07-07
  • 1970-01-01
  • 1970-01-01
  • 2012-02-17
  • 1970-01-01
  • 2020-09-23
  • 2016-11-12
  • 1970-01-01
  • 2016-07-23
相关资源
最近更新 更多