mysql 移动平均值 取每条的前5条的平均值

CREATE TABLE `trade_params1` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `PERIOD` int(11) DEFAULT NULL,
  `THEDATE` date DEFAULT NULL,
  `DAYCOUNT` int(11) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;

INSERT INTO `trade_params1` (`ID`,`PERIOD`,`THEDATE`,`DAYCOUNT`) VALUES (1,20,'2018-01-02',7);
INSERT INTO `trade_params1` (`ID`,`PERIOD`,`THEDATE`,`DAYCOUNT`) VALUES (2,20,'2018-01-03',6);
INSERT INTO `trade_params1` (`ID`,`PERIOD`,`THEDATE`,`DAYCOUNT`) VALUES (3,20,'2018-01-04',5);
INSERT INTO `trade_params1` (`ID`,`PERIOD`,`THEDATE`,`DAYCOUNT`) VALUES (4,20,'2018-01-05',7);
INSERT INTO `trade_params1` (`ID`,`PERIOD`,`THEDATE`,`DAYCOUNT`) VALUES (5,20,'2018-01-08',7);
INSERT INTO `trade_params1` (`ID`,`PERIOD`,`THEDATE`,`DAYCOUNT`) VALUES (6,20,'2018-01-09',7);
INSERT INTO `trade_params1` (`ID`,`PERIOD`,`THEDATE`,`DAYCOUNT`) VALUES (7,20,'2018-01-10',7);
INSERT INTO `trade_params1` (`ID`,`PERIOD`,`THEDATE`,`DAYCOUNT`) VALUES (8,20,'2018-01-11',6);
INSERT INTO `trade_params1` (`ID`,`PERIOD`,`THEDATE`,`DAYCOUNT`) VALUES (9,20,'2018-01-12',6);
INSERT INTO `trade_params1` (`ID`,`PERIOD`,`THEDATE`,`DAYCOUNT`) VALUES (10,20,'2018-01-15',5);
INSERT INTO `trade_params1` (`ID`,`PERIOD`,`THEDATE`,`DAYCOUNT`) VALUES (11,20,'2018-01-16',6);
INSERT INTO `trade_params1` (`ID`,`PERIOD`,`THEDATE`,`DAYCOUNT`) VALUES (12,20,'2018-01-17',6);
INSERT INTO `trade_params1` (`ID`,`PERIOD`,`THEDATE`,`DAYCOUNT`) VALUES (13,20,'2018-01-18',6);
INSERT INTO `trade_params1` (`ID`,`PERIOD`,`THEDATE`,`DAYCOUNT`) VALUES (14,20,'2018-01-19',6);
INSERT INTO `trade_params1` (`ID`,`PERIOD`,`THEDATE`,`DAYCOUNT`) VALUES (15,20,'2018-01-22',6);
INSERT INTO `trade_params1` (`ID`,`PERIOD`,`THEDATE`,`DAYCOUNT`) VALUES (16,20,'2018-01-23',6);
INSERT INTO `trade_params1` (`ID`,`PERIOD`,`THEDATE`,`DAYCOUNT`) VALUES (17,20,'2018-01-24',6);
 

子查询取每条的前5条数据的平均值

SELECT b.*,
(
    SELECT avg(t1.daycount) from (
        SELECT t.*,(@rownum := @rownum + 1) AS rownum FROM (SELECT @rownum := 0) r,trade_params1 t 
     ORDER BY  THEDATE desc
    ) t1 WHERE t1.rownum <= b.rownum + 5 and t1.rownum > b.rownum
)
 from ( select b.*,(@rownum := @rownum + 1) AS rownum FROM (SELECT @rownum := 0) r,trade_params1 b ORDER BY b.thedate desc) b

你可能感兴趣的:(sql)