2

我想知道如何将包含重复列值的列转换为 MSSQL 中的行。这是我正在使用的示例。

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_、Red、Orange、Yellow、Green、Blue。所以它看起来像这样:

任何帮助,将不胜感激。

4

1 回答 1

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
于 2013-04-13T17:42:45.077 回答