【问题标题】:SQL return most recent date & time stampSQL 返回最近的日期和时间戳
【发布时间】:2020-05-10 23:14:45
【问题描述】:

我有以下数据,需要查看操作等于“已使用”的最近日期:

CAT STAMP               ACTION
A   05/12/2019 00:13    USED
A   05/12/2019 07:56    USED
A   05/12/2019 09:05    NEW
A   05/12/2019 10:46    NEW
B   20/12/2019 20:50    USED
B   13/01/2020 14:50    USED
B   10/01/2020 22:39    NEW
B   05/12/2019 12:04    NEW

对于以上内容,我需要它返回:

A   05/12/2019 07:56    USED
B   13/01/2020 14:50    USED

对于每个“猫”,每天可能有数百个条目,它需要回顾几年,只返回最近的条目。尝试过 MAX 功能,但由于日期格式的原因,认为它不起作用。

【问题讨论】:

  • 请用您正在使用的数据库标记您的问题。另外,以防万一:stamp 列的数据类型是什么?

标签: sql date datetime max greatest-n-per-group


【解决方案1】:

一种方法是使用相关子查询进行过滤:

select t.*
from mytable t
where 
    t.action = 'USED'
    and stamp = (
        select max(t1.stamp) 
        from mtable t1 
        where t1.cat = t.cat and t1.action = t.action
    )

另一个典型的解决方案是反left join模式:

select t.*
from mytable t
left join mytable t1
    on  t1.cat = t.cat
    and t1.action = t.action
    and t1.stamp > t.stamp
where t.action = 'USED' and t1.cat is null

两种解决方案都假定stamp 存储在类似date 的数据类型中。如果不是,那么您需要一个额外的步骤来将字符串转换为日期。

【讨论】:

    【解决方案2】:

    你可以使用子查询:

    select t.*
    from table t 
    where t.action = 'used' and
          t.stamp = (select max(t2.stamp) from table t1 where t1.stamp = t.stamp)
    

    【讨论】:

      【解决方案3】:

      听起来 stamp 被存储为 varchar 而不是 datetime。先试试CAST

      SELECT cat, MAX(CAST stamp AS DateTime) as MxDate, 'used' as Action
      FROM mytable
      WHERE Action = 'used'
      GROUP BY cat
      

      【讨论】:

        【解决方案4】:

        这将是:

        select t.*
        from t 
        where t.stamp = (select min(t2.stamp)
                         from table t2
                         where t2.cat = t.cat and t2.action = 'used' 
                        );
        

        注意过滤是在子查询中。

        或者,也许更简单的是:

        select t.cat, max(t.stamp)
        from t
        where t.action = 'used'
        group by t.cat;
        

        但是,这不允许您返回其他列。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-10-14
          • 1970-01-01
          • 1970-01-01
          • 2015-08-19
          • 2015-02-04
          • 2011-09-26
          • 1970-01-01
          • 2010-10-07
          相关资源
          最近更新 更多