OFFSET FETCH
不支持与TOP (n) WITH TIES
选项的逻辑等效,它通过返回所有关系来确保确定性。
是否有任何解决方法可以将OFFSET FETCH
和WITH TIES
放在一起?
使用示例数据创建语句
CREATE TABLE #tbl(Id INT, Name VARCHAR(10))
INSERT #tbl
SELECT 1, 'a' UNION ALL
SELECT 1, 'a' UNION ALL
SELECT 2, 'b' UNION ALL
SELECT 2, 'b' UNION ALL
SELECT 2, 'b' UNION ALL
SELECT 3, 'c' UNION ALL
SELECT 3, 'c' UNION ALL
SELECT 3, 'c'
热门
SELECT TOP 3 * FROM #tbl ORDER BY Id
Id Name
1 a
1 a
2 b
TOP n WITH TIES
SELECT TOP 3 WITH TIES * FROM #tbl ORDER BY Id
Id Name
1 a
1 a
2 b
2 b
2 b
OFFSET FETCH
SELECT *
FROM #tbl
ORDER BY Id
OFFSET 0 ROWS
FETCH NEXT 3 ROWS ONLY
Id Name
1 a
1 a
2 b
可能我们需要使用Ranking函数来实现这个目标吗?
答案 0 :(得分:4)
只需在CTE内部使用它们而不使用FETCH语句
;WITH cte AS
(
SELECT Id, Name
FROM #tbl
ORDER BY Id
OFFSET 0 ROWS
)
SELECT TOP 3 WITH TIES *
FROM cte
ORDER BY Id
请参阅SQLFiddle
偏移3 SQLFiddle
的示例;WITH cte AS
(
SELECT Id, Name
FROM #tbl
ORDER BY Id
OFFSET 3 ROWS
)
SELECT TOP 3 WITH TIES *
FROM cte
ORDER BY Id
答案 1 :(得分:-1)
SELECT *
FROM #tbl
ORDER BY Id
OFFSET 0 ROWS
FETCH NEXT 3 ROWS WITH TIES