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是偏移量,指的是在結果集中向前第OFFSET個值。
問題:
1、如果基表中有的月份缺失,那么他就會把缺失的那部分月份漏查,直接再找前一個的值。
2、如果加入了時間篩選那么最前面的值得環比值,和所有結果集中的同比值全會找不到。
解決方案:
初始化一個時間維度,與基表關聯,補全所有的月份,缺失的月份數值值為零。 以銷售額為例,SQL如下:
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com