Home > Database > Mysql Tutorial > body text

利用Oracle分析函数LAG求时间段内的本期、同比、环比值

WBOY
Release: 2016-06-07 15:51:12
Original
2228 people have browsed it

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 <br>
Oracle 分析函数LAG是用来求结果集中前一个值作为新的列的值得一个函数,效率很高。可以利用此分析函数来秒求环比和同比的值,但这其中也有些问题。LAG分析函数语法结构如下:

<p><span>LAG(EXPRESSION,[OFFSET],[DEFAULT]) OVER([PATITION BY COLUMN1...] ORDER BY COLUMN1...)</span>;</p>
<p>其中offset是偏移量,指的是在结果集中向前第OFFSET个值。</p>
<p>问题:</p>
<p>1、如果基表中有的月份缺失,那么他就会把缺失的那部分月份漏查,直接再找前一个的值。</p>
<p>2、如果加入了时间筛选那么最前面的值得环比值,和所有结果集中的同比值全会找不到。</p>
<p>解决方案:</p>
<p>初始化一个时间维度,与基表关联,补全所有的月份,缺失的月份数值值为零。 以销售额为例,SQL如下:</p>
<p><br>
</p>


Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template