【发布时间】:2012-11-28 12:12:39
【问题描述】:
我有一个表 a 有两个字段:id (PK) 和 f。
考虑以下记录:
id | f
1 | NULL
2 | 'foo'
3 | 'bar'
4 | NULL
5 | 'foo'
6 | 'baz'
我想检索并计算所有具有不同 f 值的记录,包括每条记录 WHERE f IS NULL。鉴于此条件,查询应返回除 #5 之外的所有记录,因为同一值已包含在集合中,总计数为 5。
我用来检索所有记录的查询如下所示:
SELECT CASE WHEN EXISTS (SELECT id FROM a a2 WHERE a2.f = a.f AND a.id < a2.id) THEN 1 END AS not_distinct FROM a HAVING not_distinct IS NULL
如果可以改进此查询,我欢迎任何反馈。无论如何,主要问题是计数。显然添加COUNT(*) 在这里无济于事,我完全不知道如何在过滤后计算记录。
【问题讨论】:
-
您能否提供您希望以 o/p 形式获得的示例数据?
-
@AjithSasidharan:问题已经很清楚了:
the query should return every record except #5, because the same value is already included in the set, and the total count would be 5. -
是的,现在就去要求。
标签: mysql sql count null aggregate-functions