我们有一个包含两个字段tkTimeOpen和tkTimeClosed的表。我们需要找到本月和上个月的平均等待时间。我一直无法获得正确的SQL查询来提取我需要的内容。
这是记录日期时间的方式; 2017-01-25 10:35
本月的平均值;
SELECT SUM(DATEDIFF(MINUTE,tkTimeOpen,tkTimeClose)) * 1.0
/ (SELECT COUNT(*) * 1.0 FROM e_ticket)
FROM e_ticket
WHERE YEAR(tkTimeOpen) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND MONTH(tkTimeOpen) = MONTH(CURRENT_DATE - INTERVAL 0 MONTH)
上个月的平均值
SELECT SUM(DATEDIFF(MINUTE,tkTimeOpen,tkTimeClose)) * 1.0
/ (SELECT COUNT(*) * 1.0 FROM e_ticket)
FROM e_ticket
WHERE YEAR(tkTimeOpen) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND MONTH(tkTimeOpen) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
我尝试了很多变化,但它没有提供所需的输出。 如果有人能提供帮助那就太棒了!
谢谢
答案 0 :(得分:1)
这应该会给你上个月和本月的平均分钟数:
SELECT AVG(TIMESTAMPDIFF(MINUTE, tkTimeOpen, tkTimeClose))
FROM e_ticket
WHERE tkTimeOpen >= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1 DAY);
如果你仍然需要单独获得平均值,你可以保持你的WHERE子句与你拥有的相似......
这个月:
SELECT AVG(TIMESTAMPDIFF(MINUTE, tkTimeOpen, tkTimeClose))
FROM e_ticket
WHERE YEAR(tkTimeOpen) = YEAR(NOW()) AND MONTH(tkTimeOpen) = MONTH(NOW());
上个月:
SELECT AVG(TIMESTAMPDIFF(MINUTE, tkTimeOpen, tkTimeClose))
FROM e_ticket
WHERE YEAR(tkTimeOpen) = YEAR(NOW() - INTERVAL 1 MONTH) AND MONTH(tkTimeOpen) = MONTH(NOW() - INTERVAL 1 MONTH);
答案 1 :(得分:0)
TIMESTAMPDIFF
- 而不是DATEDIFF
AVG()
代替SUM() / COUNT()
SELECT AVG(TIMESTAMPDIFF(MINUTE,tkTimeOpen,tkTimeClose))
FROM e_ticket
WHERE YEAR(tkTimeOpen) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(tkTimeOpen) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)