1

您好,我是 SQL 新手,非常感谢您在转置表方面的帮助,如下所示。查看类似的帖子,这似乎可以通过 pivot/unpivot 来完成,但我不确定,因为我读到的示例的列要少得多。任何建议都会很棒!

桌子。

CATEGORY Value1 Value2  Value3  Value4  ... Value15

Hot  18 17  9   17  ... 18

Warm     5  3   0   1   ... 3

Cold     20 2   1   2   ... 2

期望的结果。

CATEGORY Hot    Warm    Cold

Value1   18 5   20

Value2   17 3   2

Value3   9  0   1

Value4   17 1   2

…    …  …   …

Value15  18 3   2
4

2 回答 2

1
select *
from tbl
unpivot (value for name in (Value1, Value2,  Value3,  Value4,  ... Value15)) unpiv
pivot (max(value) for category in ([hot],[warm],[cold])) piv
于 2013-10-15T16:01:40.037 回答
0

以下是我尝试过的简单代码。只需运行,看看它是否符合您的要求!


declare @Tbl1 table(Category Varchar(10), Value1 Int, Value2 Int, Value3 Int, Value4 Int, Value5 Int)

insert into @Tbl1(Category, Value1, Value2, Value3, Value4, Value5)
    Values ('Hot', 12, 23, 43, 5, 6)
    insert into @Tbl1(Category, Value1, Value2, Value3, Value4, Value5)
    Values ('Warm', 41, 28, 4, 45, 16)
    insert into @Tbl1(Category, Value1, Value2, Value3, Value4, Value5)
    Values ('Cold', 1, 3, 543, 15, 26)

    select * from @Tbl1

 Declare @TblUP Table(Category Varchar(100), Value Int, [Types] Varchar(10))

 Insert into @TblUP(Category, Value, Types) 
 select * from @Tbl1 unpivot ([values] for Types in (Value1, Value2, Value3, Value4, Value5)) as UNPIV
 select * from @TblUP

 Select Types, Hot, Warm, Cold
 From
    (Select Types, Category, Value from @TblUP) as TUP
    PIVOT (SUM(Value) for [Category] in ([Hot], [Warm], [Cold]))
    as PT
于 2013-10-15T16:15:32.007 回答