简体   繁体   English

如何在 postgresql 中创建 pivot 表

[英]how to create pivot table in postgresql

Hi have a table like this: invoice_type have only three value "direct","promotion" or "giftcode"嗨有一个这样的表:invoice_type 只有三个值“direct”、“promotion”或“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它显示了正确的答案,但我想优化我的代码

You can simplify this to a single statement using conditional aggregation.您可以使用条件聚合将其简化为单个语句。

However, this part of your derived tables:但是,您的派生表的这一部分:

array_agg(distinct plan_type) as direct_plan
...
where plan_type= 'direct' 

seems wrong because the aggregated column and the filter column are identical.似乎是错误的,因为聚合列和过滤列是相同的。 I assume you actually meant to aggregate the plan_type column and filter on the invoice_type column (at least after looking at the screen shots).我假设您实际上打算聚合plan_type列并在invoice_type列上进行过滤(至少在查看屏幕截图之后)。

So the simplified statement would look like this:所以简化的语句看起来像这样:

SELECT im.user_id,
       array_agg(distinct im.plan_type) filter (where im.invoice_type = 'direct') as direct_plan,
       array_agg(distinct im.plan_type) filter (where im.invoice_type = 'promotion') as promotion_plan,
       array_agg(distinct im.plan_type) filter (where im.invoice_type = 'giftcode') as giftcode_plan,
       count(*) filter (where invoice_type = 'direct') as count_direct,
       count(*) filter (where invoice_type = 'promotion') as count_promotion,
       count(*) filter (where invoice_type = 'giftcode') as count_giftcode,
FROM payment.invoices_map im
group by user_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM