Hi have a table like this : invoice_type have only three value "direct","promotion" or "giftcode"
i want to result like this:
my code is:
SELECT table1.user_id, count_direct,count_promotion,count_giftcode,direct_plan, promotion_plan, giftcode_plan
from (SELECT invoices_map.user_id,
sum(CASE WHEN invoice_type='direct' THEN 1 ELSE 0 END) as count_direct,
sum(CASE WHEN invoice_type='promotion' THEN 1 ELSE 0 END) as count_promotion,
sum(CASE WHEN invoice_type='giftcode' THEN 1 ELSE 0 END) as count_giftcode,
FROM payment.invoices_map
group by user_id) as table1
left join (Select user_id,array_agg(distinct plan_type) as direct_plan
from payment.invoices_map
where plan_type= 'direct'
group by user_id) as direct_plan_tb on table1.user_id = direct_plan_tb.user_id
left join (Select user_id,array_agg(distinct plan_type) as
from payment.invoices_map
where plan_type= 'promotion'
group by user_id) as promotion_plan_tb on table1.user_id = promotion_plan_tb.user_id
left join (Select user_id,array_agg(distinct plan_type) as
from payment.invoices_map
where plan_type= 'giftcode'
group by user_id) as giftcode_plan_tb on table1.user_id = giftcode_plan_tb.user_id
It shows correct answer but I want to optimize my code