【发布时间】:2017-02-11 10:44:53
【问题描述】:
我有活动表和示例数据,例如
我需要通过activity_type_id 3的created_at desc获取不同的contact_id顺序
我试过了
select distinct contact_id
from activities
where activity_type_id = 3 order by created_at desc limit 40 offset 0
然后 postgres 给出类似的错误
错误:对于 SELECT DISTINCT,ORDER BY 表达式必须出现在选择列表中 第 1 行:...om 活动,其中 activity_type_id = 3 order by created_at...
我解决了这种错误并尝试了查询,但结果不如我预期。
按contact_id 分组并按created_at 顺序分组没有给出正确的结果。
像上面一样,我尝试了分组依据、排序依据、不同等查询组合。
请给我建议。
我想从上面的数据中得到如下所示的 O/P
id | contact_id | activity_type_id | created_at
-------+------------+------------------+---------------------
718006 | 45816 | 3 | 2016-10-03 12:29:57
718005 | 45153 | 3 | 2016-10-03 12:27:01
718204 | 3491 | 3 | 2016-10-03 12:25:14
718186 | 42393 | 3 | 2016-10-03 12:23:00
718172 | 26867 | 3 | 2016-10-03 12:21:07
718171 | 45954 | 3 | 2016-10-03 12:20:09
基本上所有唯一的contact_id order by created_at desc order。
谢谢
【问题讨论】:
-
Select contact_id, min(created_at) as created_at from activities where activity_type_id = 3 group by contact_id order by created_at desc limit 40 offset 0
标签: sql postgresql group-by