我有这样的陈述:
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列
答案 0 :(得分: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
答案 1 :(得分: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开始返回行号。