有以下数据表:
字段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 ...)可以做到吗?
------解决方案--------------------
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;
------解决方案--------------------
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;