找出SQL表是否包含没有“标记”记录的条目

时间:2014-12-10 23:09:37

标签: mysql sql aggregate-functions

我有一个MySQL地址表,其中包含以下列:

STATE, ZIPCODE, FLAG

给定state/zipcode组合可以有多行。我想确保对于每个给定的state/zipcode组合,只有一行有FLAG = 'P'

我知道如何检查多行:

SELECT state, zipcode, flag, count(*) as numrecs
FROM addresses
WHERE flag = 'P'
group by state, zipcode
having numrecs > 1;

如何检查零条目 - state/zipcode组合中没有flag = 'P'的行?

2 个答案:

答案 0 :(得分:1)

你走在正确的轨道上,只需使用条件聚合:

SELECT state, zipcode, flag, count(*) as numrecs
FROM addresses
GROUP BY state, zipcode
HAVING coalesce(sum(flag = 'P'), 0) <> 1

或者,如果您愿意:

HAVING coalesce(sum(flag = 'P'), 0) = 0 or sum(flag = 'P') > 1

如果coalesce()可以是flag,并且给定的州/邮政编码组合只有NULL个标记,则需要NULL

答案 1 :(得分:0)

此查询应该为您提供违反标准的内容:

SELECT STATE, ZIPCODE, SUM(FLAG_COUNTER)
FROM (SELECT *, IF(FLAG='P', 1, 0) AS FLAG_COUNTER FROM addresses) tableWithCounter
GROUP BY STATE, ZIPCODE
HAVING SUM(FLAG_COUNTER) != 1