如何设置行号()

时间:2014-09-15 09:17:19

标签: sql sql-server-2008

我有一张这样的表 -

C1   C2         C3
A   20130101    10
A   20130102    10
A   20130103    20
A   20130104    10

我想设置这样的行 -

C1   C2         C3   RowNo
A   20130101    10   1
A   20130102    10   2
A   20130103    20   1
A   20130104    10   1

如何通过查询制作? 或者只有办法循环这个表?

谢谢..

3 个答案:

答案 0 :(得分:1)

我用递归CTE更新了答案。它构建层次结构树,从具有新C3值和显示级别为RowNo的记录开始。

with t as 
(select t.*, row_number () over (order by c2) rn from table1 t)

,temp (c2,c3,rn,lvl)  AS 
(SELECT c2,c3,rn,1 lvl from t t1  
                       where not exists(
                                        select 1 from t t0 
                                                 where t1.rn=t0.rn+1 
                                                   and t1.c3=t0.c3
                                       )
  UNION ALL 
 select t1.c2,t1.c3,t1.rn,lvl + 1 AS lvl FROM t t1
 join temp t2 on t1.rn=t2.rn+1 and t1.c3=t2.c3)

SELECT c2, c3, lvl rowno FROM temp order by rn;

http://sqlfiddle.com/#!3/4adbd/1

答案 1 :(得分:0)

ROW_NUMBER()函数可以帮助您设置行数:

SELECT ROW_NUMBER() over(order by [some field]), *
      FROM [your table]

答案 2 :(得分:0)

SELECT ROW_NUMBER()over(PARTITION BY [C3] order by [C2]),*       从表名