1

我需要这样的输出:

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取自用户会话。

4

1 回答 1

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.

输出:

| PDT 名称 | 数量_2M | VALUE_2M | 数量_1M | VALUE_1M | 数量_M | VALUE_M |
|---------|--------|----------|--------|--------- -|--------|---------|
| 产品A | 30 | 3000 | 30 | 3000 | 30 | 3000 |
| 产品B | 100 | 1000 | 100 | 1000 | 100 | 1000 |
| 产品C | 320 | 3200 | 320 | 3200 | 320 | 3200 |

这是SQLFiddle演示

于 2013-09-29T05:41:36.067 回答