2017-05-30 6 views

答えて

0

あなたはunion allでこれを行うことができます。

select 'name' as which, 
     max(case when id = 1 then name end) as [1], 
     max(case when id = 2 then name end) as [2], 
     max(case when id = 3 then name end) as [3], 
     max(case when id = 4 then name end) as [4] 
from t 
union all 
select 'state' as which, 
     max(case when id = 1 then state end) as [1], 
     max(case when id = 2 then state end) as [2], 
     max(case when id = 3 then state end) as [3], 
     max(case when id = 4 then state end) as [4] 
from t; 
+0

840列があり、このようには使用できません – Rahul

+0

次に、これを動的に作成するストアドプロシージャを作成する必要があります。あなたは、あなたがid = 1、id = 2 ... id = nを持つように+1で増分する変数を持っています。このアプローチのチュートリアルがあります:https://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/マイクロソフトでは、基本的な手順をhttps:// docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql それ以外の場合は、Gordon Linoffのアプローチが正しいです。 – ksauter

0

その後、あなたは動的SQLクエリを使用することができます。あなたによると

declare @sql as varchar(max); 

select @sql = 'select '+ char(39) + 'name' + char(39) + ' as [id],' + 
stuff((select distinct ', max(case when [id] = ' 
    + cast([id] as varchar(100)) + ' then [name] end) 
     as [' + cast([id] as varchar(100)) + ']' 
    from #t 
    for xml path('') 
), 1, 2, '') + 
' from #t union all ' + 
'select '+ char(39) + 'state' + char(39) + ' as [id],' + 
stuff((select distinct ', max(case when [id] = ' 
    + cast([id] as varchar(100)) + ' then [state] end) 
     as [' + cast([id] as varchar(100)) + ']' 
    from #t 
    for xml path('') 
), 1, 2, '') + 
' from #t'; 

exec(@sql); 

Chanage #t

クエリ。

+0

私は840+の列を持っています。私はあなたのクエリの中にそれらのそれぞれを書き込むことはできません。自動的に結果の列名と反復を得る他の方法がありますか? – Rahul

+0

@Rahul:ここでは個別に書き込む必要はありません。ダイナミックです。まずこのクエリを使用してからコメントを入れてください。盲目的にコメントしないでください。 – Wanderer

+0

ここでは、 ( "[id] = '+ varchar(100)+ cast [(id)] + [[name]」のように)を入力する必要はありません。 – Rahul

関連する問題