Row_number()返回null值如何解决此意外问题

时间:2018-12-19 21:10:21

标签: sql sql-server tsql row-number sql-server-2017

此处是SQL查询

;WITH rankedresults AS 
(
    SELECT 
        userid, 
        rowid 
    FROM   
        (SELECT 
             userid, 
             ROW_NUMBER() OVER (ORDER BY referredplayercount DESC) AS RowId 
         FROM   
             tblusersprofile) dt 
    WHERE  
         rowid BETWEEN 1 AND 50
) 
SELECT 
    tblusersprofile.userid, 
    referredplayercount, 
    username, 
    avatarimagelink, 
    authoritylevel, 
    rowid 
FROM
    tblusersprofile 
LEFT JOIN 
    rankedresults ON tblusersprofile.userid = rankedresults.userid 
WHERE  
    tblusersprofile.userid IN (SELECT rankedresults.userid 
                               FROM rankedresults) 
    AND referredplayercount > 0 
ORDER BY 
    rowid ASC 

这里返回的结果预期行号不会为空

enter image description here

我想知道再次通过此查询重新生成rankedresults吗?

SELECT rankedresults.userid 
FROM rankedresults

1 个答案:

答案 0 :(得分:4)

用户ID 1137仅在tbluserprofile表中,而不在rankresults结果CTE中。

因为它是一个LEFT JOIN,因为没有匹配项,所以结果中的rowid显示为NULL。

row_number()函数本身无法生成NULL。

但是要确保CTE中的ROW_NUMBER始终返回完全相同的顺序,请在ORDER BY中添加用户ID

ROW_NUMBER() OVER (ORDER BY referredplayercount DESC, userid) AS RowId

但是也许您可以避免两次使用该CTE?

;WITH rankedresults AS 
(
    SELECT 
     userid, 
     RowId
    FROM
    (
       SELECT 
        userid, 
        ROW_NUMBER() OVER (ORDER BY referredplayercount DESC, userid ASC) AS RowId 
       FROM tblusersprofile
       WHERE referredplayercount > 0 
    ) dt
    WHERE RowId BETWEEN 1 AND 50
) 
SELECT 
    usrprof.userid, 
    usrprof.referredplayercount, 
    usrprof.username, 
    usrprof.avatarimagelink, 
    usrprof.authoritylevel, 
    rr.rowid 
FROM
    tblusersprofile usrprof
JOIN 
    rankedresults rr ON rr.userid = usrprof.userid
ORDER BY 
    rr.RowId ASC

如果可以使用OFFSET & FETCH,并且您真的不需要select中的RowId吗?
然后,您甚至不需要具有row_number的CTE即可分页结果。

declare @offsetrows int = 0;
declare @nextrows int = 50;

SELECT 
 userid, 
 referredplayercount, 
 username, 
 avatarimagelink, 
 authoritylevel
FROM tblusersprofile
WHERE referredplayercount > 0
ORDER BY referredplayercount DESC, userid ASC
OFFSET @offsetrows ROWS FETCH NEXT @nextrows ROWS ONLY;

db <>小提琴here

的简化测试