[英]SQL - How to get result based on MAX date and GROUP BY
I want to get a result for maximum created_at
and for each application_id
group. 我想获得最大的created_at
和每个application_id
组的结果。 Below are the data sample, 以下是数据示例,
application_id | checkpoint_id | created_at
1 | 260 | 2018-12-28 11:54:52
11 | 259 | 2018-12-24 18:16:30
11 | 260 | 2018-12-26 17:48:58
12 | 260 | 2018-12-26 17:48:58
12 | 261 | 2018-12-26 18:00:00
The result that I want is only for checkpoint_id = 260
. 我想要的结果仅适用于checkpoint_id = 260
。 For example, the result above that I want is application_id
no. 例如,上面我想要的结果是application_id
。 1 & 11. 1&11。
The query that I tried, 我尝试过的查询
SELECT * FROM histories h
WHERE `checkpoint_id` = 260
AND created_at = (
SELECT MAX(`created_at`)
FROM histories
GROUP BY h.application_id, h.checkpoint_id
)
Result 结果
application_id | checkpoint_id | created_at
1 | 260 | 2018-12-28 11:54:52
I am expecting to get 2 rows for id no 1 and 11. Is there a way to do it. 我期望获得ID号为1和11的2行。有没有办法做到这一点。
Update on latest query 最新查询更新
Just to update on my latest query that I achieved to get the expected results. 只是为了更新我为获得预期结果而实现的最新查询。 The query is as below, 查询如下
SELECT * FROM (
SELECT application_id, checkpoint_id, created_at
FROM histories
GROUP BY application_id, checkpoint_id
) AS h
WHERE h.checkpoint_id = 260 AND h.created_at=(
SELECT MAX(`created_at`)
FROM histories h2
WHERE h2.application_id=h.application_id
)
Use a correlated subquery: 使用相关子查询:
SELECT h.*
FROM histories h
WHERE h.checkpoint_id = 260 AND
h.created_at = (SELECT MAX(h.created_at)
FROM histories h2
WHERE h2.application_id = h2.application_id AND
h2.checkpoint_id = h.checkpoint_id
);
Your version is just comparing each created_at
to a created_at
that is the maximum for any application/checkpoint combination. 您的版本只是将每个created_at
与created_at
进行比较,后者是任何应用程序/检查点组合的最大值。 You want the one that is specifically for your combination. 您需要一个专门用于您的组合的产品。
My approach: 我的方法:
SELECT *
FROM histories h
WHERE h.checkpoint_id = 260
order by h.created_at desc
LIMIT 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.