I have this table called s2s_actions:
id brand_id event_type
------ -------- ----------
22 361 0
29 361 1
35 7 1
40 7 0
41 37 1
42 37 0
43 37 1
and I want to get the count of event_type=0 and count of event_type=1 for each brand_id:
SELECT s2s_actions.brand_id, deposits.deposit_amount, signups.signup_amount
FROM
s2s_actions,
(SELECT COUNT(*) AS signup_amount FROM s2s_actions WHERE brand_id=s2s_actions.brand_id AND event_type=0) signups,
(SELECT COUNT(*) AS deposit_amount FROM s2s_actions WHERE brand_id=s2s_actions.brand_id AND event_type=1) deposits
GROUP BY brand_id
If I put a number in the inner selects (like 37), this works ok, but I can’t use the brand_id of the outer group…
Any ideas?
2
Answers
The subqueries calculate the counts for
event_type=0
andevent_type=1
separately, grouping them by thebrand_id
.The main query joins these subqueries using the
brand_id
as the common column.This is using
conditional aggregation
, which is a great option for your particular need.And if you have brand id’s without those targeted events and want to display zero rather than null in your results, then coalesce those two rows of code…