计算PostgreSQL中枚举类型的计算

时间:2013-12-16 09:20:37

标签: sql postgresql

我有一个PostgreSQLtable结构如下:

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个状态为完成,7个状态为pending,则百分比为30%。

我知道怎样才能在一个SELECT语句中执行此操作,仅提供owner_id?

1 个答案:

答案 0 :(得分: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