SQL-如何根据最大日期和GROUP BY获得结果

时间:2019-01-09 15:20:49

标签: php mysql sql

我想获得最大created_at和每个application_id组的结果。下面是数据示例,

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    

我想要的结果仅适用于checkpoint_id = 260。例如,上面我想要的结果是application_id否。 1&11

我尝试过的查询

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
)

结果

application_id | checkpoint_id | created_at 
1              |  260          | 2018-12-28 11:54:52      

我希望获得ID为1和11的2行。有没有办法做到这一点。

  

更新最新查询

只需更新我为获得预期结果而实现的最新查询即可。查询如下,

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    
)

2 个答案:

答案 0 :(得分:3)

使用相关子查询:

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
                     );

您的版本只是将每个created_at与一个created_at进行比较,这是任何应用程序/检查点组合的最大值。您想要一种专门用于您的组合的商品。

答案 1 :(得分:1)

我的方法:

SELECT * 
FROM histories h 
WHERE h.checkpoint_id = 260
order by h.created_at desc
LIMIT 1