我有以下SQL查询:
-- Top 3 users
SELECT
TOP (3) ROW_NUMBER() OVER(ORDER BY Reputation DESC) AS [#],
Id AS [UserId],
Reputation
FROM
Users
ORDER BY
Reputation DESC;
考虑上面的查询返回以下结果:
UserId | Reputation
-------------------
33 | 93123
21 | 20301
40 | 20101
如何获取ID为40
的用户所在的行号?在上面的示例中,它是3
。
另外,我需要在另一个SQL查询中使用它。我怎么能这样做?
答案 0 :(得分:1)
这有两种方法。第一个将子查询基本上用作子查询:
SELECT seqnum
FROM (SELECT ROW_NUMBER() OVER (ORDER BY Reputation DESC) AS seqnum,
Id AS [UserId],
Reputation
FROM Users
) u
WHERE UserId = 40;
第二个只使用标准SQL进行计算:
select 1 + COUNT(*)
from Users u join
Users u40
on u.Reputation < u40.reputation and
u40.Id = 40;