如何使用 ROW_NUMBER() 在 SELECT 中获取增量 "RowId" 列

How to get an incremental "RowId" column in SELECT using ROW_NUMBER()

我一直在尝试更新 a query on the DataExplorer that we use on our Gaming SE Site for keeping track of tags without excerpts to include an incremental row number in the results to make reading the returned values easier. There are a number of questions on here that discuss how to do this, such as this one and this one,它似乎对那些用户有用,但我似乎无法让它对我的情况起作用。

明确地说,我想要这样的东西:

RowId | TagName | Count | Easy List Formatting
----------------------------------------------
1     | Tag1    | 6     | 1. [tag:tag1] (6)
2     | Tag2    | 6     | 1. [tag:tag2] (6)
3     | Tag3    | 5     | 1. [tag:tag3] (5)
4     | Tag4    | 5     | 1. [tag:tag4] (5)

到目前为止我想出的是:

SELECT ROW_NUMBER() OVER(PARTITION BY TagInfo.[Count] ORDER BY TagInfo.TagName ASC) AS RowId, * 
FROM
(
   SELECT
   TagName,
   [Count],
   concat('1. [tag:',concat(TagName,concat('] (', concat([Count],')')))) AS [Easy List Formatting]
   FROM Tags
   LEFT JOIN Posts pe on pe.Id = Tags.ExcerptPostId
   LEFT JOIN TagSynonyms on SourceTagName = Tags.TagName
   WHERE coalesce(len(pe.Body),0) = 0 and ApprovalDate is null
) AS TagInfo
ORDER BY TagInfo.[Count] DESC, TagInfo.TagName

这产生了一些接近我想要的东西,但不完全是。 RowId 列递增,但一旦 Count 列发生变化,它就会重置(可能是因为 PARTITION BY)。但是,如果我删除 PARTITION BYRowId 列就会变成随机数。

鉴于表格的结构方式,我想做的事情是否可以实现?如果是这样,SQL 应该是什么?

要访问分叉查询,您可以使用 this link. The original query (before my changes) can be found here 如果它有帮助的话。

删除 PARTITION BY 正是所需要的。您的数字看起来随机的原因是外部查询的 ORDER BY 与您的 ROW_NUMBER()ORDER BY 不同。您所要做的就是使它们相同,序列项目的输出将具有您期望的单调递增值。

具体来说:

SELECT ROW_NUMBER() OVER (ORDER BY TagInfo.[Count] DESC, TagInfo.TagName) AS RowId, * 
FROM
(
   ...
) AS TagInfo
ORDER BY TagInfo.[Count] DESC, TagInfo.TagName

现在您没有分区,并且两个 ORDER BY 子句匹配,因此您将获得预期的输出。

就其价值而言,从技术上讲,您甚至不关心 ROW_NUMBER() 中的 ORDER BY,您只需要与最终结果集相同的顺序。在这种情况下,您可以通过在 ROW_NUMBER():

中提供无意义的 ORDER BY 子句来欺骗查询引擎
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS RowId

砰,大功告成!

绕过我使用它的一点方法,我在原始 table 中添加了一列,该列的增量值为 1,例如

ALTER TABLE ur_table ADD id INT IDENTITY(1,1) 
GO

之后您使用按列 id 排序的查询

select * from ur_table (query) order by id