SQL query for finding records where count > 1
我有一个名为
更新:此外,应该有一个过滤器,而不是只计算邮政编码不同的记录。
这就是表格的样子:
1 2 3 4 5 6 7 8 | | user_id | account_no | zip | DATE | | 1 | 123 | 55555 | 12-DEC-09 | | 1 | 123 | 66666 | 12-DEC-09 | | 1 | 123 | 55555 | 13-DEC-09 | | 2 | 456 | 77777 | 14-DEC-09 | | 2 | 456 | 77777 | 14-DEC-09 | | 2 | 789 | 77777 | 14-DEC-09 | | 2 | 789 | 77777 | 14-DEC-09 | |
结果看起来应该类似于:
1 2 | | user_id | COUNT | | 1 | 2 | |
你会如何在SQL查询中表达这一点? 我在想自己加入,但由于某种原因,我的计数是错误的。
使用HAVING子句和GROUP By使行唯一的字段
以下将找到
all users that have more than one payment per day with the same account number
1 2 3 4 5 6 7 8 9 10 11 | SELECT user_id , COUNT(*) COUNT FROM PAYMENT GROUP BY account, user_id , DATE HAVING COUNT(*) > 1 |
更新
如果您只想包含具有不同ZIP的那些,您可以先获得一个不同的集合,然后执行HAVING / GROUP BY
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | SELECT user_id, account_no , DATE, COUNT(*) FROM (SELECT DISTINCT user_id, account_no , zip, DATE FROM payment ) payment GROUP BY user_id, account_no , DATE HAVING COUNT(*) > 1 |
试试这个查询:
1 2 3 4 | SELECT column_name FROM TABLE_NAME GROUP BY column_name HAVING COUNT(column_name) = 1; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | CREATE TABLE payment( user_id INT(11), account INT(11) NOT NULL, zip INT(11) NOT NULL, dt DATE NOT NULL ); INSERT INTO payment VALUES (1,123,55555,'2009-12-12'), (1,123,66666,'2009-12-12'), (1,123,77777,'2009-12-13'), (2,456,77777,'2009-12-14'), (2,456,77777,'2009-12-14'), (2,789,77777,'2009-12-14'), (2,789,77777,'2009-12-14'); SELECT foo.user_id, foo.cnt FROM (SELECT user_id,COUNT(account) AS cnt, dt FROM payment GROUP BY account, dt) foo WHERE foo.cnt > 1; |
我不推荐新手的
我不清楚这个表的关键是什么(它是完全标准化的,我想知道吗?),因此我发现很难遵循你的规范:
I would like to find all records for all users that have more than one
payment per day with the same account number... Additionally, there
should be a filter than only counts the records whose ZIP code is
different.
所以我采取了字面解释。
以下是更详细,但可能更容易理解,因此维护(我已经使用CTE表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | WITH PAYMENT_TALLIES (user_id, zip, tally) AS ( SELECT user_id, zip, COUNT(*) AS tally FROM PAYMENT GROUP BY user_id, zip ) SELECT DISTINCT * FROM PAYMENT AS P WHERE EXISTS ( SELECT * FROM PAYMENT_TALLIES AS PT WHERE P.user_id = PT.user_id AND PT.tally > 1 ); |