如何获取表中记录的位置(SQL Server)
以下问题:
我需要获取表中记录的位置。假设表中有 5 条记录:
Name: john doe, ID: 1
Name: jane doe, ID: 2
Name: Frankie Boy, ID: 4
Name: Johnny, ID: 9
现在,“Frankie Boy”位于表中的第三位。但是如何从 SQL Server 获取这些信息呢?我可以计算 ID,但它们不可靠,Frankie 的 ID 为 4,但排在第三位,因为 ID 为“3”的记录已被删除。
有办法吗?我知道 ROW_RANK 但这会很昂贵,因为我需要先选择基本上整个集合,然后才能对它们进行 row_rank 排名。
我正在使用 MS SQL Server 2008 R2。
Following problem:
I need to get the position of a record in the table. Let's say I have five record in the table:
Name: john doe, ID: 1
Name: jane doe, ID: 2
Name: Frankie Boy, ID: 4
Name: Johnny, ID: 9
Now, "Frankie Boy" is in the third position in the table. But How to get this information from the SQL server? I could count IDs, but they are not reliable, Frankie has the ID 4, but is in the third position because the record with the ID '3' was deleted.
Is there a way? I am aware of ROW_RANK but it would be costly, because I need to select basically the whole set first before I can rank row_rank them.
I am using MS SQL Server 2008 R2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
桌子没有“位置”。表(=集合)中的行由其主键值标识。只有结果行具有“位置”,当存在
ORDER BY
子句时,该位置才是确定的。假设表(=集合)有一个位置只会导致问题,并且是错误的思维方式。Tables don't have 'position'. Rows in a table (=set) are identified by their primary key value. Only result rows have 'position' which can be deterministic when a
ORDER BY
clause is present. Assuming that tables (=sets) have a position will lead only to problems and is the wrong mind set.您可以使用
row_number()
来“标记”行。您必须指定一种对行进行排序的方法:如果性能是一个问题,您可以将位置存储在新列中:
使用
PositionInTable
上的索引,这将快如闪电。但是您必须在每次插入表后更新它。You can use
row_number()
to "label" rows. You've got to specify a way to order the rows:If performance is an issue, you could store the position in a new column:
With an index on
PositionInTable
, this would be lightning fast. But you would have to update this after each insert on the table.表格[概念上]没有顺序。除非您在 select 语句中指定 ORDER BY 对结果集进行排序,否则结果可能以任何顺序返回。重复执行完全相同的 SQL 可能会以不同的顺序返回每次执行的结果集。
要获取特定结果集中的行号,请使用 row_number() 函数:
这将为 sysobjects 中的每一行分配行号,就像表按 id 排序一样。
Tables are [conceptually] without order. Unless you specify ORDER BY in a select statement to order a results set, results may be returned in any order. Repeated executions of the exact same SQL may return the results set in different orders fro each execution.
To get the row number in a particular result set, use the row_number() function:
This will assign a row number to each row in sysobjects as if the table were ordered by id.
无需使用 ROW_NUMBER 即可完成此操作的一种简单方法是简单地计算表中有多少行的索引小于或等于所选索引,这将给出行号。
对于您的特定场景,这可能不是最有效的方法,但它是实现它的简单方法。
A simple way to do this without having to use ROW_NUMBER would be to simply count how many rows in the table have an index less or equal to the selected index, this would give the row number.
This may not be the most efficient way to do it for your particular scenario, but it's a simple way of achieving it.