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.

SQLで可変的アンピポット方法(postgresSQLのみ)

Posted at

テーブル上に、項目列数を持つ必要があるけれど、
可変的なアンピポット方法ができたので、備忘録として追加
(PowerQuery、Pythonとかのが楽とかある気がする。)

今回は、金額と税額、また対象の科目になっているものを除外するように作成。
実際はここまでテーブル数は必要ないと思う

--多分、postgres限定のクエリ
with tmp_2 As ( 
select 
    null
    , おいしみ.*
    , null
from おいしみ
)
,tmp AS (
   --select結果を配列に格納
   -- Array[項目A,項目B]が正しいが、動的取得のためジョグ配列っぽく取得
    select array[tmp_2.*] As arr  from tmp_2
    )
    , 配列加工 As (
    -- ジョグ配列を普通の配列に加工
    select string_to_array(arr[1]::text,','::text,'') AS おいしみarr from tmp
     )
     , 添え字 As (
    -- index作成
    select 
      おいしみp.名称
    , おいしみp.列数 As 科目idx
    , おいしみp.列数 + おいしみc.id As idx
    , おいしみp.名称 || おいしみc.名称 As col名称
       from おいしみparameter As おいしみp, おいしみcol As おいしみc
       where おいしみc.計算有無 = True
       
    ) 
    , unpivot As (
    -- unpivotの内容を取得
    select 配列加工.おいしみarr[1+1] As 日付
    , 添え字.名称 As 〇方 
    , おいしみarr[添え字.科目idx+1] As 科目
    , 添え字.col名称 , おいしみarr[添え字.idx+1]::integer  As 金額 from 配列加工, 添え字
 
    )
    -- 集計
    select unpivot.日付 , unpivot.〇方 , unpivot.科目
    , sum(unpivot.金額) As 集計金額
     from unpivot 
     where   unpivot.科目 NOT LIKE '%_対象外'
    group by unpivot.日付 , unpivot.〇方,  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?