2013-09-29 123 views
1

我需要的輸出是這樣的:MySQL的一個月明智的報告

Month -->| Pre_Mnth2 | Pre_Mnth1 | current_Month_ Name 
Product A | 3387 | 87985 | 2338 
Product B | 6386 | 67983 | 6374 
Product C | 3880 | 76988 | 9378 

... 

所有需要的數據是唯一的單表。

列如下:

id | companycode | merchantcode| pdtname | qty | value | invdate | 

任何人可以幫助我用PHP MySQL查詢代碼?

我當前的代碼返回數據,當月僅

SELECT `pdtname`, `qty`, `value`, sum(`qty`), sum(`value`) 
FROM `ist` 
WHERE merchantcode = $q AND companycode = $companycode 
    AND MONTH(invdate) = $currentdate[mon] 
GROUP BY `pdtname` 

這裏變量$q$companycode從用戶的會議上作出。

+0

你需要每個月在結果一個單獨的列? – Nikhil

回答

2

你在找這樣的事嗎?

SELECT pdtname, 
     SUM(CASE WHEN invdate 
      BETWEEN LAST_DAY(CURDATE()) - INTERVAL 3 MONTH + INTERVAL 1 DAY 
       AND LAST_DAY(CURDATE()) - INTERVAL 2 MONTH THEN qty END) qty_2m, 
     SUM(CASE WHEN invdate 
      BETWEEN LAST_DAY(CURDATE()) - INTERVAL 3 MONTH + INTERVAL 1 DAY 
       AND LAST_DAY(CURDATE()) - INTERVAL 2 MONTH THEN value END) value_2m, 
     SUM(CASE WHEN invdate 
      BETWEEN LAST_DAY(CURDATE()) - INTERVAL 2 MONTH + INTERVAL 1 DAY 
       AND LAST_DAY(CURDATE()) - INTERVAL 1 MONTH THEN qty END) qty_1m, 
     SUM(CASE WHEN invdate 
      BETWEEN LAST_DAY(CURDATE()) - INTERVAL 2 MONTH + INTERVAL 1 DAY 
       AND LAST_DAY(CURDATE()) - INTERVAL 1 MONTH THEN value END) value_1m, 
     SUM(CASE WHEN invdate 
      BETWEEN LAST_DAY(CURDATE()) - INTERVAL 1 MONTH + INTERVAL 1 DAY 
       AND LAST_DAY(CURDATE()) THEN qty END) qty_m, 
     SUM(CASE WHEN invdate 
      BETWEEN LAST_DAY(CURDATE()) - INTERVAL 1 MONTH + INTERVAL 1 DAY 
       AND LAST_DAY(CURDATE()) THEN value END) value_m 
    FROM ist 
WHERE invdate BETWEEN LAST_DAY(CURDATE()) - INTERVAL 3 MONTH + INTERVAL 1 DAY 
        AND LAST_DAY(CURDATE()) 
    AND companycode = 1 
    AND merchantcode = 1 
GROUP BY pdtname 

注:請確保您在invdate有一個索引。

輸出:

 
| PDTNAME | QTY_2M | VALUE_2M | QTY_1M | VALUE_1M | QTY_M | VALUE_M | 
|----------|--------|----------|--------|----------|-------|---------| 
| ProductA |  30 |  3000 |  30 |  3000 | 30 | 3000 | 
| ProductB | 100 |  1000 | 100 |  1000 | 100 | 1000 | 
| ProductC | 320 |  3200 | 320 |  3200 | 320 | 3200 | 

這裏是SQLFiddle演示

+0

對不起,彼得,我沒有看到你的帖子,由於一些個人probs。我完成了這項任務。回覆較晚,抱歉。 – Indra