Answer the question
In order to leave comments, you need to log in
How to write a subquery in a grouping query?
Friends, tell me please, I can’t figure out how to write the following query:
There is a table: sales
id INT
total_sum decimal
type varchar
event_date timestamp
...
sale_id int
quantity decimal
...
select
DATE(event_date),
COUNT(*) sales_count,
COUNT(IF(type = 'refund', 1, NULL)) refunds_count,
SUM(IF(type = 'sale', total_sum, 0)) revenue,
AVG(IF(type = 'sale', total_sum, NULL)) avg_check,
# (select count(*) from sale_items where sale_id=sales.id) as sale_items_count
from sales
group by DATE(event_date);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question