2012-11-26 103 views
0

我有這個疑問如何加入,創建日期範圍?

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 

輸出:

userId timeUnit sum count avg 
4   201001 6000 1 6000.0000 
4   201003 12000 2 6000.0000 
4   201004 19500 3 6500.0000 

但你可以看到,有一些日期之間的差距,我所要的輸出是一個連續的範圍如:

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 

此查詢

(SELECT DATE_FORMAT(`acceptDate`, '%Y%M') AS timeUnit FROM `agreements` GROUP BY timeUnit) 

輸出完整的日期範圍,但是當我嘗試左連接兩個Querys時,計數和平均值都被搞砸了。我如何得到結果正在尋找?

+1

是否表'agreements'有TIMEUNIT的字段值201002?該查詢可能取決於此。 – SubRed

回答

1

假設您在2012-02年的協議表中缺少一個條目,最好有一個包含簡單日期的表。

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(); 

根據您的需要調整日期範圍。

然後你可以編寫你的查詢,如下所示。我簡化了一下,因爲我看到不需要你的變量或子查詢。

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 

UPDATE:

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 
+0

如果我使用你的解決方案,並刪除變量,我每月計數/平均值和總和,我需要得到累積有沒有辦法呢? –

+0

@羅賓對不起,我沒有得到你想要的。在你的查詢中,你也可以獲得每月的數據。它應該是相同的結果。 – fancyPants

+0

只有日期是每月,例如總和就是上個月和之前的月份總和加上的總和等等。 –