MySQL当前和过去的状态

时间:2016-07-26 22:05:49

标签: mysql mysql-workbench

我有一个数据库,它在一个属性的一个表下包含状态。

APP STATUS

ID |状态|时间戳

public class SQLConnection { #region MemberVariables private SqlConnection mConnection = null; private SqlDataAdapter mDataAdapter = null; private SqlCommand mCommand = null; static string mDbConnString = string.Empty; #endregion #region PublicMemberVariables public SqlConnection Connection { get { return mConnection; } set { mConnection = value; } } public SqlDataAdapter DataAdapter { get { return mDataAdapter; } set { mDataAdapter = value; } } public SqlCommand Command { get { return mCommand; } set { mCommand = value; } } public string ConnectString { get { return mDbConnString; } set { lock (mDbConnString) { mDbConnString = value; } lock (mConnection) { mConnection.ConnectionString = mDbConnString; } } } #endregion public void TestConnection() { ConnectString = "Data Source=Cyber SQLEXPRESS;Initial Catalog=GeneratedData;Integrated Security=True"; Connection = new SqlConnection(ConnectString); Connection.Open(); MessageBox.Show(Connection.State.ToString()); } }

我试图找出在特定时间范围内从RECEIVED到SENT TO CUST的ID的数量,例如今天。为了进一步解释,如果他们处于特定状态,我可以获得ID的计数。但是,我无法确定ID从一个状态到另一个状态的数量。即目前处于SENT TO CUST状态的ID,并且确切的过去状态为RECEIVED。

2 个答案:

答案 0 :(得分:0)

嗯。这是一个相对简单的方法,可能足够接近。在时间范围内获得第一个“已收到”和最后一个“发送到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;

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

答案 1 :(得分:0)

这应该可以解决问题(使用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状态。

请告诉我是否应该进一步解释。