繁体   English   中英

如何在SQL视图中将计数和总和表示为列?

[英]How to represent groups of counts and sums as columns in a SQL view?

基本上我在定义的PostgreSQL中有mytable

id integer,
ownername text,
length integer,
status integer

预期的结果是创建一个视图,每个所有者名称行将具有以下列

 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;

使用Filter是一个很好的解决方案(请参阅@Gordon Linoff响应)

与许多数据库更加兼容,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;

暂无
暂无

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

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