SQL Pivot函数的问题

时间:2019-10-18 14:11:53

标签: sql oracle pivot

我有一个SQL查询,其中我尝试将空结果替换为零。我的代码产生错误 [1]:ORA-00923:在预期位置找不到FROM关键字 我正在使用Oracle数据库。

Select service_sub_type_descr,
nvl('Single-occupancy',0) as 'Single-occupancy',
nvl('Multi-occupancy',0) as 'Multi-occupancy'
From 
(select  s.service_sub_type_descr as service_sub_type_descr, ch.claim_id,nvl(ci.item_paid_amt,0) as item_paid_amt
from table_1 ch, table_" ci, table_3 s, table_4 ppd 
where ch.claim_id = ci.claim_id and ci.service_type_id = s.service_type_id 
and ci.service_sub_type_id = s.service_sub_type_id and ch.policy_no = ppd.policy_no) 
Pivot (
count(distinct claim_id), sum(item_paid_amt) as paid_amount For service_sub_type_descr IN ('Single-occupancy', 'Multi-occupancy')
) 

2 个答案:

答案 0 :(得分:3)

此表达式:

 nvl('Single-occupancy',0) as 'Single-occupancy',

使用Oracle定制函数说:如果字符串Single-occupancy'的值不为null,则返回数字0

这种逻辑没有任何意义。字符串值从不为null。并且,返回值有时是字符串,有时是数字。这应该会产生类型转换错误,因为第一个值不能转换为数字。

我认为您打算这样做

coalesce("Single-occupancy", 0) as "Single-occupancy",

双引号用于引用标识符,因此它引用了名为Single-occupancy的列。

所有说明,修复数据模型。没有需要引用的标识符。您可能没有对源数据的控制权,但在查询中肯定拥有控制权:

coalesce("Single-occupancy", 0) as Single_occupancy,

编辑:

只需使用条件聚合和适当的JOIN s来编写查询:

select s.service_sub_type_descr, ch.claim_id,
       sum(case when service_sub_type_descr = 'Single-occupancy' then item_paid_amt else 0 end) as single_occupancy,
       sum(case when service_sub_type_descr = 'Multi-occupancy' then item_paid_amt else 0 end) as multi_occupancy
from table_1 ch join
     table_" ci
     on ch.claim_id = ci.claim_id join
     table_3 s
     on ci.service_type_id = s.service_type_id join
     table_4 ppd 
     on ch.policy_no = ppd.policy_no
group by s.service_sub_type_descr, ch.claim_id; 

我认为简单得多。

答案 1 :(得分:1)

对于列别名,您必须使用双引号!

不要使用

 as 'Single-occupancy'

但是:

 as "Single-occupancy",