SQL Server Join with Latest 2 Entries

后端 未结 1 340
野趣味
野趣味 2021-01-25 14:36

I know the title of the post is bad but hear me out. A question like this arose the other day at work, and while I found a way around it, the problem still haunts me.

L

相关标签:
1条回答
  • 2021-01-25 14:46

    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 
    
    0 讨论(0)
提交回复
热议问题