【问题标题】:SQL Server - How to check if a value does not exist in other rows of the same table for same column values?SQL Server - 如何检查同一表的其他行中是否不存在相同列值的值?
【发布时间】:2018-08-29 17:05:38
【问题描述】:

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

我需要得到如下输出:

  • 从 Exist = 0 的 TABLE_A 中获取 ID

    我们会得到 100、101 和 102

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

    因此,无法选择 100,因为它在第二行中有 Exist = 1。

    所以,只剩下 101 和 102 个

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

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

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

您能告诉我如何编写最简单的查询来实现这一点吗?如果问题需要改进,请告诉我。

【问题讨论】:

  • 你能不能展示一下你到目前为止所做的尝试。你有没有尝试过什么?列数据类型有哪些?
  • ID 是 int 而 Exist 是 bit
  • 我试过但坚持检查同一个表中存在 Exist=1 的其他行

标签: sql sql-server


【解决方案1】:

你可以使用exists & not 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);

【讨论】:

  • 谢谢。有效。 ;with cte as ( select one.* from table_a one where exists (select 1 from table_a two where two.id = one.id and two.exist = 0) 不存在 (select 1 from table_a two where two.id = one .id and two.exist = 1) ) select * from cte where not exists(select 1 from table_b b where cte.id = b.id and b.exist = 1);
【解决方案2】:

试试:

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 那样编写更复杂的查询

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多