テーブルの 1 つにエントリが重複している postgres データベースがあります。created_by 列を表示したい
表1
id | number
1 | 123
2 | 124
3 | 125
4 | 126
表2
id | number | created_on
1 | 123 | 3/29
2 | 123 | 4/3
3 | 124 | 3/31
4 | 124 | 4/1
表 2 の番号が重複しています。以下をリストする単一のクエリを作成したいと思います。
id | number | created_on
1 | 123 | 4/3
2 | 124 | 4/1
重複したエントリの場合、最新のエントリのみが含まれます。どうすればその SQL クエリを作成できますか?
SELECT DISTINCT ON (Table1.number) Table1.id, Table2.number, Table2.create_on FROM Table1
JOIN Table2 ON Table1.number=Table2.number
ORDER BY Table2.create_on;
実際に、'DISTINCT ON' と 'ORDER BY' を 1 つのクエリ (JOIN を使用) に入れようとすると、次のエラーが発生します。
SELECT DISTINCT ON expressions must match initial ORDER BY expressions