SQLServerのT-SQLではPIVOTを利用すると、簡単に行と列を入れ替える(縦横変換)ことができます。
本来であれば複雑な福問合せなどを駆使して実現するのですがPIVOT句を使うことで通常のSELECT文と変わらない構文で行と列を入れ替え(縦横変換)られます。
SQL ServerのPIVOT
PIVOTは、テーブル値式の中のある列から一意の値を取得して出力側の複数の列に変換することで式を行列(縦横)変換し、最終的な出力のそれ以外の列値に必要な集計を行います。
PIVOTの構文は以下の通りです。
SELECT <non-pivoted column>, [first pivoted column] AS <column name>, [second pivoted column] AS <column name>, ... [last pivoted column] AS <column name> FROM (<SELECT query that produces the data>) AS <alias for the source query> PIVOT ( <aggregation function>(<column being aggregated>) FOR [<column that contains the values that will become column headers>] IN ( [first pivoted column], [second pivoted column], ... [last pivoted column]) ) AS <alias for the pivot table> <optional ORDER BY clause>;
PIVOTの使用例
準備として1行「name」と「subject」、「tokuten」を持ったテーブルを用意し、そのデータを人ごとに各科目の得点を1行として出力します。
実際のSQLは以下の通りです。
--TABLE CREATE CREATE TABLE tokuten_tbl ( name VARCHAR(10) ,subject VARCHAR(20) ,tokuten SMALLINT ); --DATAINSERT INSERT INTO tokuten_tbl VALUES ('John', 'English', 20 ) ; INSERT INTO tokuten_tbl VALUES ('John', 'Japanese', 30 ) ; INSERT INTO tokuten_tbl VALUES ('John', 'Mathematics', 40 ) ; INSERT INTO tokuten_tbl VALUES ('John', 'Science', 50 ) ; INSERT INTO tokuten_tbl VALUES ('John', 'SocialStudies', 60 ) ; INSERT INTO tokuten_tbl VALUES ('Mike', 'English', 100 ) ; INSERT INTO tokuten_tbl VALUES ('Mike', 'Japanese', 90 ) ; INSERT INTO tokuten_tbl VALUES ('Mike', 'Mathematics', 80 ) ; INSERT INTO tokuten_tbl VALUES ('Mike', 'Science', 70 ) ; INSERT INTO tokuten_tbl VALUES ('Mike', 'SocialStudies', 60 ) ; INSERT INTO tokuten_tbl VALUES ('Tom', 'English', 50 ) ; INSERT INTO tokuten_tbl VALUES ('Tom', 'Japanese', 40 ) ; INSERT INTO tokuten_tbl VALUES ('Tom', 'Mathematics', 30 ) ; INSERT INTO tokuten_tbl VALUES ('Tom', 'Science', 20 ) ; INSERT INTO tokuten_tbl VALUES ('Tom', 'SocialStudies', 10 ) ; --PIVOT SELECT name ,English ,Japanese ,Mathematics ,Science ,SocialStudies FROM tokuten_tbl PIVOT ( SUM( tokuten ) FOR subject IN ( English, Japanese, Mathematics, Science, SocialStudies )) AS result ORDER BY name; --TABLE DROP DROP TABLE tokuten_tbl
上記のSQLを実行した実行結果は以下のようになります。
name | English | Japanese | Mathematics | Science | SocialStudies |
---|---|---|---|---|---|
John | 20 | 30 | 40 | 50 | 60 |
Mike | 100 | 90 | 80 | 70 | 60 |
Tom | 50 | 40 | 30 | 20 | 10 |