4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

複数列のデータを縦に並べる方法【SQLServer】

Posted at

#複数列のデータを縦に並べる

この横に並んでいるデータを

CD RANK1 PRICE1 RANK2 PRICE2 RANK2 PRICE3
1 A 100 B 200 C 300
2 A 120 B 220 C 320
3 A 130 B 230 C 330

このように縦に並べます。

CD RANK PRICE
1 A 100
1 B 200
1 C 300
2 A 120
2 B 220
2 C 320
3 A 130
3 B 230
3 C 330

列が1つであれば UNPIVOT を使用することでできますが、
複数あると、 UNPIVOT を使いながら、 JOIN したり面倒です。

CROSS APPLY を使用することで少ないコードで実行できます。

SELECT CD
      ,v.NO
      ,v.RANK
      ,v.PRICE
FROM TABLENAME
CROSS APPLY
(values ('01' ,RANK1 ,PRICE1),
        ('02' ,RANK2 ,PRICE2),
        ('03' ,RANK3 ,PRICE3),
) v(NO
   ,RANK
   ,PRICE)

上記では行NOを付けているので、実行結果として以下のようになります。

CD NO RANK PRICE
1 01 A 100
1 02 B 200
1 03 C 300
2 01 A 120
2 02 B 220
2 03 C 320
3 01 A 130
3 02 B 230
3 03 C 330
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?