【问题标题】:T-SQL select if person has product A but not both A and BT-SQL 选择人是否有产品 A 但不是 A 和 B
【发布时间】:2016-10-17 03:20:54
【问题描述】:

我不确定如何实现这一点。我想获得拥有“ProductA”的人,而不是拥有“ProductA”和“ProductB”的人。

预期输出:

CustomerID | Product
--------------------
         1 | ProductA
         2 | ProductA
         3 | ProductA
         6 | ProductA
         7 | ProductA

表:

CREATE TABLE #TempTable 
(
     CustomerID INT,
     Product    VARCHAR(50)
)

INSERT INTO #TempTable (CustomerID, Product)
VALUES
  ('1', 'ProductA'),
  ('2', 'ProductA'),
  ('3', 'ProductA'),
  ('4', 'ProductA'),
  ('4', 'ProductB'),
  ('6', 'ProductA'),
  ('7', 'ProductA');

【问题讨论】:

    标签: sql-server tsql


    【解决方案1】:

    我会在这里对每个客户使用条件聚合,只检查客户是否至少购买了一次A,但没有购买B

    SELECT CustomerID
    FROM #TempTable
    GROUP BY CustomerID
    HAVING SUM(CASE WHEN Product = 'ProductA' THEN 1 ELSE 0 END) > 0 AND
           SUM(CASE WHEN Product = 'ProductB' THEN 1 ELSE 0 END) = 0
    

    【讨论】:

    • @Joni 这是正确的答案。它将允许其他组合。
    【解决方案2】:
    SELECT C1.CustomerID
    FROM #TempTable C1 
    LEFT JOIN #TempTable C2  
    ON C2.ID = C1.ID 
    AND C2.Product = 'ProductB'
    where C2.ID is null
    AND C1.Product = 'ProductA'
    

    【讨论】:

      【解决方案3】:

      CustomerID 分组,您可以检查可用的最小和最大Product 是否相同,这应该是您要查找的,实际上是“ProductA”:

      SELECT 
        CustomerID,
        min(Product)
      FROM TempTable
      GROUP BY CustomerID
      HAVING 1=1
        AND min(Product) = 'ProductA'
        AND max(Product) = 'ProductA'
      ;
      

      【讨论】:

        【解决方案4】:

        使用 PIVOT:

        WITH CTE
        AS
        (
            Select CustomerID, [ProductA], [ProductB] from #TempTable
            PIVOT
            (
            MAX(Product) FOR Product IN ([ProductA], [ProductB])
            ) p
            WHERE [ProductB] IS NULL
        )
        Select CustomerID, [ProductA] as Product
        from CTE
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-10-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-29
          相关资源
          最近更新 更多