2013-12-16 53 views
0

我有一個PostgreSQLtable結構類似這樣:次數計算PostgreSQL中

file(owner_id int, filename text, status status_type) 

與status_type定義:

create type status_type as enum 
(
, 'pending' 
    'complete' 
); 

從這裏,我想實現的是讓百分比多少個文件從相同所有者ID的「完整」+「待處理」集合中具有「完成」狀態。 例如如果我有10個條目,owner_id = 1,3,狀態完成3,狀態7,則百分比爲30%。

任何想法我怎麼能在一個SELECT語句中做到這一點,僅限於owner_id?

回答

2

是這樣的:

select pending_count, 
     complete_count, 
     case 
      when (pending_count + complete_count) = 0 then null 
      else pending_count::decimal/(pending_count + complete_count) 
     end as percentage 

from (
    select sum(case when status = 'pending' then 1 end) as pending_count, 
     sum(case when status = 'complete' then 1 end) as complete_count 
    from file 
    where owner_id = 1 
) t 

你可以用它來得到的百分比爲所有用戶,以及:

select owner_id, 
     pending_count, 
     complete_count, 
     case 
      when (pending_count + complete_count) = 0 then null 
      else pending_count::decimal/(pending_count + complete_count) 
     end as percentage 
from (
    select owner_id, 
     sum(case when status = 'pending' then 1 end) as pending_count, 
     sum(case when status = 'complete' then 1 end) as complete_count 
    from file 
    group by owner_id 
) t 

SQLFiddle例如:http://sqlfiddle.com/#!15/0b341/1這裏

+0

偉大的工作,謝謝,這正是我一直在尋找的! – maephisto