LoginSignup
4
5

More than 5 years have passed since last update.

カンマ区切りのセルの中身をソートし直して返すSQL

Posted at

カンマ区切りのセルの中身をソートし直して返すSQL

  • カンマ区切りデータを1カラムに持つことの是非はともかく、事実としてデータが存在する
  • カンマ区切りのセルの中身をソートした状態でレコードを取得したい

実行前データ

-------------------------------------
id         |  comma_column
-------------------------------------
1          |  linux,apple,windows
-------------------------------------
2          |  yamada,tanaka,aso
-------------------------------------

SELECT
     main.id,
     -- 文字列で返す
     array_to_string(
          -- 配列に閉じ込めて
          ARRAY(
               SELECT 
                    -- カンマ区切りをレコードに変換
                    regexp_split_to_table(comma_column,',') as sort
               FROM
                    tableA as sub
               WHERE
                    main.id = sub.id
               ORDER BY 
                    --カンマ区切りでソート
                    regexp_split_to_table(comma_column,',')
          ) ,','
     )as hoge
FROM TableA as main
ORDER BY main.id

SELECTデータ

-------------------------------------
id         |  comma_column
-------------------------------------
1          |  apple,linux,windows
-------------------------------------
2          |  aso,tanaka,yamada
-------------------------------------

4
5
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
4
5