如何在SEDE上对徽章表进行分页?

时间:2019-07-04 14:31:14

标签: sql-server sql-server-2017 dataexplorer

具有this示例中的代码:

-- UserId: User ID     "Enter a user's ID."
SELECT      u.Id     AS [User Link]
            , CASE
                WHEN b.Tagbased = 1 THEN 'Tag: [' + b.Name + ']'
                ELSE b.Name
            END    AS [Badge name]
            , CASE
                WHEN b.Class = 1 THEN 'Gold'
                WHEN b.Class = 2 THEN 'Silver'
                WHEN b.Class = 3 THEN 'Bronze'
                ELSE '*Unkown*'
            END    AS [Class]
            , b.Date AS [Awarded]
FROM        Badges b
LEFT JOIN   Users u  ON u.Id = b.Userid
--WHERE       b.Userid = ##UserId:int##
WHERE       u.reputation > 100000
ORDER  BY   u.Displayname
            , [Awarded] DESC

如何实现分页like this示例来接收大于50000的结果?

1 个答案:

答案 0 :(得分:1)

使用CTE方法(据称它比OFFSET和FETCH更快),查询变为:
(请参见live at SEDE

-- StartRow: Starting row for paging
-- EndRow: Ending row for paging (Max 50K rows at a time)
-- MinimumRep: Ony return data for users that have this many reputation points
WITH allData AS (
    SELECT
                ROW_NUMBER() OVER (ORDER BY u.Displayname, b.Date DESC) AS row
                , u.Id
                , CASE
                    WHEN b.Tagbased = 1 THEN 'Tag: [' + b.Name + ']'
                    ELSE b.Name
                END    AS [Badge name]
                , CASE
                    WHEN b.Class = 1 THEN 'Gold'
                    WHEN b.Class = 2 THEN 'Silver'
                    WHEN b.Class = 3 THEN 'Bronze'
                    ELSE '*Unkown*'
                END    AS [Class]
                , b.Date AS [Awarded]
    FROM        Users u
    INNER JOIN  Badges b    ON u.Id = b.Userid
    WHERE       u.reputation > ##MinimumRep:int?100000##
)
SELECT      a.Id     AS [User Link]
            , a.[Badge name]
            , a.[Class]
            , a.[Awarded]
FROM        allData a
WHERE       row    >= ##StartRow:INT?1##
AND         row    <= ##EndRow:INT?50000##
ORDER BY    row