with time_dim as (select add_months(add_months(date'2013-7-1',-12),(rownum-1)) dim_month from dual connect by level =months_between(date'2014-1-1',date'2012-7-1')+1)select t.dim_month, t.c_count, nvl(t.ly_count,0) ly_count, nvl(t.lm_count,
with time_dim as (select add_months(add_months(date'2013-7-1',-12),(rownum-1)) dim_month from dual connect by level <=months_between(date'2014-1-1',date'2012-7-1')+1) select t.dim_month, t.c_count, nvl(t.ly_count,0) ly_count, nvl(t.lm_count,0) lm_count from (select t1.dim_month, nvl(t2.c_count,0) c_count, lag(t2.c_count,1,0) over(order by t1.dim_month) ly_count, lag(t2.c_count,12,0) over(order by t1.dim_month) lm_count from time_dim t1 left join test_lzc t2 on t1.dim_month = t2.dim_month) t where t.dim_month between date'2013-7-1' and date'2014-1-1' order by 1 desc;
LAG(EXPRESSION,[OFFSET],[DEFAULT]) OVER([PATITION BY COLUMN1...] ORDER BY COLUMN1...);
其中offset是偏移量,指的是在結(jié)果集中向前第OFFSET個(gè)值。
問(wèn)題:
1、如果基表中有的月份缺失,那么他就會(huì)把缺失的那部分月份漏查,直接再找前一個(gè)的值。
2、如果加入了時(shí)間篩選那么最前面的值得環(huán)比值,和所有結(jié)果集中的同比值全會(huì)找不到。
解決方案:
初始化一個(gè)時(shí)間維度,與基表關(guān)聯(lián),補(bǔ)全所有的月份,缺失的月份數(shù)值值為零。 以銷售額為例,SQL如下:
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com