簡體   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