我正在尝试进行以下咨询:
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中使用大小写来创建单独的列?
答案 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;