5

如何在 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

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

4

2 回答 2

9

您必须更改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 (... 
于 2016-07-06T22:54:30.537 回答
-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'
        )
    )
)
;
于 2019-12-02T10:55:53.903 回答