sql server 2008中的查询问题

时间:2011-08-29 12:00:44

标签: sql-server tsql sql-server-2008 sql-server-express

我有一个名为album的表,其中包含以下列:

Album_Id, User_Id, Report_Id, PhotoName

PhotonameUser_Id组合

上有不同的Report_Id

像:

Album_Id   User_Id    Report_Id       PhotoName
1          1          16              A.jpg
2          1          16              B.jpg
3          2          17              C.jpg
4          2          17              D.jpg

我只是想以格式检索数据

User_Id    Report_Id       PhotoName1     PhotoName2
 1          16              A.jpg          B.jpg  
 2          17              C.jpg          D.jpg

最大照片是4 ...

2 个答案:

答案 0 :(得分:3)

WITH    cte
          AS ( SELECT   * ,
                        ROW_NUMBER() OVER ( PARTITION BY User_Id, Report_Id ORDER BY Album_Id ) AS RN
               FROM     T
             )
    SELECT  User_Id ,
            Report_Id ,
            MAX(CASE WHEN RN = 1 THEN PhotoName
                END) AS PhotoName1 ,
            MAX(CASE WHEN RN = 2 THEN PhotoName
                END) AS PhotoName2 ,
            MAX(CASE WHEN RN = 3 THEN PhotoName
                END) AS PhotoName3 ,
            MAX(CASE WHEN RN = 4 THEN PhotoName
                END) AS PhotoName4
    FROM cte
    GROUP BY User_Id ,
            Report_Id    

答案 1 :(得分:0)

SELECT a.User_Id, a.Report_Id, a.PhotoName as 'PhotoName1', a2.PhotoName as 'PhotoName2', a3.PhotoName as 'PhotoName3', a4.PhotoName as 'PhotoName4'
FROM album a
    LEFT JOIN album a2 on a2.User_Id = a.User_Id and a2.Report_Id = a.Report_Id AND a2.Album_Id != a.Album_Id
    LEFT JOIN album a3 on a3.User_Id = a.User_Id and a3.Report_Id = a.Report_Id AND a3.Album_id NOT IN (a.Album_Id, a2.Album_Id)
    LEFT JOIN album a4 on a4.User_Id = a.User_Id and a4.Report_Id = a.Report_Id AND a4.Album_id NOT IN (a.Album_Id, a2.Album_Id, a3.Album_Id)
ORDER BY a.User_Id, a.Report_Id ASC;