Unpivot期间表

时间:2014-11-24 07:12:06

标签: sql-server sql-server-2008 pivot pivot-table unpivot

在数据库中,它包含一个表

  ID   Name   MTH201401UN   MTH201401LC   MTH201312UN  MTH201312LC  MTH201311UN  MTH201311LC

   1    A      200            300          400           500            600        700

想要一张如下所示的不透明的表格:

  ID   Name   Period     UN  LC

  1     A   MTH201401  200  300 
  1     A   MTH201312  400  500 
  1     A   MTH201311  600  700 

主要的是期间不固定但是MTH部分是固定的 我该如何做到这一点,可以在没有特别提及的情况下花费时间?

1 个答案:

答案 0 :(得分:0)

这可能会对您有所帮助:这假定LCUN已修复

样本数据

create table temp(
    ID int,
    Name varchar(10),
    MTH201401UN int,
    MTH201401LC int,
    MTH201312UN int,
    MTH201312LC int,
    MTH201311UN int,
    MTH201311LC int
)
insert into temp
select 1, 'A', 200, 300, 400, 500, 600, 700

使用DYNAMIC SQL的解决方案

declare @sql varchar(4000) = ''

select @sql = @sql + '
select
    Id
    ,Name' + '
    ,''' +  column_name + ''' as Period' + '
    ,' +  column_name + 'LC as LC' + '
    ,' +  column_name + 'UN as UN' + char(10) +
'from temp
' + 
case 
    when rn < cc then 'union all'
    else ''
end
from (
    select
        + column_name as column_name,
        row_number() over(order by column_name) as rn,
        count(*) over(partition by (select null)) as cc
    from (
        select distinct 
            substring(column_name, 0, len(column_name) - 1) as column_name      
        from information_schema.columns
        where 
            table_name = 'temp'
            and column_name not in('ID','Name')
    )a
)t

print @sql

exec(@sql)

drop table temp