gpt4 book ai didi

sql - 在 Postgres 中选择大小写

转载 作者:行者123 更新时间:2023-11-29 14:38:05 24 4
gpt4 key购买 nike

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

        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;

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

ERROR: syntax error at or near "as"
LINE 1: ... CASE WHEN lower(job)='salesman' THEN count(job) as "SALESM...

如何在选择中使用 case 来创建单独的列?

最佳答案

您需要将计数放在周围 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;

关于sql - 在 Postgres 中选择大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41227931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com