带有连接和分组的MySQL子查询结果

时间:2016-06-26 08:03:20

标签: mysql

我无法让mySQL返回我追求的结果,因此希望有人能给我一些关于我出错的地方的指示。我有3个表(Sales_Area,Orders,Rooflight_Request),订单包含Sales_Area_ID列以加入Sales_Area,因此Sales_Area可以有很多订单。 Rooflight_Request包含Order_ID,因此订单可以包含许多Rooflight_Request。

Rooflight_Request包含产品,我试图按销售区域分组的订单总结屋顶灯总数(使用等式计算价格,折扣,货币汇率和数量)。

当我运行此查询时:

    SELECT salesArea.Area_Name,
(SELECT SUM(((rr.Price - (rr.Price * (rr.Discount /100))) / orders.Currency_Rate) * rr.Quantity) 
    FROM Rooflight_Request AS rr
    WHERE rr.Order_ID = orders.Order_ID
    AND rr.Record_Active = 1 
    AND rr.Alternative_Option <> 1
) AS Rooflights_Total
FROM Sales_Area AS salesArea
    LEFT JOIN Orders AS orders ON
        salesArea.Sales_Area_ID = orders.Sales_Area_ID
    LEFT JOIN Users AS users ON
        salesArea.User_ID = users.User_ID
GROUP BY salesArea.Area_Name

结果按销售区域分组,但我只获得一个价值单一的订单。如果我将组交换到orders.Order_ID,则结果集将包含所有订单和产品,但会返回数千条记录,因为它没有按销售区域分组。任何人都可以告诉我哪里出错了吗?感谢。

2 个答案:

答案 0 :(得分:1)

期待你查询结构我认为总的子选择是不正确的..你应该(我的意见)尝试加入rr与订单到其他表

SELECT  salesArea.Area_Name, SUM(((rr.Price - (rr.Price * (rr.Discount /100))) / orders.Currency_Rate) * rr.Quantity) 
FROM FROM Rooflight_Request AS rr
INNER JOIN Orders ON r.Order_ID = orders.Order_ID
LEFT JOIN Orders AS orders ON
    salesArea.Sales_Area_ID = orders.Sales_Area_ID
LEFT JOIN Users AS users ON
    salesArea.User_ID = users.User_ID
WHERE rr.Record_Active = 1 
    AND rr.Alternative_Option <> 1
GROUP BY salesArea.Area_Name

答案 1 :(得分:1)

尝试一下它会工作

SELECT SA.Area_Name,SUM(((RR.Price - (RR.Price *(RR.Discount / 100)))/ O.CuRRency_Rate)* RR.Quantity)FROM Sales_Area SA INNER JOIN Orders O ON SA。 Sales_Area_ID = O.Sales_Area_ID INNER JOIN Rooflight_Request RR ON RR.Order_ID = O.Order_ID WHERE RR.Record_Active = 1         AND RR.Alternative_Option&lt;&gt; 1 GROUP BY SA.Area_Name;