【问题标题】:How to fetch last record for each day in a given group of records?如何获取给定记录组中每一天的最后一条记录?
【发布时间】:2017-12-15 09:06:51
【问题描述】:

我有一个结构如下的表:

 id | service_name | subscribers_count | date
 1  | service 1    | 1                 | 2017-07-01 01:01:01
 2  | Service 1    | 2                 | 2017-07-01 01:01:02
 3  | Service 1    | 3                 | 2017-07-02 01:01:01
 4  | Service 1    | 2                 | 2017-07-03 01:01:01
 5  | Service 1    | 3                 | 2017-07-04 01:01:01
 6  | Service 2    | 1                 | 2017-07-01 01:01:01
 7  | Service 2    | 2                 | 2017-07-01 01:01:02
 8  | Service 2    | 3                 | 2017-07-01 01:01:03
 9  | Service 2    | 4                 | 2017-07-02 01:01:01

获取每项服务的最后一条记录很容易,但我需要更多 - 我需要获取每天每项服务的最后一条记录。这是我期望得到的:

2  | Service 1    | 2                 | 2017-07-01 01:01:02
3  | Service 1    | 3                 | 2017-07-02 01:01:01
4  | Service 1    | 2                 | 2017-07-03 01:01:01
5  | Service 1    | 3                 | 2017-07-04 01:01:01
8  | Service 2    | 3                 | 2017-07-01 01:01:03
9  | Service 2    | 4                 | 2017-07-02 01:01:01

最有效的写法是什么?

【问题讨论】:

标签: mysql sql


【解决方案1】:

一种方法是where 子句中的相关子查询:

select t.*
from t
where t.date = (select max(t2.date)
                from t t2
                where t2.service_name = t.service_name and
                      date(t2.date) = date(t.date)
               );

【讨论】:

  • (service_name) - 虽然我同意它应该是一个 id
【解决方案2】:

使用您自己的解决方案...

SELECT t1.* 
  FROM messages t1
  JOIN 
     ( SELECT from_id
            , SOMETHING HERE
            , MAX(timestamp) timestamp 
         FROM messages 
        GROUP 
           BY from_id
            , SOMETHING HERE
     ) t2
    ON t1.from_id = t2.from_id 
   AND SOMETHING HERE
   AND t1.timestamp = t2.timestamp;

这个解决方案非常“有效”。尽管您只会欣赏此解决方案与 Gordon 在相当大的数据集上的任何差异,但我怀疑此解决方案的性能会胜过那个解决方案 - 尽管我很高兴被证明是错误的。

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 2016-09-03
    • 2023-01-28
    • 2021-07-23
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    相关资源
    最近更新 更多