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?

More than 1 year has passed since last update.

Postgres: Power BI で利用しやすくする為の Pivot SQL

Posted at

背景

Unpivot の反対に Pivot をしたくなったので

概要

Pivot が無いので、Group By して

詳細

変換前:元データ

image.png

変換後:取得したい結果

こんな感じで Pivot したいだけ
image.png

SQL

  • GROUP BY でグルーピング
    • 条件合致するデータだけを Pivot 追加列に取得
      • MIN: 特に意味は無い。取得対象は一点あるかないか、なので、MIN 使ってるだけ
    • COALESCE で存在しない場合の値を定義。例では全部 0
Pivot
SELECT 
    "ID",
    COALESCE(MIN(t0."SubID"), 0)::int AS  SubID,
    COALESCE(MIN(CASE WHEN "isVertical" THEN "length" END), 0)::int AS  Height,
    COALESCE(MIN(CASE WHEN NOT "isVertical" THEN "length" END), 0)::int AS  Width,
    COALESCE(MAX(t0."SubID"), 0)::int AS  SubID2
FROM sampleTable AS t0
GROUP BY "ID"

あとがき

Pivot が無いと気付かず少し悩んでしまった・・

keyword

Equivalent to pivot() in PostgreSQL

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?