日期:2014-05-17  浏览次数:20749 次

一直困扰的ORACLE SQL 问题,求助
START_CI  name_id  TIME_STAMP
11933    test01 2013-1-7 11:01
11933   test01 2013-1-7 13:18
11933   test01 2013-1-7 18:18
38165   test02 2013-1-7 8:36
38165   test02 2013-1-7 9:36
3244   test02 2013-1-7 13:20
38165   test02 2013-1-7 18:36
3210   test02 2013-1-7 23:39
测试表名为:TEST  三列如上:START_CI  name_id  TIME_STAMP
想要的结果为:
11933    test01 2013-1-7 11:01
38165   test02 2013-1-7 8:36
3244  test02       2013-1-7 13:20
38165  test02       2013-1-7 18:36
3210  test02       2013-1-7 23:39
解释:
根据不同的name_id分组。合并START_CI相同的记录,取TIME_STAMP最小值,
但合并注意。不联系的不可合并,比如:
38165   test02 2013-1-7 8:36
38165   test02 2013-1-7 9:36
3244   test02 2013-1-7 13:20
38165   test02 2013-1-7 18:36
这四条记录,中间有条START_CI为3244 让teset02的用户 START_CI为38165变的不连续的行,只能合并前两行,对于test01用户前三行START_CI都是11933且都是上下行都是联系的11933,没有被其他不同的分隔开,可以合并一条
ORACLE?SQL?技术

------解决方案--------------------
with t as
 (select t.*,
         case
           when t.START_CI <> lead(START_CI)
            over(order by rownum) and t.START_CI <> lag(START_CI)
            over(order by rownum) then
            1
           else
            0
         end flag
    from test t)
select START_CI, name_id, TIME_STAMP
  from (select t.*,
               row_number() over(partition by START_CI, flag order by TIME_STAMP) rn
          from t)
 where rn = 1;