【问题标题】:group by with order by query issuegroup by 与 order by 查询问题
【发布时间】: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。

谢谢

【问题讨论】:

标签: sql postgresql group-by


【解决方案1】:

这个呢?

SELECT contact_id, MAX(created_at) AS CreatedAt 
FROM activities 
WHERE activity_type_id = 3 
GROUP BY contact_id 
ORDER BY CreatedAt DESC
limit 40 offset 0

【讨论】:

  • 不包括MAX的订单是否在这里工作?
【解决方案2】:

您需要指定哪个您关心的联系人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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    相关资源
    最近更新 更多