Förutsatt att du saknar en post i din avtalstabell för 2012-02 är det alltid bra att ha en tabell som bara innehåller datum.
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();
Justera datumintervallet efter dina behov.
Sedan kan du skriva din fråga så här. Jag förenklade det lite, eftersom jag inte såg något behov av dina variabler eller underfrågan.
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
UPPDATERING:
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