将WHERE和GROUP BY合并到datetime sum MySQL查询中

时间:2018-04-02 19:42:30

标签: php mysql sql

我的查询:

我正在尝试按类别对“持续时间”列进行求和:

SELECT DATE_FORMAT(FROM_UNIXTIME(sum(`duration`)), '%T') AS `totalduration` 
FROM `my_custom_table`
WHERE `category` = "SLE"
GROUP BY `category`

结果为NULL但应为“05:00”。

如果我排除了WHERE和GROUP BY,则查询会正确汇总:

SELECT DATE_FORMAT(FROM_UNIXTIME(sum(`duration`)), '%T') AS `totalduration`
FROM `my_custom_table`

结果正确24:00:00。

如何将WHERE和GROUP BY合并到我的查询中?

我的数据:

一个phpMyAdmin / MySQL表,包含“duration”列(datetime)和“category”列(varchar 255):

0000-00-00 05:00:00 | SLE
0000-00-00 00:30:00 | CLA
0000-00-00 00:30:00 | CLA
0000-00-00 00:15:00 | FOO
0000-00-00 01:45:00 | MON
0000-00-00 00:30:00 | CLA
0000-00-00 01:30:00 | MON
0000-00-00 02:30:00 | CLE
0000-00-00 01:00:00 | CLA
0000-00-00 01:30:00 | MON
0000-00-00 01:00:00 | REC
0000-00-00 00:30:00 | CLA
0000-00-00 01:30:00 | MON
0000-00-00 00:45:00 | CLA
0000-00-00 01:00:00 | FOO
0000-00-00 01:00:00 | REC
0000-00-00 01:00:00 | REC
0000-00-00 01:00:00 | MON
0000-00-00 00:15:00 | NOT
0000-00-00 00:30:00 | CLA
0000-00-00 00:30:00 | CLA

4 个答案:

答案 0 :(得分:2)

我为你创建了一个SQLFiddle:http://sqlfiddle.com/#!9/f31e6a/6/0

查询:

SELECT category, SEC_TO_TIME(SUM(TIME_TO_SEC(duration)))
FROM test
WHERE category = 'SLE'
GROUP BY category;

测试数据:

CREATE TABLE test (duration DATETIME, category TEXT);

INSERT INTO test (duration, category) VALUES
('0000-00-00 05:00:00', 'SLE'),
('0000-00-00 00:30:00', 'CLA'),
('0000-00-00 00:30:00', 'CLA'),
('0000-00-00 00:15:00', 'FOO'),
('0000-00-00 01:45:00', 'MON'),
('0000-00-00 00:30:00', 'CLA'),
('0000-00-00 01:30:00', 'MON'),
('0000-00-00 02:30:00', 'CLE'),
('0000-00-00 01:00:00', 'CLA'),
('0000-00-00 01:30:00', 'MON'),
('0000-00-00 01:00:00', 'REC'),
('0000-00-00 00:30:00', 'CLA'),
('0000-00-00 01:30:00', 'MON'),
('0000-00-00 00:45:00', 'CLA'),
('0000-00-00 01:00:00', 'FOO'),
('0000-00-00 01:00:00', 'REC'),
('0000-00-00 01:00:00', 'REC'),
('0000-00-00 01:00:00', 'MON'),
('0000-00-00 00:15:00', 'NOT'),
('0000-00-00 00:30:00', 'CLA'),
('0000-00-00 00:30:00', 'CLA');

相应的结果:

category    SEC_TO_TIME(SUM(TIME_TO_SEC(duration)))
SLE     05:00:00

答案 1 :(得分:0)

SELECT DATE_FORMAT(FROM_UNIXTIME(sum(`duration`)), '%T') AS `totalduration` 
FROM `my_custom_table`
GROUP BY `category` 
HAVING category = "SLE"

答案 2 :(得分:0)

我认为不需要使用group by,因为where子句只返回一个数据。所以你可以执行以下操作。

SELECT DATE_FORMAT(FROM_UNIXTIME(sum(`duration`)), '%T') AS `totalduration` 
FROM `my_custom_table`
WHERE `category` = "SLE"

如果仍然返回null,您可以执行以下操作。

SELECT DATE_FORMAT(FROM_UNIXTIME(sum(`duration`)), '%T') AS `totalduration` 
FROM `my_custom_table`
WHERE `category` LIKE "%SLE%"

答案 3 :(得分:0)

只需使用to_seconds()

select sum(to_seconds(duration))

如果您想要时间格式:

select sec_to_time(sum(to_seconds(duration)))