我有两张桌子。第一个包含库存清单(物料),第二个包含销售历史(invoiceLines)。
+--------------------+ +--------------------+
| items + + invoiceLines +
+--------------------+ +--------------------+
+ id + + itemCode +
+ itemDesc + + qtyShipped +
+ qtyOnHandW1 + + invDate +
+--------------------+ +--------------------+
我可以使用单独的查询获取我想要的数据,例如:
SELECT itemCode, itemDesc, ROUND(SUM(qtyShipped)) as m11
FROM invoiceLines
WHERE invDate >= (NOW() - INTERVAL 11 MONTH) AND invDate <= (NOW() - INTERVAL 10 MONTH)
AND itemCode = 001
GROUP BY itemCode;
但是,我想从项目中返回id,itemDesc,qtyOnHandW1, 与去年(m12)本月的SUM或qtyShipped一样,本月+去年(m11)+ 1m,本月+去年(m10)+ 2m。
+-------------------------------------------------------------------+
| id | itemDesc | qtyOH | m12 | m11 | m10 |
+-------------------------------------------------------------------+
+ 001 | product A | 50 | 32 | 25 | 70 |
+-------------------------------------------------------------------+
+ 002 | product B | 31 | 16 | 31 | 41 |
+-------------------------------------------------------------------+
+ 003 | product C | 5 | 22 | 11 | 3 |
+-------------------------------------------------------------------+
谢谢!
答案 0 :(得分:0)
尝试将您的查询更改为类似的内容...假设您正在寻找2017年引用的月份....
SELECT
a.itemCode as itemCode,
a.itemDesc as itemCode,
(select ROUND(SUM(qtyShipped))
from invoiceLines
where date_format(invDate,'%Y%m') = '201712' and itemCode = a.itemCode
group by date_format(invDate,'%Y%m'),itemCode ) as m12,
(select ROUND(SUM(qtyShipped))
from invoiceLines
where date_format(invDate,'%Y%m') = '201711' and itemCode = a.itemCode
group by date_format(invDate,'%Y%m'),itemCode ) as m11,
(select ROUND(SUM(qtyShipped))
from invoiceLines
where date_format(invDate,'%Y%m') = '201710' and itemCode = a.itemCode
group by date_format(invDate,'%Y%m'),itemCode ) as m10
FROM invoiceLines as a
AND a.itemCode = 001
GROUP BY a.itemCode;
答案 1 :(得分:0)
如果无法访问某些示例数据,则很难回复,但此查询应该有效:
SELECT i.id, i.itemDesc, i.qtyOnHandW1,
SUM(CASE WHEN l.invDate BETWEEN (NOW() - INTERVAL 12 MONTH) AND (NOW() - INTERVAL 11 MONTH) THEN l.qtyShipped ELSE 0 END) AS m12,
SUM(CASE WHEN l.invDate BETWEEN (NOW() - INTERVAL 11 MONTH) AND (NOW() - INTERVAL 10 MONTH) THEN l.qtyShipped ELSE 0 END) AS m11,
SUM(CASE WHEN l.invDate BETWEEN (NOW() - INTERVAL 10 MONTH) AND (NOW() - INTERVAL 9 MONTH) THEN l.qtyShipped ELSE 0 END) AS m10
FROM items i
LEFT JOIN invoiceLines l
ON l.itemCode = i.id
GROUP BY i.id
这里是demo,其中包含我创建的一些示例数据。