如何找到有多少顾客从桌子上购买多件东西

时间:2017-03-24 12:20:31

标签: sql postgresql

表销售:

  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');  

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

1 个答案:

答案 0 :(得分:2)

您需要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;