Hvis du antager, at du mangler en post i din aftaletabel for 2012-02, er det altid godt at have en tabel, der blot indeholder datoer.
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();
Juster datointervallet efter dine behov.
Så kan du skrive din forespørgsel som følgende. Jeg forenklede det lidt, da jeg ikke så noget behov for dine variabler eller underforespørgslen.
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
OPDATERING:
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