1

テーブルの 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
4

2 に答える 2

0

あなたがコメントで言ったように: created_on=date_trunc('day', now())、したがって、フィールドのデータ型created_onは ですtimestamp。できることは次のとおりです。

SELECT table_1.id, table_1.number, max(created_on) as created_on
  FROM table_1
  inner join table_2 using(number)
  group by table_1.id, table_1.number
于 2013-04-05T11:12:26.890 に答える
0

の列はDISTINCT ON()、クエリの最初の列である必要がありORDER BYます。また、最新の created_on 日付が必要な場合は、並べ替える必要がありますcreated_on DESC

SELECT DISTINCT ON (Table1.number) Table1.id, Table2.number, Table2.created_on 
FROM Table1
JOIN Table2 
  ON Table1.number=Table2.number
ORDER BY Table1.number,Table2.created_on DESC;

http://sqlfiddle.com/#!12/5538a/2

于 2013-04-05T11:18:12.290 に答える