LoginSignup
0
0

条件次第でレコード分割をするSQL

Posted at

ちょっと仕事の関係で、条件次第でレコード分割をするSQLを作成する必要があったので、SQLを記載しました。

環境

sqlite

サンプル要件

条件分岐でレコードを増やすSQL
増殖条件:①山と川がそろう:=>連番1では山、連番2では川を表示
     ②AとBがそろう:=>連番1ではA、連番2ではBを表示
     ③exampleのいずれかを複数持っている。
       :=> A , B, C の順番にいづれか出力する。

image.png

上記のようなテーブルから、以下の結果を出すような感じのSQLですね。
image.png

SQL

/*条件分岐でレコードを増やすSQL
   増殖条件:①山と川がそろう:=>連番1では山、連番2では川を表示
        ②AとBがそろう:=>連番1ではA、連番2ではBを表示
        ③exampleのいずれかを複数持っている。:=> A , B, C の順番にいづれか出力する。
   
*/
WITH seq(num) as ( 
    select
          * 
    from
        (   values (1) 
            union 
            values (2) 
            union 
            values (3) 
            union 
            values (4)))
SELECT
      cast("id" as integer) as id 
    , seq.num as num
    , substr(coalesce("mount",' ')
                  ||coalesce("river",' ')
             , seq.num , 1 ) as "山川" 
    , substr(coalesce("A",' ')
                  ||coalesce("B",' ')
             ,seq.num,1) as AB                               

    , substr(coalesce("example_A",'')
                  ||coalesce("example_B",'') 
                  ||coalesce("example_C",'')
             ,seq.num , 1 ) as example
    , "biko" 

FROM
    "test" as t
   left join seq 
     on seq.num <= (case when
                     --  exampleA~Cが複数ある場合はそれぞれ複数行を返す。(最大3レコード)
                           (case when   t.example_A = 'A' then 1 else 0 end  
                            + case when t.example_B = 'B' then 1 else 0 end
                            + case when t.example_C = 'C' then 1 else 0 end) >= 2
                        AND (case when   t.example_A = 'A' then 1 else 0 end  
                             + case when t.example_B = 'B' then 1 else 0 end
                             + case when t.example_C = 'C' then 1 else 0 end) <= 3 
                        then (case when   t.example_A = 'A' then 1 else 0 end  
                             + case when t.example_B = 'B' then 1 else 0 end
                             + case when t.example_C = 'C' then 1 else 0 end)
                    when 
                     -- AとBが両方そろった場合2レコードを返す(最大2レコード)
                        t.A = 'A' AND t.B = 'B' then 2
                    when 
                     -- 山と川が両方そろった場合2レコードを返す(最大2レコード)
                        t.mount = '山'  AND t.river = '川' then 2
                    else 1
                end) 
                    
order by id, num       

ねっ、簡単でしょ。
やってる技術はjoinとsubstrとかだけだからそんな難しくないよ。多分。

説明は……いる??
多分、説明なくても問題ないと思うけど要望があったら解説する。

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