Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 根据SQL中的值获取最大时间_Mysql_Sql - Fatal编程技术网

Mysql 根据SQL中的值获取最大时间

Mysql 根据SQL中的值获取最大时间,mysql,sql,Mysql,Sql,我对Sql有一个问题 我有一个记录运行状态变化的表。这就像在下面 装备 TS 斯达 A. 12/31/2020 19:55:10 0 A. 01/06/2020 16:47:59 1. B 12/27/2020 21:39:20 1. B 12/29/2020 01:01:32 0 C 12/29/2020 01:00:54 1. C 12/29/2020 01:01:32 0 您可以使用行数分析功能,如下所示: select count(*) from (select t.*,

我对Sql有一个问题

我有一个记录运行状态变化的表。这就像在下面

装备 TS 斯达 A. 12/31/2020 19:55:10 0 A. 01/06/2020 16:47:59 1. B 12/27/2020 21:39:20 1. B 12/29/2020 01:01:32 0 C 12/29/2020 01:00:54 1. C 12/29/2020 01:01:32 0
您可以使用
行数
分析功能,如下所示:

select count(*) from
(select t.*,
       row_number() over (partition by equip order by ts desc) as rn
  from t) t
where rn = 1 and stat = 1
select count(*) from t
 where t.stat = 1
   and not exists 
       (select 1 from t tt
         where tt.equip = t.equip and tt.ts > t.ts)
您还可以使用
不存在
,如下所示:

select count(*) from
(select t.*,
       row_number() over (partition by equip order by ts desc) as rn
  from t) t
where rn = 1 and stat = 1
select count(*) from t
 where t.stat = 1
   and not exists 
       (select 1 from t tt
         where tt.equip = t.equip and tt.ts > t.ts)

您可以通过两个级别的聚合来实现这一点。此查询获取当前正在运行的设备:

select equip
from t
group by equip
having max(ts) = max(case when stat = 1 then ts end);
它检查最大值
ts
是否与状态值为
1
的最大值相同

如果要计算值而不是返回值,则可以使用子查询:

select count(*)
from (select equip
      from t
      group by equip
      having max(ts) = max(case when stat = 1 then ts end)
     ) e;

运行设备?是什么告诉我们它正在运行