SQL SSMS Select 子句有 2 个 where 函数用于同一字段

SQL SSMS Select clause with 2 where functions for same field

我想找到在同一次购买中同时购买了一块水果和一块巧克力的客户。我的数据如下所示:

ID         purchase_date    product
22212      2021-06-03       Fruit
111999     2021-06-03       Fruit
111999     2021-06-03       Chocolate
56727      2019-05-03       Bread
30726      2019-05-03       Fruit
30761      2019-05-03       Chocolate
53899      2019-05-03       Fruit

我想要这个:

  ID         purchase_date
  111999     2021-06-03

我尝试了一个带有 where 子句的 select 函数,但它没有返回任何记录。有什么想法吗?

SELECT ID, purchase_date
From dbo.mytable
where product='Fruit' AND product='Chocolate'
Group by ID, purchase_date

编辑 - 有谁知道我如何找到只在交易中购买水果的人?

如果我没理解错的话,你可以尝试在HAVING

中写聚合条件函数
SELECT ID,purchase_date    
FROM dbo.mytable
GROUP BY  ID,purchase_date    
HAVING 
    COUNT(CASE WHEN product='Fruit' THEN 1 END) > 0 
AND
    COUNT(CASE WHEN product='Chocolate' THEN 1 END) > 0 

一种方法是在 HAVING:

中使用条件 COUNT
SELECT ID,
       Purchase_date
FROM dbo.MyTable
GROUP BY ID,
         Purchase_date
HAVING COUNT(DISTINCT CASE WHEN product IN ('Fruit','Chocolate') THEN product END) = 2;

您的数据

declare @a TABLE (
   ID            int  NOT NULL 
  ,purchase_date DATE  NOT NULL
  ,product       VARCHAR(9) NOT NULL
);
INSERT INTO @a(ID,purchase_date,product) VALUES (22212,'2021-06-03','Fruit');
INSERT INTO @a(ID,purchase_date,product) VALUES (111999,'2021-06-03','Fruit');
INSERT INTO @a(ID,purchase_date,product) VALUES (111999,'2021-06-03','Chocolate');
INSERT INTO @a(ID,purchase_date,product) VALUES (56727,'2019-05-03','Bread');
INSERT INTO @a(ID,purchase_date,product) VALUES (30726,'2019-05-03','Fruit');
INSERT INTO @a(ID,purchase_date,product) VALUES (30761,'2019-05-03','Chocolate');
INSERT INTO @a(ID,purchase_date,product) VALUES (53899,'2019-05-03','Fruit');

您的最终查询

with t as(
select ID, purchase_date,STRING_AGG( product,',') products  from @a
group by ID,purchase_date)

select ID,purchase_date from t
where products like N'%Chocolate%' and  products like N'%Fruit%' 

还有另一种选择,因为许多人似乎忽略或忘记了集合运算符。

select ID, purchase_date from dbo.mytable where product='Fruit' 
intersect
select ID, purchase_date from dbo.mytable where product='Chocolate';

请注意缺少 ORDER BY 子句。如果顺序很重要(通常确实如此),那么您必须包含一个 ORDER BY 子句。