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,基本上,我在Postgresql中定义了mytable id integer, ownername text, length integer, status integer 预期的结果是为每个ownername行创建一个具有以下列的视图 ownername | count_in_status1 | sum_length_status1 | count_in_status2 | sum_length_status2 | count_in_status3 | sum_length_status

基本上,我在Postgresql中定义了mytable

id integer,
ownername text,
length integer,
status integer
预期的结果是为每个ownername行创建一个具有以下列的视图

 ownername  | count_in_status1 | sum_length_status1 | count_in_status2 | sum_length_status2 | count_in_status3 | sum_length_status3 | ..... | total_count | total_sum_length 
这有点难以解释,但基本上我需要一个计数和每个拥有者的总和,最后是一个总计数和长度的总和。目前实际上有5种状态

试过下面的

create view myview as     
select ownername, status, count(*), sum(length) from mytable group by ownername, status

这将返回数据,但不是以我上面介绍的最有效的方式返回。如何实现它?

我想这就是你想要的:

create view myview as     
    select ownername, 
           count(*) filter (where status = 1) as cnt_status_1,
           sum(length) filter (where status = 1) as len_status_1,
           count(*) filter (where status = 2) as cnt_status_2,
           sum(length) filter (where status = 2) as len_status_2,
           . . .  -- continue for each status
           count(*) as cnt,
           sum(length) as length
    from mytable
    group by ownername;

使用
过滤器
是一个优雅的解决方案(请参见@Gordon Linoff响应)

Te与许多数据库更兼容,yan还可以写:

create view myview as     
select ownername,
       sum(case when status = 1 then 1      else 0 end) as cnt_status_1,
       sum(case when status = 1 then length else 0 end) as len_status_1,
       sum(case when status = 1 then 1      else 0 end) as cnt_status_2,
       sum(case when status = 1 then length else 0 end) as len_status_2,           
       . . .  -- continue for each status
       count(*) as cnt,
       sum(length) as length
from mytable
group by ownername;

您不需要状态栏。@没有名字的马。谢谢。事实上,
filter()
是标准的ISO SQL