在查询结果中包含行号 (SQL Server)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3344863/
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
Include row number in query result (SQL Server)
提问by TCM
I think each row in sql server is given a unique number. How can I include that in my SQL query results?
我认为 sql server 中的每一行都有一个唯一的编号。如何将其包含在我的 SQL 查询结果中?
回答by Thomas
If you are referring to the row number provided by Management Studio when you run a query, there is no way to get that because it does not really exist. Management Studio generates that on the fly. You can however, recreate a sequential number using the ROW_NUMBERranking function if you are using SQL Server 2005 or later. Note you should never assume the database will return the rows in a specified order unless you include an Order By statement. So your query might look like:
如果您在运行查询时参考 Management Studio 提供的行号,则无法获取该行号,因为它实际上并不存在。Management Studio 即时生成。但是,如果您使用的是 SQL Server 2005 或更高版本,则可以使用ROW_NUMBER排名函数重新创建序列号。请注意,除非您包含 Order By 语句,否则您永远不应假设数据库会以指定的顺序返回行。因此,您的查询可能如下所示:
Select ....
, Row_Number() Over ( Order By T.SomeColumn ) As Num
From Table As T
Order By T.SomeColumn
The Order By in the Over clause is used to determine the order for creating the sequential numbers. The Order By clause at the end of the query is used to determine the order of the rows in the output (i.e. the order for the sequence number and the order of the rows can be different).
Over 子句中的 Order By 用于确定创建序列号的顺序。查询末尾的Order By 子句用于确定输出中行的顺序(即序列号的顺序和行的顺序可以不同)。
回答by simplyharsh
The uniqueness in your result will always be your primary key.
结果中的唯一性将始终是您的主键。
But there is something called ROW_NUMBER function that can be used as unique identity of row in a specific result.
但是有一个叫做 ROW_NUMBER 的函数可以用作特定结果中行的唯一标识。
SELECT zip,city,state,latitude,longitude,timezone,dst,
ROW_NUMBER() OVER (ORDER BY zip) AS num
FROM dbo.zipcode;
回答by Montu Padmani
I think you should use this one....
我认为你应该使用这个......
DCount('Column_Name','Table_Name','Column_Name <= ' & [Column_Name]) as SR
DCount('Column_Name','Table_Name','Column_Name <= ' & [Column_Name]) as SR