i have this query
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(`acceptDate`, '%Y%M') AS timeUnit
FROM `agreements`
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
Output:
userId timeUnit sum count avg
4 201001 6000 1 6000.0000
4 201003 12000 2 6000.0000
4 201004 19500 3 6500.0000
But as you can see, there is a gap between some dates and I want the output to be a contiguous range eg:
userId timeUnit sum count avg
4 201001 6000 1 6000.0000
4 201002 0 2 3000.0000
4 201003 12000 3 6000.0000
4 201004 19500 4 4875.0000
This Query
(SELECT DATE_FORMAT(`acceptDate`, '%Y%M') AS timeUnit FROM `agreements` GROUP BY timeUnit )
Outputs the full date range, but when I try to LEFT JOIN the two Querys, the count and avg gets all messed up. How can I get the result am looking for?
Assuming you are missing an entry in your agreements table for 2012-02, it’s always good to have a table containing simply dates.
Adjust the date range according to your needs.
Then you can write your query like the following. I simplified it a bit, since I saw no need for your variables or the subquery.
UPDATE: