-2

表の現在のデータ

id  AA  BB  CC  DD  EE  FF
1   a   b   c   d   e   f
2   a1  b2  c3  d2  e4  f2

そして、私はしたい:

Colx   1   2
AA     a   a1 
BB     b   b2
CC     c   c3
DD     d   d2 
EE     e   e4 
FF     f   f2

私を助けてください。

4

1 に答える 1

2

さて、あなたの質問を注意深く見た後、これは重複していないと思います。列を行に変換するだけでなく、行を列に同時に変換したいのです。
したがって、次のような 2 つのソリューションを組み合わせる必要があります。列を行にピボット解除し、行を列にピボットします。

select
    c.name as ColX,
    max(case when t.id = 1 then c.value else null end) as [1],
    max(case when t.id = 2 then c.value else null end) as [2]
from Table1 as t
    cross apply (values
        ('AA', t.AA),
        ('BB', t.BB),
        ('CC', t.CC),
        ('DD', t.EE)
     ) as c(name, value)
group by c.name

sql fiddle demo

SQL Server から標準のピボットとアンピボットを使用することもできます。

select *
from Table1 as t
unpivot (
    value for
    colx in (AA, BB, CC, DD, EE, FF)
) as unpiv
pivot (
    max(unpiv.value)
    for id in ([1], [2])
) as piv

sql fiddle demo

ID と列の値を指定したくない場合は、動的 SQL を試してください。

declare @stmt1 nvarchar(max), @stmt2 nvarchar(max), @stmt nvarchar(max)

select @stmt1 =
    isnull(@stmt1 + ', ', '') + 
    '(''' + c.column_name + ''', t.' + c.column_name + ')'
from information_schema.columns as c
where c.table_name = 'Table1' and c.column_name <> 'id'

select @stmt2 =
    isnull(@stmt2 + ', ', '') + 'max(case when t.id = ' + t.id + ' then c.value end) as [' + t.id + ']'
from (select distinct cast(id as nvarchar(max)) as id from Table1) as t

select @stmt = '
    select
        c.name as ColX, ' + @stmt2 + '
    from Table1 as t
        cross apply (values ' + @stmt1 + ') as c(name, value)
    group by c.name'

exec sp_executesql @stmt = @stmt

sql fiddle demo

于 2013-08-19T09:19:56.200 に答える