在单个SELECT中使用多个SUM,如foreach循环或CASE

时间:2012-09-14 13:44:39

标签: mysql

我有这个MySQL查询,它返回某个Product_ID销售的细分。

我想扩展此查询以包含多个Product_ID。

继承人我拥有的东西给了我1 Product_ID:

SELECT
o.Customer_ID, o.CompanyName, cg.Category, o.Order_ID,
SUM(old.LineTotal) as TOTAL,
SUM(old.qty) as PID,
COUNT(o.Order_ID) as OIDs

FROM Orders o
LEFT JOIN Order_LineDetails old ON old.Order_ID = o.Order_ID
LEFT JOIN CustomerDetails cd ON o.Customer_ID = cd.Customer_ID
LEFT JOIN _CustomerCategory cg ON cg.Category_ID = cd.Category_ID

WHERE o.IsPENDING = 0
AND o.OrderPlaceServerTime >= '2012-1-1'
AND o.OrderPlaceServerTime <= '2012-9-1'
AND o.IsVOID = 0
AND old.Product_ID = '56789' 

GROUP BY o.Customer_ID
ORDER BY TOTAL DESC
LIMIT 10

我正在尝试添加somthing以执行超过1个Product_ID并获取它们的SUM。

这是我正在考虑的想法,但obviosley这不起作用。

(CASE WHEN old.Product_ID = '56789' 
        SUM(old.LineTotal) as TOTAL_56789,
        SUM(old.qty) as PID_56789)

根据我追求的产品数量,这将重复。

跳跃这是有道理的。

有什么建议吗?

EDIT ::

以下是我想要回来的例子。

enter image description here

1 个答案:

答案 0 :(得分:0)

查看this

基本上你需要数据透视表,但是mysql不支持它。你可以强制它writing your queries dinamically in your client application。如果您对存储过程有更多经验,可以尝试the automatic version