按查询分组

迈赫什·卡哈莱

我有活动表和示例数据,例如

在此处输入图片说明

我需要通过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(由created_at排序)...

我解决了此类错误并尝试了查询,但结果与我预期的不同。

按contact_id分组并按created_at desc排序的分组未给出正确的结果。

就像上面我尝试过的,分组依据,排序依据,不同的查询组合等。

请给我建议。

我希望上面的数据像下面这样的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唯一顺序都由created_at desc顺序决定。

谢谢

戈登·利诺夫(Gordon Linoff)

你需要指定哪个你关心接触式ID -因为你有多个行。

使用时select distinct子句中只有中的列select可用order by

因此,使用group byorder by像这样:

select a.contact_id
from activities a
where a.activity_type_id = 3
group by a.contact_id
order by max(a.created_at) desc
limit 40 offset 0;

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章