SQL Server-如何检查同一列值的相同表的其他行中是否不存在值?

时间:2018-08-29 17:05:39

标签: sql sql-server

以下是SQL Server中的两个表:TABLE_A和TABLE_B

enter image description here

我需要获得如下输出:

  • 从存在= 0的TABLE_A获取ID

    我们将获得100、101和102

  • 现在,在100、101和102中,没有其他具有相同ID值的行(在同一表中)具有Exist = 1

    因此,由于第二行中Exist = 1,因此无法选择100。

    因此,仅剩101和102

  • 使用剩余的ID值(101和102),对照TABLE_B中的ID列进行检查,其中“存在”列的值在任何行中均不应等于“ 1”

    在TABLE_B中,第4行的Exist = 1等于102。因此,无法选择

    我们现在只有101个。这是必需的输出,应该选择。

能否让我知道如何编写最简单的查询来实现这一目标?让我知道这个问题是否需要改进。

3 个答案:

答案 0 :(得分:1)

尝试:

SELECT
    ID,
    SUM(CAST(Exist AS int)) AS [Exists]
FROM
    TABLE_A
GROUP BY ID
HAVING SUM(CAST(Exist AS bit)) = 0

将为您提供第一部分的答案。然后,您可以JOIN进行类似TABLE_B的查询。这是显示其工作方式的“简单”方法。您可以像@Yogest Sharma一样编写更复杂的查询

答案 1 :(得分:1)

您可以使用existsnot exists

with t as (
     select t1.*
     from t1
     where exists (select 1 from t1 t11 where t11.id = t1.id and t11.exists = 0) and
           not exists (select 1 from t1 t11 where t11.id = t1.id and t11.exists = 1)
)

select t.*
from t
where not exists (select 1 from t2 where t.id = t2.id and t2.exists = 1);

答案 2 :(得分:1)

就像@Peter Smith提到的那样,可以使用聚合函数SUM。请注意,您将需要强制转换,因为您不能在具有BIT数据类型的字段上使用聚合函数

;WITH CTE AS
(
SELECT ID, SUM(CAST(Exist AS INT)) AS AggExist FROM TABLE_A GROUP BY ID
UNION
SELECT ID, SUM(CAST(Exist AS INT)) As AggExist FROM TABLE_B GROUP BY ID
)
SELECT ID, SUM(AggExist) FROM CTE GROUP BY ID
HAVING SUM(AggExist) = 0

这里是demo