简体   繁体   English

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

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

Basically I have mytable in Postgresql which is defined 基本上我在定义的PostgreSQL中有mytable

id integer,
ownername text,
length integer,
status integer

Intended outcome is to create a view that will have the following columns for each ownername row 预期的结果是创建一个视图,每个所有者名称行将具有以下列

 ownername  | count_in_status1 | sum_length_status1 | count_in_status2 | sum_length_status2 | count_in_status3 | sum_length_status3 | ..... | total_count | total_sum_length 

It's a bit hard to explain but basically I need a count and sum per ownername with a total count and total sum of length at the end. 有点难以解释,但基本上我需要每个所有者名称的计数和总和,最后需要总计数和总长度。 At the moment there are actually 5 statuses 目前,实际上有5种状态

Tried the below 尝试以下

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

This returns the data but not in the most efficient manner that I presented above. 这将返回数据,但不会以我上面介绍的最有效的方式返回。 How to achieve it? 如何实现呢?

I think this is what you want: 我认为这是您想要的:

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;

Using Filter is an elegant solution (see @Gordon Linoff response) 使用Filter是一个很好的解决方案(请参阅@Gordon Linoff响应)

Te be more compatible with many database, yan can also write : 与许多数据库更加兼容,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