DECLARE @SQL AS VARCHAR(MAX),@T AS VARCHAR(200),@Cols AS VARCHAR(1000)
SET @SQL = 'SELECT t1.PaintSize'
SET @Cols = ''
SET @T = ''
SELECT @SQL = @SQL + ',[' + CAST(PhotoNum AS VARCHAR(10)) + 'Figures]', @Cols = @Cols + ',[' + CAST(Id as NVARCHAR(10)) + '] AS [' + CAST(PhotoNum as NVARCHAR(10)) + 'Figures]',@T = @T + '[' + CAST(ID AS VARCHAR(10)) + '],' FROM T_PhotoNum
SET @T = LEFT(@T,LEN(@T) - 1)
SET @SQL = @SQL + ' FROM (SELECT SizeId' + @Cols + ' FROM (SELECT SizeId,PhotoId,PhotoPrice FROM T_Photo_Size) AS P PIVOT (MAX(PhotoPrice) FOR PhotoId IN (' + @T + ')) AS PVT) t2 LEFT JOIN T_PaintSize t1 ON t1.Id = t2.SizeId'
EXEC(@SQL)
答案是参照你的表结构写的,相关的需求可以了解一下PIVOT.
你贴的图片是防外链的