-1

从 myTable 中选择部门,其中联系人为空

   Department    Contact
    ------------- ---------
    Cleaning      Jack
    Admin         Peter
    Software      James
    Cleaning      (null)
    Cleaning      Jill
    Hardware      (null)

在上表中,如何选择联系人为空的部门,不包括现有联系人。

上面的语句将返回“清洁”和“硬件”。

我所期望的只是“硬件”

我怎样才能只选择“硬件”或者有可能。

TIA

4

3 回答 3

2

我认为您只想返回没有任何非空联系人的行。

SELECT
    DISTINCT department
FROM
    myTable
WHERE
    contact IS NULL
    AND department NOT IN (SELECT department FROM myTable where contact IS NOT NULL)

或者,如果您想在没有该IN子句的情况下执行此操作:

SELECT
    DISTINCT a.[department]
FROM
    myTable AS a
LEFT OUTER JOIN
    myTable AS b
        ON b.[department] = a.[department]
        AND b.[contact] IS NOT NULL
WHERE
    a.[contact] IS NULL
    AND b.[contact] IS NULL

NOT NULL使用for 条件进行自连接,然后JOIN通过检查子句NULL来验证失败。WHERE

于 2013-05-14T04:35:56.173 回答
1

听起来您想排除与 ANY 记录中的非空值关联的部门。为此,您应该执行子查询以获取所有非空部门,并将它们从检索空部门的查询中排除。像这样:

SELECT DISTINCT department
FROM mytable
WHERE contact is null 
AND department NOT IN (SELECT department FROM mytable where contact is not null)
于 2013-05-14T04:35:52.390 回答
0
SELECT department,
         SUM(CASE WHEN Contact is not null THEN 1 ELSE 0 END) as count
         from myTable
         group by department
         HAVING count > 0 ;
于 2013-05-14T04:37:53.770 回答