【问题标题】:SQL Select where a column contains one value but not another in another rowSQL 选择其中一列包含一个值但在另一行中不包含另一个值
【发布时间】:2022-11-10 18:18:46
【问题描述】:

我在下图中有这张桌子。 我正在尝试选择 DestinationSystemID 为“11”的所有行,其中具有相同 SupplierPartyID 的其他行也没有 DestinationSystemID“16”。

例如,在下表中,应选择以下行,因为它们的行的 DestinationSystem 为 11,但不是 16:

  • 7300009017706
  • 7300009043088
  • 7330509000502

不应选择以下选项,因为它同时具有 DestinationSystemID 11 和 16:

  • 7318270000006

我希望你明白我想在这里问什么。

我已尝试搜索解决方案,但无法正确查询问题以找到解决方案。

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    NOT EXISTS 非常适合这个:

    SELECT {explicit t.columns}
      FROM dbo.YourTableName AS t
      WHERE t.DestinationSystemID = 11
        AND NOT EXISTS
        (
          SELECT 1 FROM dbo.YourTableName AS t2
            WHERE t2.SupplierPartyID = t.SupplierPartyID
              AND t2.DestinationSystemID = 16
        );
    

    【讨论】:

    • 谢谢,这工作得很好。
    【解决方案2】:

    NOT IN 也可以将此作为另一种选择:

    SELECT * FROM test a
    WHERE DestinationSystemID = 11 
    AND SupplierPartyID NOT IN (SELECT SupplierPartyID
                                FROM   test b
                                WHERE  a.SupplierPartyID = a.SupplierPartyID
                                AND b.DestinationSystemID = 16) 
    

    小提琴here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-21
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 2018-10-18
      • 2021-09-21
      • 1970-01-01
      • 2014-12-16
      相关资源
      最近更新 更多