ORACLE SQL:如何在Pivot函数中将NULL替换为0

时间:2016-07-06 22:44:45

标签: sql oracle pivot null-coalescing

如何在ORACLE SQL的PIVOT函数中将NULL替换为0? 这是我想写的查询:

SELECT * 
FROM
(
SELECT DISTINCT
    CUSTOMER_ID AS CUSTOMER_ID,
    CASE  
        WHEN CATEGORY_CODE = '01' THEN 'CAT 01'
        WHEN CATEGORY_CODE = '02' THEN 'CAT 02'
        WHEN CATEGORY_CODE = '03' THEN 'CAT 03'
        ELSE 'OTHER' END AS CATEGORY,
    SUM(ORDERS) AS ORDERS
FROM
    TABLE_01
GROUP BY
    CUSTOMER_ID,
    CASE  
        WHEN CATEGORY_CODE = '01' THEN 'CAT_01'
        WHEN CATEGORY_CODE = '02' THEN 'CAT_02'
        WHEN CATEGORY_CODE = '03' THEN 'CAT_03'
        ELSE 'OTHER' END
)
PIVOT
    (
    SUM(ORDERS)
    FOR CATEGORY IN 
        (
        'CAT_01',
        'CAT_02',
        'CAT_03',
        'OTHER'
        )
    )
)
;

我想要的是有一个表,当客户在特定类别上没有任何订单时,它将返回0而不是NULL。像这样:

CUSTOMER_ID   CAT_01   CAT_02   CAT_03
00001              0      100        0
00002            100        0        0
00003              0        0      100

请记住,这是包含多个类别和嵌套查询的复杂查询的一个非常简化的部分。

2 个答案:

答案 0 :(得分:5)

您必须更改顶部查询的select *部分才能单独指定列,以便您可以将它们包含在nvl的调用中。如果您愿意,也可以使用coalesce

select customer_id,
       nvl(cat_01, 0) as cat_01, 
       nvl(cat_02, 0) as cat_02, 
       nvl(cat_03, 0) as cat_03,
       nvl(other, 0) as other
from (... 

答案 1 :(得分:-1)

SELECT CUSTOMER_ID,
NVL(CAT_01,0),
NVL(CAT_02,0)
NVL(   CAT_03   
FROM
(
SELECT DISTINCT
    CUSTOMER_ID AS CUSTOMER_ID,
    CASE  
        WHEN CATEGORY_CODE = '01' THEN 'CAT 01'
        WHEN CATEGORY_CODE = '02' THEN 'CAT 02'
        WHEN CATEGORY_CODE = '03' THEN 'CAT 03'
        ELSE 'OTHER' END AS CATEGORY,
    SUM(ORDERS) AS ORDERS
FROM
    TABLE_01
GROUP BY
    CUSTOMER_ID,
    CASE  
        WHEN CATEGORY_CODE = '01' THEN 'CAT_01'
        WHEN CATEGORY_CODE = '02' THEN 'CAT_02'
        WHEN CATEGORY_CODE = '03' THEN 'CAT_03'
        ELSE 'OTHER' END
)
PIVOT
    (
    SUM(ORDERS)
    FOR CATEGORY IN 
        (
        'CAT_01',
        'CAT_02',
        'CAT_03',
        'OTHER'
        )
    )
)
;