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如下:
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号