SQL 如何在select语句中生成序列号+加1
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7600022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to generate Serial numbers +Add 1 in select statement
提问by James123
I know we can generate row_number in select statement. But row_number starts from 1, I need to generate from 2 and onwards.
我知道我们可以在 select 语句中生成 row_number。但是 row_number 从 1 开始,我需要从 2 开始生成。
example
例子
party_code
----------
R06048
R06600
R06791
(3 row(s) affected)
I want it like
party_code serial number
---------- -------------
R06048 2
R06600 3
R06791 4
Current I am using below select statement for generate regular row number.
目前我正在使用下面的 select 语句来生成常规行号。
SELECT party_code, ROW_NUMBER() OVER (ORDER BY party_code) AS [serial number]
FROM myTable
ORDER BY party_code
How can modify above select statement and start from 2?
如何修改上面的select语句并从2开始?
回答by AakashM
SELECT party_code, 1 + ROW_NUMBER() OVER (ORDER BY party_code) AS [serial number]
FROM myTable
ORDER BY party_code
to add: ROW_NUMBER()
has an unusual syntax, and can be confusing with the various OVER
and PARTITION BY
clauses, but when all is said and done it is still just a function with a numeric return value, and that return value can be manipulated in the same way as any other number.
补充:ROW_NUMBER()
有一个不寻常的语法,可能会与各种OVER
andPARTITION BY
子句混淆,但总而言之,它仍然只是一个具有数字返回值的函数,并且该返回值可以以与 any 相同的方式进行操作其他号码。
回答by Yahia
I don't know much about SQL Server but either one of these will work:
我对 SQL Server 了解不多,但其中任何一种都可以使用:
SELECT party_code, 1 + ROW_NUMBER() OVER (ORDER BY party_code) AS [serial number]
FROM myTable
ORDER BY party_code
OR
或者
SELECT party_code, serial_numer + 1 AS [serial number] FROM
(SELECT party_code, ROW_NUMBER() OVER (ORDER BY party_code) AS [serial number]
FROM myTable)
ORDER BY party_code