Dengan asumsi Anda kehilangan entri dalam tabel perjanjian Anda untuk 2012-02, selalu baik untuk memiliki tabel yang hanya berisi tanggal.
CREATE TABLE dates(`date` date primary key);
DROP PROCEDURE IF EXISTS insertDates;
DELIMITER $$
CREATE PROCEDURE insertDates()
BEGIN
SET @start_date = '2010-01-01';
WHILE (@start_date <= '2010-12-31') DO
INSERT INTO dates VALUES (@start_date);
SET @start_date:=DATE_ADD(@start_date, INTERVAL 1 DAY);
END WHILE;
END $$
DELIMITER ;
CALL insertDates();
Sesuaikan rentang tanggal sesuai kebutuhan Anda.
Kemudian Anda dapat menulis kueri Anda seperti berikut ini. Saya menyederhanakannya sedikit, karena saya tidak melihat perlunya variabel atau subkueri Anda.
SELECT userId, DATE_FORMAT(dates.`date`, '%Y%M') AS timeUnit,
SUM(orderValue),
COUNT(orderValue),
AVG(orderValue)
FROM
dates LEFT JOIN
`agreements` ON dates.date = agreements.acceptDate
WHERE userId = 4
AND acceptDate > '2000-00-00'
GROUP BY userId, timeUnit
PERBARUI:
SELECT userId, orgQuery.timeUnit,
@SUM := @SUM + orgQuery.orderValue AS sum,
@COUNT := @COUNT + 1 AS count,
@AVG := @SUM / @COUNT AS avg
FROM (
SELECT userid, orderValue,
DATE_FORMAT(dates.`date`, '%Y%M') AS timeUnit
FROM dates LEFT JOIN
`agreements` ON dates.date = agreements.acceptDate
WHERE userId = 4
AND acceptDate > '2000-00-00'
GROUP BY timeUnit
)
AS orgQuery,
(SELECT @COUNT := 0, @SUM := 0,@AVG :=0)
AS extra GROUP BY timeUnit