SQL:对 SELECT 语句返回的行进行编号
假设我有一个返回一组结果的 SELECT 语句。 有什么方法可以按以下方式对结果进行编号:
从 PuppyNames 中按投票数排序选择前 3 个名字
会给我...
菲多
漫游者
弗雷迪·克鲁格
...但我想要...
1、菲多
2、漫游者
3、弗雷迪·克鲁格
当然,逗号表示数字在自己的列中。 [我正在使用 SQL Server 2000。]
Suppose I have a SELECT statement that returns some set of results. Is there some way I can number my results in the following way:
SELECT TOP 3 Name FROM PuppyNames ORDER BY NumberOfVotes
would give me...
Fido
Rover
Freddy Krueger
...but I want...
1, Fido
2, Rover
3, Freddy Krueger
where of course the commas signify that the numbers are in their own column. [I am using SQL Server 2000.]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 Microsoft SQL Server 2005 中,您可以使用
ROW_NUMBER()
函数来完成您想要的操作。如果您无法使用 SQL Server 2000,典型的技术是创建一个新的临时表来包含查询结果,并添加一个 IDENTITY 列并生成增量值。 请参阅此处讨论此技术的文章:http://www.databasejournal.com/features/mssql/article.php/3572301/RowNumber-function-in-SQL-Server-2005.htm
In Microsoft SQL Server 2005, you have the
ROW_NUMBER()
function which does exactly what you want.If you are stuck with SQL Server 2000, the typical technique was to create a new temporary table to contain the result of your query, plus add an
IDENTITY
column and generate incremental values. See an article that talks about this technique here: http://www.databasejournal.com/features/mssql/article.php/3572301/RowNumber-function-in-SQL-Server-2005.htm对于 SQL 2000,您需要使用相关子查询。
With SQL 2000 you need to use a correlated sub-query.
在客户端应用程序中添加数字通常更容易。 SQL 中有一些技巧,但对于纯粹主义者来说,它们涉及作弊,而且它们通常不可移植。
对我来说,这是我最基本的重构模式之一。
It's usually easier to add the numbers in the client app. There are tricks in SQL, but to a purist they involve cheating, and they aren't generally portable.
For me, it's one of my most basic refactoring patterns.
您还可以使用临时表来完成此操作:
如果
您注意到,您的 SELECT 语句就在那里。 它只是被使行号起作用的东西包围着。
You could also do it with a temp table:
becomes
If you'll notice, your SELECT statement is in there. It is just surrounded by stuff that makes the row numbers work.
您可以使用此查询,该查询会考虑 PK,以便在 NumberOfVotes 相同的情况下提供正确的编号:
You could use this query, which takes into account the PK in order to provide correct numbering in case of same NumberOfVotes:
SQL 2005、2008:
选择前 3 个 ROW_NUMBER() OVER(ORDER BY NumberOfVotes DESC) AS VoteRank、名称
FROM PuppyNames
编辑:抱歉 - 刚刚看到您指定了 2000。
SQL 2005, 2008:
SELECT TOP 3 ROW_NUMBER() OVER(ORDER BY NumberOfVotes DESC) AS VoteRank, Name
FROM PuppyNames
EDIT: Sorry - just saw you specified 2000.