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个&#20540;。
问题:
1、如果基表中有的月份缺失,那么他就会把缺失的那部分月份漏查,直接再找前一个的&#20540;。
2、如果加入了时间筛选那么最前面的&#20540;得环比&#20540;,和所有结果集中的同比&#20540;全会找不到。
解决方案:
初始化一个时间维度,与基表关联,补全所有的月份,缺失的月份数&#20540;&#20540;为零。 以销售额为例,SQL如下: