如何找到有多少客户从一张桌子上购买了不止一种东西



表销售:

  create table sales (  
    Date date,  
    customer_id integer,  
    product_id integer,  
    units_sold integer,  
    paid_amount integer  
    );
Insert into sales (Date, customer_id, product_id, units_sold, paid_amount)  
VALUES  
('2016-01-01', '1', '1', '5', '45'),  
('2016-01-01', '2', '1', '2', '18'),  
('2016-01-01', '3', '2', '7', '35'),  
('2016-01-07', '1', '3', '3', '45'),  
('2016-01-07', '2', '2', '5', '25'),  
('2016-01-07', '4', '2', '5', '25'),  
('2016-01-10', '1', '4', '5', '30'),  
('2016-01-10', '2', '4', '5', '30'),  
('2016-01-10', '4', '5', '6', '60'),  
('2016-01-10', '4', '3', '9', '135'),  
('2016-01-14', '3', '1', '4', '60'),  
('2016-01-14', '2', '3', '6', '90'),  
('2016-01-14', '2', '3', '6', '90');  

有多少客户在每次访问时购买了多个不同的产品(即 天(?

你需要

group by并获得喜欢count()

select customer_id, count(distinct product_id) as item_purchased
from sales 
group by "date", customer_id
having count(distinct product_id) > 1;

最新更新