mysql - SQL query to compute total number of customers who purchase >4 products on one day -
i want write sql query compute customers have purchased more 4 products on same day.
here tables:
sales (date, customer_id, product_id, units_sold)
products (id, name, price)
customers (id, name)
& here's have far:
select count(s.product_id) total_customers sales s1 datediff(s1.date, s2.date)=0 inner join sales s2 on s1.product_id = s2.product_id having count(s.product_id) > 4;
if want customers have purchased more 4 products on same date:
select distinct s.customer_id sales s group s.customer_id, date(s.date) having count(*) > 4; this 1 of few cases select distinct used group by. if want know dates well, include date(s.date) in select.
note assumes given product purchased customer once on each date. if customer can have multiple records single product on 1 date, use count(distinct product_id) instead of count(*).
to total number of customers, use subquery:
select count(*) (select distinct s.customer_id sales s group s.customer_id, date(s.date) having count(*) > 4 ) c
Comments
Post a Comment