Postgres group by with order by不返回唯一记录

时间:2015-09-15 04:24:01

标签: sorting group-by unique distinct postgresql-9.1

我正在编写一个查询,以便从unique school_id表中按最新school id获取school_images订单。这是我的询问。

select school_id, id from school_images group by id order by id desc

这是表结构 -

id integer primary key
school_id integer
school_image varchar

目前结果显示如下。那些并不是唯一的 -

38705 
185 
185 
185 
22413 
3670 
3670 
24814 
22814 
17911 
16272 
18417 
17152 
24210 

我期待像 -

这样的结果
38705 
185 
22413 
3670 
24814 
17911 
16272 
18417 
17152 
24210 

另外,我不想按school_id排序。我想对主键或日期排序如下 -

select school_id, id 
from school_images group by id 
order by id desc 

select school_id, created 
from school_images 
group by id 
order by created desc

两者都提供重复记录。

1 个答案:

答案 0 :(得分:0)

尝试此查询,它将正常工作

select school_id,id 
from school_images 
where CTID in (select max(CTID) from school_images group by school_id)
order by school_id

这里我使用了行的CTID,这对于postgres sql中的每一行都是唯一的。