我想计算最近6个月的平均温度。
现在,我有这样的东西:
SELECT AVG(`temp`) FROM `temperature` WHERE YEAR(date) = 2020 AND MONTH(date) = 1 AND `sensor_id` = "00000b858c95"
返回所选月份的平均温度……这是正确的吗?
我的桌子:
CREATE TABLE `temperature` (
`id` int(11) NOT NULL,
`sensor_id` varchar(32) NOT NULL,
`temp` varchar(32) NOT NULL,
`date` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Zrzut danych tabeli `temperature`
--
INSERT INTO `temperature` (`id`, `sensor_id`, `temp`, `date`) VALUES
(1, '00000b845b2b', '38.3', '2019-12-05 20:42:06'),
(2, '00000b858c95', '-1.3', '2019-12-05 20:42:06'),
(3, '00000a035951', '24.7', '2019-12-05 20:42:06'),
(4, '00000b845b2b', '38.4', '2019-12-05 20:43:06'),
(5, '00000b858c95', '-1.2', '2019-12-05 20:43:06'),
(6, '00000a035951', '24.7', '2019-12-05 20:43:06'),
(7, '00000b845b2b', '38.4', '2019-12-05 20:44:06'),
(8, '00000b858c95', '-1.2', '2019-12-05 20:44:06'),
(9, '00000a035951', '24.7', '2019-12-05 20:44:06'),
(10, '00000b845b2b', '38.4', '2019-12-05 20:45:05'),
(11, '00000b858c95', '-1.2', '2019-12-05 20:45:05'),
(12, '00000a035951', '24.7', '2019-12-05 20:45:05'),
(13, '00000b845b2b', '38.5', '2019-12-05 20:46:06'),
(14, '00000b858c95', '-1.3', '2019-12-05 20:46:06'),
(15, '00000a035951', '24.7', '2019-12-05 20:46:06'),
(16, '00000b845b2b', '38.6', '2019-12-05 20:47:06'),
(17, '00000b858c95', '-1.3', '2019-12-05 20:47:06'),
(18, '00000a035951', '24.8', '2019-12-05 20:47:06'),
(19, '00000b845b2b', '38.7', '2019-12-05 20:48:06'),
(20, '00000b858c95', '-1.3', '2019-12-05 20:48:06'),
(21, '00000a035951', '24.9', '2019-12-05 20:48:06'),
(22, '00000b845b2b', '39.1', '2019-12-05 21:00:05'),
(23, '00000b858c95', '-1.4', '2019-12-05 21:00:05'),
(24, '00000a035951', '25.9', '2019-12-05 21:00:05'),
(25, '00000b845b2b', '37.9', '2019-12-05 22:00:06'),
(26, '00000b858c95', '-1.4', '2019-12-05 22:00:06'),
....
我希望它在过去6个月中返回6个结果,每个月返回一个。
答案 0 :(得分:1)
我想计算最近6个月的平均温度。
您似乎想要简单的日期算术:
SELECT AVG(temp) FROM temperature WHERE date >= current_date - interval 6 month
对于今天2020-01-18,这将选择2019-07-17的记录。
或者,如果您想要当月和过去的6个月(即今天,从2019-07-01开始):
WHERE date >= date_format(current_date, '%Y-%m-01') - interval 6 month
如果您想在过去6个月中每月记录一次,则需要按月分组,就像这样:
SELECT DATE_FORMAT(date, '%Y-%m-01') date_month, AVG(temp) avg_temp
FROM temperature
WHERE date >= date_format(current_date, '%Y-%m-01') - interval 6 month
GROUP BY DATE_FORMAT(date, '%Y-%m-01')