如何取平均时间列并将输出显示为时间

时间:2019-08-26 11:12:27

标签: mysql datetime

我想取时间列的平均值并将输出显示为时间列

我写了一个SQL查询,给我错误的输出。

SELECT
  SOD_EOD_Job_Ran_Date,
  cast(avg(SOD_End_Time) as time),
  avg(SOD_End_Time)
FROM aap_auto
group by SOD_EOD_Job_Ran_Date;

这是输入

SOD_EOD_Job_Ran_Date, SOD_End_Time
2019-08-09 00:00:00, 05:45:00

2019-08-09 00:00:00, 05:50:00

2019-08-09 00:00:00, 06:00:00

2019-08-09 00:00:00, 05:40:00

2019-08-09 00:00:00, 05:48:00

2019-08-09 00:00:00, 05:55:00

2019-08-09 00:00:00, 05:35:00

2019-08-09 00:00:00, 05:38:00

2019-08-09 00:00:00, 05:42:00

2019-08-09 00:00:00, 05:36:00

这是输出

SOD_EOD_Job_Ran_Date, cast(avg(SOD_End_Time) as time), avg(SOD_End_Time)

2019-08-09 00:00:00, null, 54890.0000

此处“ cast”将null作为输出。 在某些情况下,此查询给出了正确的输出

SOD_EOD_Job_Ran_Date, cast(avg(SOD_End_Time) as time), avg(SOD_End_Time)

2019-08-10 00:00:00, 05:46:20, 54620.0000

1 个答案:

答案 0 :(得分:1)

如果已经尝试将SOD_End_Time作为varchar和时间来尝试,而我却没有得到您的时间

let a = 1;
let b = 0.8;
let c = a-b

你与

CREATE TABLE aap_auto
(`SOD_EOD_Job_Ran_Date` datetime, `SOD_End_Time` varchar(8))
;

INSERT INTO aap_auto
(`SOD_EOD_Job_Ran_Date`, `SOD_End_Time`)
VALUES
('2019-08-09 00:00:00', '05:45:00'),
('2019-08-09 00:00:00', '05:50:00'),
('2019-08-09 00:00:00', '06:00:00'),
('2019-08-09 00:00:00', '05:40:00'),
('2019-08-09 00:00:00', '05:48:00'),
('2019-08-09 00:00:00', '05:55:00'),
('2019-08-09 00:00:00', '05:35:00'),
('2019-08-09 00:00:00', '05:38:00'),
('2019-08-09 00:00:00', '05:42:00'),
('2019-08-09 00:00:00', '05:36:00')
;

以下结果

SELECT
  SOD_EOD_Job_Ran_Date,
  TIME_FORMAT(SEC_TO_TIME(avg(TIME_TO_SEC(SOD_End_Time))),'%H:%i%s' ),
  avg(SOD_End_Time)
FROM aap_auto
group by SOD_EOD_Job_Ran_Date;