テーブルをピボットしようとしていますが、少し苦労しています。私のテーブル スキーマは次のようになります。
ID W_C W_P A_C A_P
3 257 251342 217 206078
4 443 109023 332 87437
6 17 9985 32 13515
私が達成しようとしているのは、次のようなものです。
3 4 6
w_c 257 443 17
w_p 251342 109023 9985
a_c 217 332 87437
a_p 206078 87437 13515
w_c
、 、w_p
を表示する必要はありませんa_c
。または、a_p
単に参照点として使用していました。
ピボット/アンピボットでそれを行う方法があるかもしれないと思いますが、私はそれらにあまり慣れていないため、読んだことは役に立ちません。
私はCTEを使って何かをしようとしましたが、それは複雑すぎて悪い習慣だと思います:
;with [3_Data] as (
Select
1 as [common_key3]
,max(Case when [id] = 3 then [w_c] else 0 end) as [3_Records]
From [example]
), [4_data] as (
Select
1 as [common_key4]
,max(Case when [id] = 4 then [w_c] else 0 end) as [4_Records]
From [example]
), [6_data] as (
Select
1 as [common_key6]
,max(Case when [id] = 6 then [w_c] else 0 end) as [6_Records]
From [example]
)
Select [3_Records], [4_Records], [6_Records]
From [3_Data]
inner join [4_data] on [common_key3] = [common_key4]
inner join [6_data] on [common_key3] = [common_key6]
作成済みのテーブルを使用した SQL フィドル: http://sqlfiddle.com/#!3/02ef2/6