在Postgres中选择案例

时间:2016-12-19 17:28:25

标签: sql postgresql conditional-aggregation

我正在尝试进行以下咨询:

        Managers | Clerks | Presidents | Analysts | Salesmans
    -------------+---------+--------------+ -----------+-------------

      3            4              1               2               4

到目前为止,我设法做到了:

select  CASE WHEN lower(job)='salesman' THEN count(job) as "SALESMAN"
 WHEN lower(job)='clerk' THEN count(job)  as "CLERK"
 WHEN lower(job)='manager' THEN count(job)  as "MANAGER"
 WHEN lower(job)='analyst' THEN count(job)  as "ANALYST"
 WHEN lower(job)='president' THEN count(job)  as "PRESIDENT"
from emp
group by job;

但是我似乎无法运行它,它会出错:

  

错误:“as”或附近的语法错误   第1行:......当低(工作)='推销员'时计算(工作)为“销售人员......

如何在select中使用大小写来创建单独的列?

1 个答案:

答案 0 :(得分:3)

您需要将计数置于 case

select count(CASE WHEN lower(job)='salesman' THEN 1 END) as "SALESMAN"
       count(CASE WHEN lower(job)='clerk' THEN 1 END) as "CLERK"
       count(case WHEN lower(job)='manager' THEN 1 END) as "MANAGER"
       count(case WHEN lower(job)='analyst' THEN 1 END)  as "ANALYST"
       count(case WHEN lower(job)='president' THEN 1 END) as "PRESIDENT"
from emp;

count()这样的聚合函数会忽略空值。对于与条件不匹配的值,CASE表达式返回NULL,因此不计算这些值。

使用filter子句更简单:

select count(*) filter (where lower(job)='salesman') as "SALESMAN"
       count(*) filter (where lower(job)='clerk') as "CLERK"
       count(*) filter (where lower(job)='manager') as "MANAGER"
       count(*) filter (where lower(job)='analyst')  as "ANALYST"
       count(*) filter (where lower(job)='president') as "PRESIDENT"
from emp;