求高手看看这个SQL该怎么写
本帖最后由 allenpony 于 2013-06-19 17:21:14 编辑
            有一个表testtable,有如下字段
active_time,inactive_time,seq_id,area_id
表中有如下数据
active_time             inactive_time           seq_id          area_id
2008/10/22 16:22:57	2008/10/22 17:22:57	153991356	43993
2008/10/22 16:22:57	2009/9/1	        153991356	90032
2008/10/22 16:22:57	2008/11/29 11:14:12	153991356	90081
2008/10/22 16:22:57	2008/11/29 11:14:13	153991356	42116
2008/10/22 16:22:57	2008/11/29 11:14:13	153991356	44336
2008/10/22 17:22:58	2008/12/1	        153991356	43993
2010                    2037                    153991356	43993
现在要找出一个seq_id对应的active_time最小的那个月(200810)的数据,同一个seq_id,同一个area_id对应多条数据的时候,取inactive_time最大的。比如43993,要求是2008/12/1那条数据,最后的结果应该是
active_time             inactive_time           seq_id          area_id
2008/10/22 16:22:57	2009/9/1	        153991356	90032
2008/10/22 16:22:57	2008/11/29 11:14:12	153991356	90081
2008/10/22 16:22:57	2008/11/29 11:14:13	153991356	42116
2008/10/22 16:22:57	2008/11/29 11:14:13	153991356	44336
2008/10/22 17:22:58	2008/12/1	        153991356	43993
另外该表有其他字段,且数据量有上亿,因此不可用group by 的方式。
              
------解决方案--------------------select t.active_time, t.inactive_time, t.seq_id, t.area_id
  from (select t.*,
               row_number() over(partition by seq_id, t.area_id order by t.inactive_time desc) rn
          from (select t.*,
                       dense_rank() over(partition by seq_id order by to_char(t.active_time, 'yyyymm')) dr
                  from testtable t) t
         where t.dr = 1) t
 where t.rn = 1;
估计会跑不动