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

时间:2013-09-25 13:34:28

标签: sql sql-server sql-server-2005 unpivot

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

enter image description here

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

enter image description here

有没有一种简单的方法可以做到这一点?

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

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

我会使用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 with demo。如您所见,这会在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)

请参阅Demo

答案 1 :(得分: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

相关问题