首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > oracle >

lag查询疑点

2013-04-21 
lag查询疑问--测试数据--create table lag_test (areaVARCHAR2(20),arttypeVARCHAR2(10),allcountNUMBER(8

lag查询疑问
--测试数据--


create table lag_test (
  area            VARCHAR2(20),
  arttype               VARCHAR2(10),
  allcount            NUMBER(8),
  acct_month         VARCHAR2(7)
); 

insert into lag_test
select '北京', '说', 15, '201201' from dual
union all
select '北京', '说', 12, '201202' from dual
union all
select '北京', '说', 21, '201203' from dual
union all
select '北京', '说', 31, '201204' from dual
union all
select '北京', '学', 14, '201201' from dual
union all
select '北京', '学', 12, '201202' from dual
union all
select '北京', '学', 21, '201203' from dual
union all
select '北京', '学', 15, '201204' from dual
union all
select '北京', '逗', 15, '201201' from dual
union all
select '北京', '逗', 16, '201202' from dual
union all
select '北京', '逗', 17, '201203' from dual
union all
select '北京', '逗', 18, '201204' from dual


--查询1--

select t.area,
       t.arttype,
       t.allcount,
       t.acct_month,
       lag(t.allcount, 1, 0) over(partition by area, arttype order by acct_month) as pre_month_allcount
  from lag_test t
where t.acct_month='201203'


--查询1结果--
   AREAARTTYPEALLCOUNT  ACCT_MONTHPRE_MONTH_ALLCOUNT
1北京逗17  2012030
2北京说21  2012030
3北京学21  2012030


--查询2--

select * from
(select t.area,
       t.arttype,
       t.allcount,
       t.acct_month,
       lag(t.allcount, 1, 0) over(partition by area, arttype order by acct_month) as pre_month_allcount
  from lag_test t)
  where acct_month='201203'


--查询2结果--
   AREAARTTYPEALLCOUNTACCT_MONTHPRE_MONTH_ALLCOUNT
1北京逗17          20120316
2北京说21          20120312
3北京学21          20120312

问题:为何查询1和查询2得出的结果不同呢?
[解决办法]
这个结果是必然,SQL1执行查询条件t.acct_month='201203'后只有三条记录
所以针对area, arttype的前一条记录都是没有的,就是0

SQL2是计算出area, arttype的前一条记录后,然后再通过查询条件t.acct_month='201203'
查出记录。
[解决办法]
执行顺序不一样,条件针对的结果集不同.

热点排行