投稿された質問で、列名に基づいていない結果に基づいてピボットを行うことを確認しました この結果を取得するSQLスクリプトは何かアドバイスできますか?列名のSQL ServerでPivotテーブルを返すにはどうすればよいですか?
実際の結果
期待される結果、事前に
ありがとう。
投稿された質問で、列名に基づいていない結果に基づいてピボットを行うことを確認しました この結果を取得するSQLスクリプトは何かアドバイスできますか?列名のSQL ServerでPivotテーブルを返すにはどうすればよいですか?
実際の結果
期待される結果、事前に
ありがとう。
あなたは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;
その後、あなたは動的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
クエリ。
840列があり、このようには使用できません – Rahul
次に、これを動的に作成するストアドプロシージャを作成する必要があります。あなたは、あなたが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