SQL Server Join with Latest 2 Entries

风流意气都作罢 提交于 2019-12-02 04:30:00

You can use a crosstab query pivoting on ROW_NUMBER

WITH UC 
     AS (SELECT UCJ.userId, 
                C.comment, 
                ROW_NUMBER() OVER (PARTITION BY userId 
                                       ORDER BY creationdate DESC) RN 
         FROM   UsersCommentsJoin UCJ 
                JOIN Comments C 
                  ON C.commentId = U.commentId) 
SELECT username, 
       MAX(CASE 
             WHEN RN = 1 THEN comment 
           END) AS MostRecent, 
       MAX(CASE 
             WHEN RN = 2 THEN comment 
           END) AS SecondMostRecent 
FROM   Users U 
       JOIN UC 
         ON UC.userId = U.userId 
WHERE  UC.RN <= 2 
GROUP  BY UC.userId 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!