2017-02-14 53 views
0

有人可以告訴我如何做到這一點?如何填寫模擬數據的列值爲null

比方說,我已經得到了以下結果:

APP ¦ DAY ¦ PERCENT 
------------------------ 
JKL ¦ 2017-02-05 ¦ 
JKL ¦ 2017-02-06 ¦ 
JKL ¦ 2017-02-07 ¦ 78 
JKL ¦ 2017-02-08 ¦ 
JKL ¦ 2017-02-09 ¦ 64 
JKL ¦ 2017-02-10 ¦ 
JKL ¦ 2017-02-11 ¦ 
TZU ¦ 2017-02-05 ¦ 97 
TZU ¦ 2017-02-06 ¦ 
TZU ¦ 2017-02-07 ¦ 
TZU ¦ 2017-02-08 ¦ 24 
TZU ¦ 2017-02-09 ¦ 23 
TZU ¦ 2017-02-10 ¦ 
TZU ¦ 2017-02-11 ¦ 
UIO ¦ 2017-02-05 ¦ 
.. 
. 

我想上面的結果轉換成這樣:

APP ¦ DAY ¦ PERCENT 
---------------------- 
JKL ¦ 2017-02-05 ¦ 100 
JKL ¦ 2017-02-06 ¦ 100 
JKL ¦ 2017-02-07 ¦ 78 
JKL ¦ 2017-02-08 ¦ 78 
JKL ¦ 2017-02-09 ¦ 64 
JKL ¦ 2017-02-10 ¦ 64 
JKL ¦ 2017-02-11 ¦ 64 
TZU ¦ 2017-02-05 ¦ 97 
TZU ¦ 2017-02-06 ¦ 97 
TZU ¦ 2017-02-07 ¦ 97 
TZU ¦ 2017-02-08 ¦ 24 
TZU ¦ 2017-02-09 ¦ 23 
TZU ¦ 2017-02-10 ¦ 23 
TZU ¦ 2017-02-11 ¦ 23 
UIO ¦ 2017-02-05 ¦ 100 
.. 
. 

所以我需要某種形式的代碼開始檢查「APP」,直到最後一個「DAY」重複先前的記錄值@「PERCENT」,如果它的空值,以100開始,除了第一個條目(每個APP)已經填滿外。

在此先感謝。

回答

0

您可以使用the last_value() analytic function來實現此目的。如果當前值爲null,找了app的最後一個值(這是partition by條款)按日期順序排列(order by day),忽略任何空 - 所以你回頭看的了app以前的非空值:

select app, to_char(day, 'YYYY-MM-DD') as day, 
    nvl(percent, last_value (percent ignore nulls) 
    over (partition by app order by day)) as percent 
from my_table 
order by app, day; 

APP DAY   PERCENT 
--- ---------- ---------- 
JKL 2017-02-05   
JKL 2017-02-06   
JKL 2017-02-07   78 
JKL 2017-02-08   78 
JKL 2017-02-09   64 
JKL 2017-02-10   64 
JKL 2017-02-11   64 
TZU 2017-02-05   97 
TZU 2017-02-06   97 
TZU 2017-02-07   97 
TZU 2017-02-08   24 
TZU 2017-02-09   23 
TZU 2017-02-10   23 
TZU 2017-02-11   23 
UIO 2017-02-05   

我已使用nvl(),但如果您願意,可以使用case。在缺少100個值填補你可以再次使用nvl()case

select app, to_char(day, 'YYYY-MM-DD') as day, 
    nvl(percent, nvl(last_value (percent ignore nulls) 
    over (partition by app order by day), 100)) as percent 
from my_table 
order by app, day; 

APP DAY   PERCENT 
--- ---------- ---------- 
JKL 2017-02-05  100 
JKL 2017-02-06  100 
JKL 2017-02-07   78 
JKL 2017-02-08   78 
JKL 2017-02-09   64 
JKL 2017-02-10   64 
JKL 2017-02-11   64 
TZU 2017-02-05   97 
TZU 2017-02-06   97 
TZU 2017-02-07   97 
TZU 2017-02-08   24 
TZU 2017-02-09   23 
TZU 2017-02-10   23 
TZU 2017-02-11   23 
UIO 2017-02-05  100 

其他分析功能可以用來代替 - lag(),或通過顛倒順序,lead()first_value()

1

如果第一行對於給定的應用程序具有空值,則可以將第一行初始設置爲100。然後使用LAGIGNORE NULLS選項來獲取以前的非空值。

SELECT APP, 
     DT, 
     CASE WHEN NEW_PERCENT IS NOT NULL THEN NEW_PERCENT 
     ELSE LAG(NEW_PERCENT IGNORE NULLS) OVER(PARTITION BY APP ORDER BY DT) 
     END AS PERCENT 
FROM 
(SELECT T.*, 
     CASE WHEN ROW_NUMBER() OVER(PARTITION BY APP ORDER BY DT) = 1 AND PERCENT IS NULL THEN 100 
     ELSE PERCENT 
     END AS NEW_PERCENT 
    FROM T 
) X