0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

データを縦並びにする(UNPIVOT、CROSS APPLY)

Last updated at Posted at 2025-01-22

はじめに

SQLServerで横並びを縦並びにするクエリ「UNPIVOT」と「CROSS APPLY」のサンプルを纏めておきます。
横並びから縦並びへの変換では「UNION」を使いがちですが、カラム数が多い場合は「UNPIVOT」や「CROSS APPLY」が有効です。

縦並びから横並びへの変換クエリは以下の記事に書いています。

サンプル

テーブル構成

学籍番号 学年 国語 数学 英語 社会 理科
20220101 1 A 83 65 30 57 22
20220102 1 A 78 30 95 35 59
20220103 1 A 31 65 51 34 83

UNPIVOT

SELECT [学籍番号]
     , [学年]
     , []
     , [科目]
     , [点数]
  FROM [v_student_score]
UNPIVOT ([点数] FOR [科目] IN ([国語], [数学], [英語], [社会], [理科])) AS T

結果

学籍番号 学年 科目 点数
20220101 1 A 国語 83
20220101 1 A 数学 65
20220101 1 A 英語 30
20220101 1 A 社会 57
20220101 1 A 理科 22
20220102 1 A 国語 78
20220102 1 A 数学 30

CROSS APPLY

SELECT [学籍番号]
     , [学年]
     , []
     , [科目]
     , [点数]
  FROM [v_student_score]
 CROSS APPLY (VALUES ('国語', [国語])
                   , ('数学', [数学])
                   , ('英語', [英語])
                   , ('社会', [社会])
                   , ('理科', [理科])
             ) V(科目,点数)
 ORDER BY [学年]
        , []
        , [学籍番号]

結果は「UNPIVOT」と同じです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?