カラム毎の重複を削除した結果を取得したいです。
distinctではレコード単位の重複削除であり、selectしたカラム毎の重複削除になりません。
また、取得項目毎のselect distinct文をunionする方法も考えましたが、
最終的には6カラムほどselectするので、6つunionする方法もあまり綺麗ではありません。
実現方法をご存知の方にご教示いただきたいです。
下記は実現したい結果のイメージです。
PostgreSQL
1-- 取得元のテーブル 2create table food ( 3 food_code character varying(100) 4 ,food_name character varying(100) 5 ,produnction_code character varying(100) 6 ,produnction_name character varying(100) 7); 8 9-- データを投入 10insert into food values( 11 '001' 12 ,'りんご' 13 ,'AAA' 14 ,'会社AAA' 15); 16 17insert into food values( 18 '001' 19 ,'りんご' 20 ,'BBB' 21 ,'会社BBB' 22); 23 24insert into food values( 25 '002' 26 ,'バナナ' 27 ,'AAA' 28 ,'会社AAA' 29); 30-- 試したselect文 31select 32 array_to_string(food_code,','), 33 array_to_string(food_name,','), 34 array_to_string(produnction_code,',') 35-- into out_food_code,out_food_name, out_produnction_code 36from food;
2022/2/2 23:09 追記
下記select文で行えるかもしれませんが、手元に実行環境がないため、3日に試します。
select array_to_string(array_agg(distinct food_code), ','), array_to_string(array_agg(distinct food_name), ','), array_to_string(array_agg(distinct produnction_code), ',') -- into out_food_code,out_food_name, out_produnction_code from food
2022/2/3 19:27 追記
実現したい取得結果は下記の通りです。
food_code | food_name | produnction_code |
---|---|---|
001,002 | りんご,バナナ | AAA,BBB |
下記SQLにて実現は出来ましたが、よりすっきりとしたコードに出来ないか模索中です。
select array_to_string(array_agg(distinct food_code), ','), array_to_string(array_agg(distinct food_name), ','), array_to_string(array_agg(distinct produnction_code), ',') -- into out_food_code,out_food_name, out_produnction_code from food
回答1件
あなたの回答
tips
プレビュー