在 SQL 中将数据透视表转换为平面表

问题描述 投票:0回答:2

我想将数据透视表转换为平面表,但采用以下方式:考虑此表的简单示例:

enter image description here

如您所见,对于每个项目(地址或收入),我们有一列用于旧值,一列用于新值(更新值)。我想将表格转换为“平面”表格,如下所示:

enter image description here

有简单的方法吗?

sql sql-server sql-server-2005 unpivot
2个回答
2
投票

为了获得结果,您需要取消数据透视。当您取消透视时,您将多列转换为多行,这样做时数据的数据类型必须相同。

我会使用 CROSS APPLY 成对地取消透视列:

select t.employee_id,
  t.employee_name,
  c.data,
  c.old,
  c.new
from yourtable t
cross apply
(
  values 
  ('Address', Address_Old, Address_new),
  ('Income', cast(income_old as varchar(15)), cast(income_new as varchar(15)))
) c (data, old, new);

请参阅SQL Fiddle 演示。正如您所看到的,这在

cast
列上使用了
income
,因为我猜测它是与
address
不同的数据类型。由于最终结果将在同一列中包含这些值,因此数据必须具有相同的类型。

这也可以使用 CROSS APPLY 和 UNION ALL 来编写:

select t.employee_id,
  t.employee_name,
  c.data,
  c.old,
  c.new
from yourtable t
cross apply
(
  select 'Address', Address_Old, Address_new union all
  select 'Income', cast(income_old as varchar(15)), cast(income_new as varchar(15))
) c (data, old, new)

参见演示


1
投票
select employee_id,employee_name,data,old,new
from (
select employee_id,employee_name,adress_old as old,adress_new as new,'ADRESS' as data
from employe
union
select employee_id,employee_name,income_old,income_new,'INCOME'
from employe
 ) data
order by employee_id,data

参见这个小提琴演示:http://sqlfiddle.com/#!2/64344/7/0

© www.soinside.com 2019 - 2024. All rights reserved.