如何取消透视以下列?
Posted
技术标签:
【中文标题】如何取消透视以下列?【英文标题】:How to unpivot the following columns? 【发布时间】:2019-08-29 11:20:11 【问题描述】:我有一个表 Tabel1,其中包含列 id、data1、value1A、value1B、date2、value2A、value2B。
数据就像
id, data1, value1A, value1B, date2, value2A, value2B
111, 01/01/1999, 10, 11, 05/05/2000 20, 22
222, 01/01/2005, 30, 32, 07/07/2007 44, 46
我想把它安排成如下:
id, data, value1, value2
111, 01/01/1999, 10, 11
111 05/05/2000 20, 22
222, 01/01/2005, 30, 32
222, 07/07/2007 44, 46
提前致谢
【问题讨论】:
【参考方案1】:您可以使用cross apply
来完成此操作:
declare @tbl as table (id int,data1 date,data2 date,value1A int,value1B int,value2A int,value2B int)
insert into @tbl
values (111,'1999-01-01','2000-05-05',10,11,20,22),
(222,'2005-01-01','2007-07-07',30,32,44,46)
select
id
, cp.*
from @tbl
cross apply
(
values
(data1,value1A,value1B),(data2,value2A,value2B)
)cp([data],value1,value2)
见demo
希望对你有帮助!
【讨论】:
【参考方案2】:您可以使用union all
运算符:
--test dataset
declare @somedata as table
(
id int,
data1 date,
value1A int,
value1B int,
data2 date,
value2A int,
value2B int
)
insert into @somedata
values (111, '1999-01-01', 10, 11, '2000-05-05', 20, 22),
(222, '2005-01-01', 30, 32, '2007-07-07', 44, 46)
--query
select c.id,
c.data,
c.value1,
c.value2
from ( select id,
data1 as data,
value1A as value1,
value1B as value2
from @somedata as a
union all
select id,
data2,
value2A,
value2B
from @somedata as b) as c
order by c.id, c.data
输出:
【讨论】:
以上是关于如何取消透视以下列?的主要内容,如果未能解决你的问题,请参考以下文章