繁体   English   中英

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

[英]SQL Server - How to check if a value does not exist in other rows of the same table for same column values?

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

在此处输入图片说明

我需要获得如下输出:

  • 从存在0的TABLE_A获取ID

    我们将得到100、101和102

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

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

    因此,仅剩下101和102

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

    在TABLE_B中,第4行的Exist = 1 for102。因此,无法选择该行

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

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

尝试:

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

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

您可以使用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);

就像@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

这是演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM