我有一个这样的SQL查询:
SELECT [a].*,
[rp].[TestId],
[r].[Deleted]
FROM (SELECT *,
ROW_NUMBER() OVER (PARTITION BY [RollId] ORDER BY [TimeStamp] DESC) AS row
FROM [RollAction]) a
INNER JOIN [RollPermission] rp ON ([rp].[RoId] = [a].[RollId]
AND [rp].[RoType] = [a].[RoType]
AND [rp].[UserId] = [a].[UserId]
AND [rp].[Deleted] = 0)
INNER JOIN [Roll] r ON ([r].[Id] = [a].[RollId]
AND [r].[RoType] = [a].[RollType]
AND [r].[Deleted] = 0)
WHERE row = 1
AND [a].[Action] = 'Fetched'
AND [a].[RollType] = 'Test'
AND [a].[Deleted] = 0
AND [a].[UserId] = 5
ORDER BY [a].[TimeStamp] DESC
OFFSET 0 ROWS FETCH NEXT 3 ROWS ONLY;
我想要完成的:Fetch
按RollPermission
过滤RollAction
inner join
的前 3 行,并Roll like
我已完成的inner joins
。
它可以工作,但它跳过一个分区,因此它确实获取了第一、第三和第四行。因为一个分区由于某种原因没有第 1 行和第 2 行,所以它在WHERE
子句中被过滤掉。
为什么该分区会跳过行?我试图去掉所有的 Where 子句,但它仍然跳过,我也试图去掉内部连接。
我的问题是我如何强制它不跳过第 1 行和第 2 行,或者交换行 = 1 以选择每个分区中存在的最低行号
正确答案来自Xanatos。
在子查询内移动AND [a].[Action] = 'Fetched' AND [a].[RollType] = 'Test' AND [a].[Deleted] = 0 AND [a].[UserId] = 5
RANK(( 而不是 ROW_NUMBER 可能是一种可能性