有以下数据表:
字段1 字段2 字段3
15 tom dog
12 jack cat
23 tom dog
24 alex pig
33 hunk bird要求按字段1排序,并给出排序编号,但是字段2和字段3一样的情况下,编号要一样,类似下面的:编号 字段1 字段2 字段3
1 12 jack cat
2 15 tom dog
2 23 tom dog
3 24 alex pig
4 33 hunk bird请问sql文怎么写呀?用类似dense_rank() over(order by ...)可以做到吗?

解决方案 »

  1.   

    with t as
     (select 15 a, 'tom' b, 'dog' c
        from dual
      union all
      select 12, 'jack', 'cat'
        from dual
      union all
      select 23, 'tom', 'dog'
        from dual
      union all
      select 24, 'alex', 'pig'
        from dual
      union all
      select 33, 'hunk', 'bird' from dual)
    select dense_rank() over(order by nvl(d, a)) seq, a, b, c
      from (select t.*, lag(a) over(partition by b order by rownum) d from t) t;
      

  2.   

    谢谢楼上给出的sql,的确可以做到。
    但是实际运用上,我的情况可能更复杂一点,即字段2和字段3一样的情况可能不止两条记录,例如有N条记录,也可能不止一组,例如有tom+dog为一组,还有hunk+bird为一组的情况,所以上述这条sql语句就不行了,请问能不能改进一下符合这个要求的?
      

  3.   


    with t as
     (select 15 a, 'tom' b, 'dog' c
        from dual
      union all
      select 12, 'jack', 'cat'
        from dual
      union all
      select 23, 'tom', 'dog'
        from dual
      union all
      select 24, 'alex', 'pig'
        from dual
      union all
      select 33, 'hunk', 'bird'
        from dual
      union all
      select 34, 'hunk', 'bird'
        from dual
      union all
      select 32, 'hunk', 'bird'
        from dual
      union all
      select 13 a, 'tom' b, 'dog' c from dual)
    select dense_rank() over(order by d) seq, a, b, c
      from (select t.*, last_value(a) over(order by b) d from t) t;
      

  4.   

    select  t2.ord, t1.*
    from  表  t1, ( select rownum as ord , 字段2 from ( select distinct 字段2 from 表 order by 字段2  )   )  t2
    where t1.字段2 = t2.字段2 order by ord