如何在SQL中选择记录作为列

时间:2011-02-01 15:19:52

标签: sql

我有两个表:tblSizes和tblColors。 tblColors具有名为ColorName,ColorPrice和SizeID的列。有一种尺寸到多种颜色。我需要编写一个查询来选择该大小的大小和所有颜色(作为列),每个大小的价格在各自的列中。

颜色必须以列的形式返回,例如:

SizeID : Width : Height : Red : Green : Blue  
1---------220-----220----£15----£20-----£29 

希望这有意义 谢谢

编辑:尝试了以下代码,但不太确定是什么问题:

DECLARE @Colors NVARCHAR(4000), @Query NVARCHAR(MAX)
SET @Colors = ''

SELECT @Colors = @Colors + '[' + C.Color +'],'
FROM tblTempProductSizesColors SC
INNER JOIN tblColors C on SC.ColorID=C.ID
GROUP BY Color
ORDER BY Color

SET @Colors = LEFT(@Colors,LEN(@Colors)-1)


SET @Query = '
SELECT *
FROM (  SELECT TS.Sizeid, TS.Width, TS.Height, TS.Depth, TC.Price
        FROM tblTempProductSizes TS
        INNER JOIN tblTempProductSizesColors TC
        ON TS.SizeId = TC.SizeId INNER JOIN tblColors C on TC.ColorID=C.ID) A
        PIVOT(SUM(Price) FOR C.Color IN ('+@Colors+')) AS PT'

EXEC sp_executesql @Query

2 个答案:

答案 0 :(得分:2)

select s.Sizeid, s.Width, s.Height, 
Red = SUM(CASE WHEN c.ColorName = "Red" THEN c.ColorPrice ELSE 0 END),
Blue = SUM(CASE WHEN c.ColorName = "Blue" THEN c.ColorPrice ELSE 0 END),
Green = SUM(CASE WHEN c.ColorName = "Green" THEN c.ColorPrice ELSE 0 END)
from tblSizes s
join tblColors c on c.SizeId = s.SizeId
group by s.Sizeid, s.Width, s.Height

答案 1 :(得分:0)

如果您不想编写每种颜色以及这些列的表达式,则可以使用动态SQL(如果您有MSSQL 2005+)(首先,请务必查看此link)。
在评论后更新

DECLARE @Colors NVARCHAR(4000), @Query NVARCHAR(MAX)
SET @Colors = ''

SELECT @Colors = @Colors + '[' + C.Color +'],'
FROM tblTempProductSizesColors SC
INNER JOIN tblColors C on SC.ColorID=C.ID
GROUP BY Color
ORDER BY Color

SET @Colors = LEFT(@Colors,LEN(@Colors)-1)


SET @Query = '
SELECT *
FROM (  SELECT TS.Sizeid, TS.Width, TS.Height, TS.Depth, TC.Price, C.Color
        FROM tblTempProductSizes TS
        INNER JOIN tblTempProductSizesColors TC
        ON TS.SizeId = TC.SizeId INNER JOIN tblColors C on TC.ColorID=C.ID) A
        PIVOT(SUM(Price) FOR Color IN ('+@Colors+')) AS PT'

EXEC sp_executesql @Query