使用case语句从函数结果中填充零值

时间:2017-02-18 05:26:08

标签: oracle

我在oracle中有这个查询:

WITH LOANS_PRINCIPAL
  AS
  (SELECT 
    MASKAN_RATE.RATE,
    HRS.FN_GETREMIND_BY_DATE(PERSON_DOCK.ID,'2016/01/01') AS PRINCIPAL_DOCK
  FROM
     HRS.TBCONTINUES_PERSON_DOCK PERSON_DOCK
  LEFT JOIN HRS.TBMASKAN_REPAY_CATEGORY MASKAN_REPAY_CAT
  ON MASKAN_REPAY_CAT.ID = PERSON_DOCK.DOCK_REQUEST_DETAIL_ID
  LEFT JOIN HRS.TBFACILITY_MASKAN_RATE MASKAN_RATE
  ON MASKAN_RATE.ID = MASKAN_REPAY_CAT.FACILITY_MASKAN_RATE_ID
  LEFT JOIN HRS.TBFACILITY_MASKAN FACILITY_MASKAN
  ON FACILITY_MASKAN.ID = MASKAN_RATE.FACILITY_MASKAN_ID  
  LEFT JOIN HRS.TBPERSONNEL STAFF
  ON STAFF.ID=FACILITY_MASKAN.PERSONNEL_ID
  WHERE FACILITY_MASKAN.STATE_CODE = 7
  AND STAFF.NO=95801
  AND FACILITY_MASKAN.MASKAN_FACILITY_TYPE_CODE = 4 
  AND PERSON_DOCK.IS_CANCELED_CODE = 2 
  AND PERSON_DOCK.CANCEL_DATE IS NULL
  AND MASKAN_REPAY_CAT.FACILITY_DOCK_TYPE_CODE = 1
  AND FACILITY_MASKAN.FAMILY_ID IS NULL)
  SELECT *
  FROM LOANS_PRINCIPAL
  PIVOT (SUM (PRINCIPAL_DOCK)
  FOR RATE in (4,7,12,13,14,16,10))  

结果是:

(null)245221991 97611272(null)(null)(null)(null)

我需要用零填充这个空值,更喜欢用case语句填充

1 个答案:

答案 0 :(得分:0)

而不是SELECT *(从底部开始的第4行),写下

SELECT case when "4" is null then 0 else "4" end as "4",
       case when "7" is null then 0 else "7" end as "7",
... (etc.)

在大多数情况下,在双引号中使用列名并不是一个好主意(因此使用数字作为列名称不是一个好主意,因为你可以做到这一点的唯一方法是通过双引号)。相反,最好在PIVOT子句中添加别名:

... for rate in (4 as rt_4, 7 as rt_7, ....)

然后

SELECT case when rt_4 is null then 0 else rt_4 end as rt_4, ....

当COALESCE做同样的事情并且更简洁时,也不清楚为什么要使用CASE表达式。 (NVL也是如此,但您可能更喜欢使用SQL标准结构; NVL是专有的Oracle。)

SELECT coalesce (rt_4, 0) as rt_4, ...