2013-10-17 67 views
0

我有这种说法的迭代:通过SQL变量,其中声明

declare @max int 
@max = 1 
SELECT @max, t1.col1, t1.col2 
FROM table1 t1 

这会给我的结果:

1 a a 
1 b b 
1 c c 

,我想获得这种结果

1 a a 
2 b b 
3 c c 

我该如何达到这个结果?

我已经尝试做如下:

@max = 1 
SELECT @max, t1.col1, t1.col2 
FROM table1 t1 
WHERE @max = @max + 1 

,但没有成功,有人可以帮助我呢? 谢谢!

PS。我必须使用@max作为变量 - 我无法使用Identity或AUTOINCREMENT列

回答

7

使用row_number()函数。

SELECT row_number() over (order by t1.col1, t1.col2),t1.col1, t1.col2 
FROM table1 t1 

从固定值开始:

declare @your_number int 
set @your_number = 24353 

SELECT @your_number + row_number() over (order by t1.col1, t1.col2) AS num,t1.col1, t1.col2 
FROM table1 t1 
+0

确定开始行号,但假设我不想从1开始......但是对于前者。从一些随机int 24353?我怎样才能做到这一点? – Krystian

+0

查看我的回答 – Jonysuise

+1

@Krystian:'24353 + ROW_NUMBER()OVER(....)'..... –

2

试试这个:

with cte as 
(
    SELECT t1.col1, t1.col2, ROW_NUMBER() by (order by t1.col1, t1.col2) as RowNumber 
    FROM table1 t1 
) 

select c.RowNumber, c.col1, c.col2 
from cte c 

row_number()函数将返回从1

+0

在这种特殊情况下不需要CTE。欢呼! – Jonysuise