TSQL Counting Nulls - 所有分组项都具有NULL字段

时间:2014-04-03 05:06:52

标签: sql sql-server tsql

试着围绕所需的逻辑/命令:

我有一个联系人表。每个联系人都以多对一的方式拥有一个客户。 我正在尝试获取任何所有联系人都具有电子邮件NULL值的clientID。

示例数据:

ContactID   EmailAddress    ClientID
1           NULL                3
907         NULL                3
2468        NULL                3
2469        email@email.com     4
1077        NULL                4
908         email@email.com     4
2           email@email.com     4
3           email@email.com     5
909         email@email.com     5

谢谢!

3 个答案:

答案 0 :(得分:7)

您可以使用分组聚合和HAVING子句执行此操作(假设空白电子邮件地址可以与空值相同):

SELECT 
    ClientID
    FROM ClientEmails
    GROUP BY ClientID
    HAVING MAX(LEN(ISNULL(EmailAddress, ''))) = 0;

SqlFiddle

答案 1 :(得分:7)

这会有帮助吗?

select *
from
(
select clientId, 
COUNT(emailAddress) as Mailz, 
COUNT(contactId) as Contacts
from contacts
group by clientId
) as src
where (Mailz = 0 and contacts > 0)

答案 2 :(得分:2)

请尝试:

SELECT 
    ClientID
FROM(
    SELECT 
        ClientID, 
        SUM(CASE WHEN EmailAddress IS NULL THEN 1 ELSE 0 END) a,
        COUNT(*) b
    FROM YourTable
    GROUP BY ClientID
)x WHERE a=b