繁体   English   中英

将数字列拆分为多列

[英]Split numeric column into multiple columns

我有 SQL 查询,它从两个表中对所有者及其状态进行分组:

select value, count(distinct owner_id) as owners, account.status
from accounts_login_history
left join accounts on accounts.id = accounts_login_history.owner_id
where date >= '2020-02-01'
and owner_type = 1
group by value, accounts.status

输出:

在此处输入图片说明

我应该如何将拆分status列的查询更改为所有分类值(状态有 5 个唯一值)?

在此处输入图片说明

我使用 postgresql。

谢谢!

您可以使用条件聚合,在 Postgres 中最好使用filter来完成:

select value, count(distinct owner_id) as owners,
       max(a.status) filter (where status = 1) as status_1,
       max(a.status) filter (where status = 2) as status_2,
       max(a.status) filter (where status = 3) as status_3,
       max(a.status) filter (where status = 4) as status_4,
       max(a.status) filter (where status = 5) as status_5
from accounts_login_history alh left join
     accounts a 
     on accounts.id = alh.owner_id
where date >= '2020-02-01' and
      owner_type = 1
group by value;

这将为缺失值返回null而不是0 您当然可以使用coalesce()将其更改为0 但是,我更喜欢null

暂无
暂无

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

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