2
1

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 5 years have passed since last update.

【PL/SQL】レコードの縦横変換

Last updated at Posted at 2019-04-03

レコードの縦横変換

やりたいこと

下記の表のように発注ごとに商品の売り上げ金額を持っているような場合に、発注IDごとの集計をするために縦横変換を行いたい。

元データ

発注ID 商品 金額
TK001 コーヒー 200
TK001 緑茶 300
TK001 ほうじ茶 400
TK002 コーヒー 500
TK002 ほうじ茶 600

縦横変換後

発注ID コーヒー 緑茶 ほうじ茶
TK001 200 300 400
TK002 500 0 600

サンプルコード

発注IDごとにデータをGROUP BYを行い、その合計額を取ります。
合計額にする必要がない場合はSUMMAXなどに変え、1レコードのみ取得するなどの方法が取れます。

SELECT 発注ID,
       SUM(CASE WHEN 商品 = 'コーヒー' THEN 金額 END) AS コーヒー,
       SUM(CASE WHEN 商品 = '緑茶'     THEN 金額 END) AS 緑茶,
       SUM(CASE WHEN 商品 = 'ほうじ茶' THEN 金額 END) AS ほうじ茶
FROM 元データ
GROUP BY 発注ID
;
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?