购买了确切2件商品的顾客

时间:2020-03-29 12:44:18

标签: sql postgresql

我有一个名为order_details的表,其中包含3列order_idcustomer_iditem_name

我需要找到那些同时购买了 customer_idKindle

的客户中的Alexa

这是我的桌子的样子。

enter image description here

这些是DML和DDL命令供您参考:

create table personal.order_details(
order_id varchar(10),
customer_id varchar(10),
item_name varchar(10))

insert into personal.order_details values
('1000','C01','Alexa'),
('1000','C01','Kindle'),
('1001','C02','Alexa'),
('1002','C03','Alexa'),
('1002','C03','Kindle')

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用聚合和having子句:

select od.customer_id
from personal.order_details od
where od.item_name in ('Alexa', 'Kindle')    -- rows that have either
group by od.customer_id
having count(distinct od.item_name) = 2;     -- customers that have both