Q&A
前提・実現したいこと
グラフを表示するシステムを作っていますが、軸情報が欠けている場合もエラーになったりずれたりしないように、データの列番号を代用として表示したいです。
発生している問題
軸情報のテーブルとデータのテーブルをright joinして、軸の個々のラベルを取得していますが、outer joinで補われるレコードが欠けたままです。
該当のソースコード
sql
1create table stat( 2 id integer 3 , row integer 4 , col integer 5 , data double precision not null 6 , constraint stat_pk1 primary key (id, row, col) 7); 8 9create table axis_item( 10 id integer 11 , row integer 12 , label varchar(30) 13 , constraint axis_item_pk1 primary key (id, row) 14);
bash
1psql (12.8) 2Type "help" for help. 3 4postgres=# \c otnj 5You are now connected to database "otnj" as user "postgres". 6otnj=# select * from stat where id = 2; 7 id | row | col | data 8----+------+-----+---------- 9 2 | 2011 | 1 | 1501660 10 2 | 2012 | 1 | 1848450 11 2 | 2013 | 1 | 2821940 12中略 13 2 | 2018 | 5 | 20378470 14 2 | 2019 | 5 | 27346300 15 2 | 2020 | 5 | 3592790 16 2 | 2011 | 6 | 1169060 17 2 | 2012 | 6 | 1738380 18 2 | 2013 | 6 | 2111660 19 2 | 2014 | 6 | 2845860 20 2 | 2015 | 6 | 4906920 21 2 | 2016 | 6 | 4906270 22 2 | 2017 | 6 | 4996190 23 2 | 2018 | 6 | 5799760 24 2 | 2019 | 6 | 7403690 25 2 | 2020 | 6 | 1037150 26 2 | 2011 | 7 | 269960 27 2 | 2012 | 7 | 375330 28中略 29 2 | 2019 | 10 | 5423450 30 2 | 2020 | 10 | 861960 31(99 rows) 32 33otnj=# select * from axis_item where id = 2; 34 id | row | label 35----+-----+---------- 36 2 | 1 | 北海道 37 2 | 2 | 東北 38 2 | 3 | 関東 39 2 | 4 | 北陸信越 40 2 | 5 | 近畿 41 2 | 7 | 中国 42 2 | 8 | 四国 43 2 | 9 | 九州 44 2 | 10 | 沖縄 45(9 rows) 46 47otnj=# select distinct s.col, trim(coalesce(label, to_char(s.col,'9999999999'))) as label 48 from axis_item a 49 right join 50 stat s on s.col = a.row 51 where 52 (a.id = 2 or a.id is null) 53 and 54 s.id = 2 55 order by s.col; 56otnj-# 57 col | label 58-----+---------- 59 1 | 北海道 60 2 | 東北 61 3 | 関東 62 4 | 北陸信越 63 5 | 近畿 64 7 | 中国 65 8 | 四国 66 9 | 九州 67 10 | 沖縄 68(9 rows) 69 70otnj=#
axis_itemテーブルのrow=6のレコードがないですが、statデーブルにcol=6のレコードがあるので、結果はcol=6 label=6としたいのですが、うまくいきませんので、ご教授お願いいたします。
試したこと
axis_itemテーブルを結合せず、statテーブルだけならばcol=6は出てきますが、テーブル結合を用いずに、axis_itemテーブルの情報とうまく合わせるクエリを思いつきませんでした。
補足情報(FW/ツールのバージョンなど)
PostgreSQL 12.8
回答1件
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。