卡在Oracle的查询中

我有一张桌子,

卡在Oracle的查询中

我的预期输出是(10,20,30是deptno):

卡在Oracle的查询中

所以我这样尝试:

select job,case 
                when deptno=10 then sum(sal) else null
                end dept_10_data,case 
                when deptno=20 then sum(sal) else null
                end dept_20_data,case 
                when deptno=30 then sum(sal) else null
                end dept_30_data       
 from ot.employee group by job;

但是我收到以下错误消息:

ORA-00979: not a GROUP BY expression

如何获得此输出?

themoonsky2009 回答:卡在Oracle的查询中

您快到了。您需要将case表达式放在内的聚合函数中。在这里,您要使用sum()

select 
    job,sum(case when deptno = 10 then sal end) dept_10_data,sum(case when deptno = 20 then sal end) dept_20_data,sum(case when deptno = 30 then sal end) dept_30_data
from ot.employee 
group by job;
,

您围绕错误的方式进行条件汇总。您应该先将条件应用于数据,然后再进行汇总,例如:

SELECT job,SUM(case when deptno = 10 then sal end) dept_10_data,...
FROM   ot.employee
GROUP BY job;

如果deptno不是指定值,则我没有包含默认值,因为大多数聚合函数(包括SUM)都会忽略NULL值。

,

由于在select子句中使用了直接列(没有aggregate函数)而没有在group by子句中提及它们,您遇到了错误。 (如两个答案中所述)。

但是您也可以将PIVOT用于以下相同的输出:

Select * from
(Select job,deptno,sal from ot.employee)
Pivot
(Sum(sal) for deptno in (10,20,30))

干杯!

本文链接:https://www.f2er.com/3165253.html

大家都在问