简体   繁体   中英

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

Basically I have mytable in Postgresql which is defined

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

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)

Te be more compatible with many database, yan can also write :

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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