【问题标题】:Issue With SQL Pivot FunctionSQL Pivot 函数的问题
【发布时间】:2019-10-18 14:11:53
【问题描述】:

我有一个 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')
) 

【问题讨论】:

    标签: sql oracle pivot


    【解决方案1】:

    这个表达式:

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

    正在使用 Oracle 定制函数来表示:如果字符串 Single-occupancy' 的值不为空,则返回数字 0

    这个逻辑真的没有道理。字符串值永远不会是null。而且,返回值有时是字符串,有时是数字。这应该会产生类型转换错误,因为第一个值无法转换为数字。

    我想你打算:

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

    双引号用于引用标识符,所以这指的是名为Single-occupancy的列。

    说了这么多,修复你的数据模型。没有需要引用的标识符。您可能无法控制源数据,但您肯定可以控制查询:

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

    编辑:

    只需使用条件聚合和正确的JOINs 编写查询:

    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]: ORA-00904: "Multi-occupancy": invalid identifier
    • 这个查询对我来说不是用 0 替换空格。我只是运行它,仍然得到空白
    【解决方案2】:

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

    不要使用

     as 'Single-occupancy'
    

    但是:

     as "Single-occupancy",
    

    【讨论】:

    • 谢谢,我现在有不同的错误信息? [1]: ORA-00904: "SERVICE_SUB_TYPE_DESCR": 无效标识符
    • 最好使用 Single_occupancy 和 Multi_occupancy 作为列别名(“as”之后的部分),不应更改带有“IN ('Single-occupancy', 'Multi-occupancy')”的部分我猜。
    • 在带有“s.service_sub_type_descr as service_sub_type_descr”的部分,您可以删除“as service_sub_type_descr”,因为您正在重复使用相同的名称,因此在此处添加别名是没有用的。
    • 我删除了 as service_sub_type_descr 和同样的东西
    • 老实说,您的查询有几个奇怪的部分。选择 service_sub_type_descr, nvl('Single-occupancy',0) as 'Single-occupancy', nvl('Multi-occupancy',0) as 'Multi-occupancy' => nvl('something',0) 将始终给出你'某事',你还必须使用列或表达式作为 nvl 函数的第一个参数。至于 PIVOT 功能,我不是这方面的专家
    猜你喜欢
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多