来自别名表的MySQL Sum

时间:2017-09-28 07:37:17

标签: mysql sql group-by sum

我有这个问题......

CREATE VIEW CustOrderItems AS
SELECT CustFirstName, CustLastName, OrderNumber, OrderDate, ShipDate, 
QuantityOrdered * QuotedPrice AS ItemTotal
FROM Customers NATURAL JOIN Orders NATURAL JOIN Order_Details;

将这样的订单分组后......

SELECT CustFirstName, CustLastName, OrderNumber, OrderDate, ShipDate, 
QuantityOrdered * QuotedPrice AS ItemTotal
FROM Customers NATURAL JOIN Orders NATURAL JOIN Order_Details
GROUP BY OrderNumber
ORDER BY OrderNumber ASC;

我知道需要计算一起添加的所有ItemTotal的总和吗?

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

正如已在评论中提到的那样,您可以使用SUM在SQL中获得总和,这应该不会令人感到意外。你知道关于GROUP BY,但不关于SUM

,这似乎很奇怪

此时我想建议在加入之前总是聚合,而不是之后。您需要订单及其客户信息及其总价。因此,从订单中选择,加入客户,加入总价。一旦你想要来自不同表的聚合,这种方法将为你省去一些麻烦。

SELECT 
  c.CustFirstName,
  c.CustLastName,
  o.OrderNumber,
  o.OrderDate,
  o.ShipDate, 
  od.OrderTotal
FROM Orders o
JOIN Customers c ON c.CustomerNumber = o.CustomerNumber
JOIN 
(
  SELECT
    OrderNumber,
    SUM(QuantityOrdered * QuotedPrice) AS OrderTotal
  FROM Order_Details
  GROUP BY OrderNumber
) od ON od.OrderNumber = o.OrderNumber
ORDER BY o.OrderNumber ASC;