根据状态(开/关)计算差异时间戳

时间:2019-06-12 06:52:28

标签: mysql sql timestamp

我正在尝试计算MySQL的总(每日)正常运行时间和总停机时间。我得到了以下数据库:

CREATE TABLE `IOT_DATA` (
  `DATA_ID` int(11) NOT NULL,
  `DATA_BRON` text NOT NULL,
  `DATA_SOORT` text NOT NULL,
  `DATA_WAARDE` int(11) NOT NULL,
  `DATA_TIJD` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `IOT_DATA` (`DATA_ID`, `DATA_BRON`, `DATA_SOORT`, `DATA_WAARDE`, `DATA_TIJD`) VALUES
(931, '77', 'temperature', 29, '2019-06-11 14:05:00'),
(932, '77', 'humidity', 32, '2019-06-11 14:05:00'),
(933, '77', 'temperature', 30, '2019-06-11 14:10:01'),
(934, '77', 'humidity', 32, '2019-06-11 14:10:01'),
(935, '77', 'temperature', 30, '2019-06-11 14:15:00'),
(936, '77', 'humidity', 31, '2019-06-11 14:15:00'),
(963, '77', 'status', 0, '2019-06-11 14:17:19'),
(978, '77', 'status', 1, '2019-06-11 14:18:40'),
(982, '77', 'temperature', 29, '2019-06-11 14:20:00'),
(983, '77', 'humidity', 32, '2019-06-11 14:20:00'),
(993, '77', 'status', 0, '2019-06-11 14:22:40'),
(1008, '77', 'status', 1, '2019-06-11 14:23:21'),
(1019, '77', 'status', 0, '2019-06-11 14:24:50'),
(1044, '77', 'temperature', 30, '2019-06-11 14:25:00'),
(1045, '77', 'humidity', 32, '2019-06-11 14:25:00'),

ALTER TABLE `IOT_DATA`
  ADD PRIMARY KEY (`DATA_ID`);

ALTER TABLE `IOT_DATA`
  MODIFY `DATA_ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1070;

它保存了机器上的所有传感器数据。 “ DATA_SOORT”“状态”指示机器是启动(1)还是停止(0)。

我不知道从哪里开始,我搜索了类似的主题并得到了这个信息:

select 
    date, 
    DATA_ID, 
    sum(datediff(minute, starttime, endtime )) downtime 
from (
    select 
       cast(t1.DATA_TIJD as date) as date, 
       t1.serviceid, 
       min(t1.DATA_TIJD) starttime, 
       ca.DATA_TIJD endtime
    from IOT_DATA t1
    cross apply (
       select top 1 DATA_TIJD
       from IOT_DATA
       where serviceid = t1.serviceid 
       and DATA_TIJD > t1.DATA_TIJD 
       and DATA_SOORT = "status"
       and DATA_WAARDE in (1) 
       order by DATA_TIJD
    ) ca
    where t1.DATA_ID in (0)
    group by cast(t1.DATA_TIJD as date), t1.DATA_ID, ca.DATA_TIJD
) a
group by date, DATA_ID;

这是行不通的,说实话这是什么。它给出了以下错误:

- Incorrect parameter count in the call to native function 'datediff'

所以我搜索了该错误并得到了类似的信息,它只能处理两个表达式?但是我什至不确定这是否是正确的方法。

预期结果应该是

+------------+--------+----------+------------+--------------+
|    Date    | Source | TotaleUp | TotaleDown | PercentageUp |
+------------+--------+----------+------------+--------------+
| 11-06-2019 |     77 | 04:30:20 | 3:30:40    | 56%          |
| 12-06-2019 |     77 | 06:00:00 | 1:00:00    | 85%          |
+------------+--------+----------+------------+--------------+

来源= DATA_BRON 百分比百分比= Totaleup /(Totaleup + TotaleDown)* 100

这是我的第一个话题,如果有什么遗漏,请告诉我

0 个答案:

没有答案