SQL QUERY 转向并加入

SQL QUERY Pivot and join

我有一个父 table 称数据为

ID     Lat     Lon  

并有照片 table 作为

ID    id_from_Data_table    photoPath

照片table 数据表中的每条记录都有多条记录。

我想要这样的结果集:

lat   lon    photopath1   photopath2   photopath3 ...... 

照片中每条记录的照片路径列 table。

使用动态 SQL 查询可能如下所示:

DECLARE @cols  AS NVARCHAR(MAX),
        @query AS NVARCHAR(MAX)

SELECT @cols = STUFF((SELECT ',' + QUOTENAME(rn)
                    FROM (
                    SELECT d.*, p.photoPath, rn = CONCAT('Photo Path ',ROW_NUMBER() OVER (PARTITION BY d.id ORDER BY p.id)) 
                    FROM data d 
                    JOIN photo p ON d.ID = p.id_from_Data_table
                ) yourtable
                    GROUP BY rn
                    ORDER BY rn
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

SET @query = N'
    SELECT lat, lon, ' + @cols + N' 
    FROM 
    (
       SELECT 
          d.*, 
          p.photoPath, 
          rn = CONCAT(''Photo Path '', ROW_NUMBER() OVER (PARTITION BY d.id ORDER BY p.id)) 
       FROM data d 
       JOIN photo p ON d.ID = p.id_from_Data_table
    ) x
    PIVOT 
    (
       MAX(photoPath) FOR rn IN (' + @cols + N')
    ) p;'

EXEC sp_executesql @query;

Sample SQL Fiddle