LoginSignup
2
1

More than 3 years have passed since last update.

postgres distinctしたカラムと別でorder byしたい!

Posted at

問題
取り出したいものは、重複なくしたidですがその並びを時間や数字で並び替えた状況で、idをとってきたい!

テーブルA
id 時間
1   2時
2   3時
3   11時   
1   10時
1   8時

この時、単純に
select distinct id from テーブルA order by 時間
では、
SELECT DISTINCT, ORDER BY expressions must appear in select list
と出る。
これは、order byで指定するものはdistinctで指定したカラムでないといけない。

解決策
サブクエリを使う
select * from (select distinct on (id) * from テーブルA) subA order by 時間;

手順1
サブクエリで重複なくしたレコードを生成。

そのレコードの中で、並び替える

ポイント
①distinctではなく、distinct onを使う。distinctのみでは、単一のカラムが出てきてしまう。ここで出したいのは、時間を出して時間で並び変えたいから、distinct onして*でカラム指定で全フィールド取り出す。

②サブクエリの後の()の後の名前をつける必要がある。(任意の名前)

③全フィールド出した結果、最後に時間でorder byする。

2
1
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
2
1