[英]MySql Group By and order by date
Here is my table data:这是我的表数据:
id page_id time created
=======================================================
1 1 00:15:00 2020-11-05 09:55:54
2 1 00:25:00 2020-11-10 07:35:24
3 2 00:10:25 2020-11-06 06:15:20
and here is the MySql query:这是 MySql 查询:
SELECT
a.* SUM (a.time) AS time
FROM
`activity` AS a
GROUP BY a.page_id
ORDER BY a.created DESC;
The desired result is to have the latest record showing on top, but instead, Im getting first record being on top;期望的结果是将最新的记录显示在顶部,但相反,我将第一条记录显示在顶部;
Like:喜欢:
2 1 00:25:00 2020-11-10 07:35:24
3 2 00:10:25 2020-11-06 06:15:20
instead I'm getting this:相反,我得到了这个:
1 1 00:15:00 2020-11-05 09:55:54
3 2 00:10:25 2020-11-06 06:15:20
You seem to want the latest record per id
, as defined by created
.您似乎想要每个id
的最新记录,如created
所定义。 If so, you need to filter rather than aggregate.如果是这样,您需要过滤而不是聚合。
In MySQL 8.0, I would suggest window functions:在 MySQL 8.0 中,我建议使用窗口函数:
select *
from (
select a.*,
rank() over(partition by page_id order by created desc) rn
from activity a
) a
where rn = 1
order by created desc
In earlier versions, you can filter with a correlated subquery:在早期版本中,您可以使用相关子查询进行过滤:
select a.*
from activity a
where a.created = (
select max(a1.created) from activity a1 where a1.page_id = a.page_id
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.