Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 将数字列拆分为多列_Sql_Postgresql_Pivot - Fatal编程技术网

Sql 将数字列拆分为多列

Sql 将数字列拆分为多列,sql,postgresql,pivot,Sql,Postgresql,Pivot,我有一个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 val

我有一个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
输出:

如何将“拆分状态”列的查询更改为“所有类别值”“状态有5个唯一值”

我使用postgresql


谢谢大家!

您可以使用条件聚合,在Postgres中,最好使用过滤器:


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

编辑您的问题,以便清楚列的来源。谢谢!我稍微编辑了一下您的查询,因为我会得到每个状态下有多少帐户:选择值、countdistinct owner_id作为所有者、countdistinct owner_id筛选器,其中status=1作为status_1。。。countdistinct owner\u id筛选器,其中status=5作为status\u 5来自accounts\u login\u history alh左加入a.id=alh.owner\u id,其中date>='2020-02-01'和owner\u type=1按值分组;
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;