Oracle中不同时间粒度的日期约束


最近使用arcplan做报表,遇到不同日期粒度下展示数据的需求,利用sql直接从数据库中查询更为简便,且复用性强,记录下。

年粒度情况:展示当年前推5年的数据。

  1. t.d_day>= add_months(to_date('2012'||'0101''yyyymmdd'),-60)   
  2. and  t.d_day<= last_day(to_date('2012'||'1201''yyyymmdd'))  

半年粒度情况:展示当前半年前推12个数据点。

  1. d_day>=add_months(to_date(substr('2011H2', 1, 4)||decode(substr('2011H2', 6, 6),1,'0101',2,'0701'), 'yyyymmdd') ,-72)   
  2. and  t3.d_day<=to_date(substr('2011H2', 1, 4)||decode(substr('2011H2', 6, 6),1,'0630',2,'1231'), 'yyyymmdd')  

季粒度情况:展示当前季度前推12个数据点。

  1. t.d_day>=add_months(to_date(substr('2012Q1', 1, 4)||decode(substr('2012Q1', 6, 6),1,'0101',2,'0401',3,'0701',4,'1001'), 'yyyymmdd') ,-36)   
  2. and  t.d_day<=to_date(substr('2012Q1', 1, 4)||decode(substr('2012Q1', 6, 6),1,'0101',2,'0401',3,'0701',4,'1001'), 'yyyymmdd')  

月粒度情况:展示当前年所在12个月的数据,不足12个月前推。

  1. t.d_day<=last_day(to_date('201204   
  2. ', 'yyyymm')) and t.d_day>add_months(last_day(to_date('201204', 'yyyymm')),-12)  

旬粒度情况:展示当年季度前推12个点的数据。

  1. t.d_day>= to_date(to_char(add_months(to_date(substr('201201X3', 1, 6), 'yyyymm'), -ceil(11 / 3) ), 'YYYYMM')||decode( to_char(   
  2. case when to_number(substr('201201X3', 8, 1)) - mod(11, 3) > 0 THEN to_number(substr('201201X3', 8, 1)) - mod(11, 3)   
  3. else to_number(substr('201201X3', 8, 1)) - mod(11, 3) + 3 END),1,'01',2,'11',3,'21'),'yyyymmdd')   
  4. and t.d_day<= decode(substr('201201X3', 8, 8),1,to_date(substr('201201X3', 1, 6)||'10','yyyymmdd'),2,to_date(substr('201201X3', 1, 6)||'20','yyyymmdd'),3,last_day(to_date(substr('201201X3', 1, 6)||'01','yyyymmdd')))  

周粒度情况:展示当年周前12个数据点。

  1. t.d_day<= trunc(to_date(substr('2011W53', 1, 4) || '01' || '01''yyyymmdd'), 'IW') + 7 * to_number(substr('2011W53', 6, 2)) - 1     
  2. and t.d_day> trunc(to_date(substr('2011W53', 1, 4) || '01' || '01''yyyymmdd'), 'IW') + 7 * to_number(substr('2011W53', 6, 2)) - 1 - 12 * 7   

日粒度情况:展示当前月30天,不足30天前推30天。

  1. t.d_day<=to_date('20120326   
  2. ', 'yyyymmdd') and t.d_day>(to_date('20120326', 'yyyymmdd')-30)  

相关内容