【问题标题】:MySQL Current and Past StatusMySQL 当前和过去的状态
【发布时间】:2016-11-30 17:41:02
【问题描述】:

我有一个数据库,在一个属性的一个表下保存状态。

应用状态

标识 |状态 |时间戳

1 | WAITING | 2014-07-10 00:33:14 1 | SENT | 2014-07-10 00:34:14 1 | RECEIVED | 2014-07-10 00:35:14 1 | SENT TO CUST | 2014-07-10 00:36:14 1 | COMPLETE | 2014-07-10 00:37:14 2 | WAITING | 2014-07-10 00:33:14 2 | SENT | 2014-07-10 00:34:14 2 | RECEIVED | 2014-07-10 00:35:14 2 | WAITING | 2014-07-10 00:36:14 2 | SENT | 2014-07-10 00:37:14

我正在尝试计算在特定时间范围内(例如今天)从 RECEIVED 到 SENT TO CUST 的 ID 计数。为了进一步解释,如果他们曾经处于特定状态,我可以获得 ID 的计数。但是,我无法确定有多少 ID 从特定状态变为另一种状态。即当前处于 SENT TO CUST 且过去的确切状态为 RECEIVED 的 ID。

【问题讨论】:

  • 预期的输出是?
  • 已编辑...抱歉,如果需要更多信息,请告诉我。我是新手。

标签: mysql mysql-workbench


【解决方案1】:

嗯。这是一种相对简单的方法,可能足够接近。获取时间范围内的第一个“received”和最后一个“sent to cust”并进行比较:

select count(*)
from (select id,
             min(case when status = 'RECEIVED' then timestamp end) as ts_received,
             min(case when status = 'SENT TO CUST' then timestamp end) as ts_senttocust
      from t
      where timestamp between ?? and ??
      group by id
     ) t
where ts_received < ts_senttocust;

这告诉你收到是之前,但不一定是之前。

【讨论】:

    【解决方案2】:

    这应该可以解决问题(使用tableName 作为表名):

    select count(*)
    from tableName main
    where
        exists (
          select *
          from tableName temp1
          where temp1.ID = main.ID and
                temp1.Status = 'RECEIVED' and
                ( select temp2.Status
                  from tableName
                  where temp2.ID = temp1.ID and
                        temp2.TimeStamp < temp1.TimeStamp
                  order by temp2.TimeStamp desc
                  limit 1) = 'SENT TO CUST'
        )
    

    发生了什么:

    计算tableName 中出现RECEIVED 状态后紧跟SENT TO CUST 状态的记录。

    如果我需要进一步解释,请告诉我。

    【讨论】:

      猜你喜欢
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多