2013-04-13 60 views
2

我在想如何將包含重複列值的列轉換爲MSSQL中的行。這是我正在使用的一個例子。在SQL中重複列值到行

CREATE TABLE Colors 
(
    Time_ Time, 
    Color varchar(6), 
    count int 
) 

INSERT INTO Colors VALUES ('10:00', 'Red', 2); 
INSERT INTO Colors VALUES ('10:00', 'Orange', 3); 
INSERT INTO Colors VALUES ('10:00', 'Yellow', 6); 
INSERT INTO Colors VALUES ('10:00', 'Green', 9); 
INSERT INTO Colors VALUES ('10:00', 'Blue', 2); 
INSERT INTO Colors VALUES ('11:00', 'Red', 3); 
INSERT INTO Colors VALUES ('11:00', 'Orange', 4); 
INSERT INTO Colors VALUES ('11:00', 'Yellow', 6); 
INSERT INTO Colors VALUES ('11:00', 'Green', 7); 
INSERT INTO Colors VALUES ('11:00', 'Blue', 1); 
INSERT INTO Colors VALUES ('12:00', 'Red', 2); 
INSERT INTO Colors VALUES ('12:00', 'Orange', 2); 
INSERT INTO Colors VALUES ('12:00', 'Yellow', 7); 
INSERT INTO Colors VALUES ('12:00', 'Green', 9); 
INSERT INTO Colors VALUES ('12:00', 'Blue', 4); 

而且SQLFiddle:http://sqlfiddle.com/#!3/48657/1

我正在尋找的是一個表,其中的行是Time_,紅,橙,黃,綠,藍。因此,這將是這個樣子:

任何幫助,將不勝感激。

回答

3
SELECT Time_, 
     Red, 
     Orange, 
     Yellow, 
     Green, 
     Blue 
FROM 
    (
     SELECT Time_, Color, Count 
     FROM Colors 
    ) orgData 
    PIVOT 
    (
     MAX(Count) 
     FOR Color IN (Red, Orange, Yellow, Green, Blue) 
    ) pvt 
+0

感謝您的幫助! – StoneRanger

+0

不客氣':D' –