SQL将多列转换为行
您好,我是SQL新手,非常感谢您对如下表的转换提供帮助。查看类似的文章,这似乎可以通过pivot/unpivot实现,但我不确定,因为我读到的示例中的列要少得多。任何建议都很好 桌子SQL将多列转换为行,sql,sql-server,pivot,Sql,Sql Server,Pivot,您好,我是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
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
下面是我试用过的一个简单代码。只要跑一跑,看看它是否符合你的要求
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
下面是我试用过的一个简单代码。只要跑一跑,看看它是否符合你的要求
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
最终答案?把它全部加载到一个递归数组中,然后用较低的级别反向重放。最终答案是什么?将其全部加载到一个递归数组中,并以相反的方式用较低的级别重放它。