SQL Server 选择SUM,连接两个表,在SQL查询中按OrderID对总和分组

kxe2p93d  于 2022-12-17  发布在  其他
关注(0)|答案(1)|浏览(158)

当前正在尝试解决此错误的原因:
选择列表中的列“Orders.OrderID”无效,因为聚合函数或GROUP BY子句中都不包含该列。
我的目标是对Order Details表中每个订单ID中的所有数量进行分组
作为W3School网站工具的一部分,我正在使用的SQL Server数据库是向公众开放的。如果要测试查询结果,请在此处查看:https://www.w3schools.com/sql/trysqlserver.asp?filename=trysql_func_sqlserver_datepart
我感谢任何帮助,请让我知道如果你需要更多的上下文/信息来帮助我。谢谢!
PS:请原谅我混乱的代码,SQL新手:)
我目前掌握的情况:

SELECT 
    O.OrderID,
    YEAR(O.OrderDate) AS OrderYear,
    DATEPART(qq, O.OrderDate) AS OrderQuarter,
    CONCAT(E.FirstName, SPACE(1), E.LastName) AS EmployeeName,
    C.CustomerName,
    S.ShipperName,
    SUM(D.Quantity) AS OrderItems
FROM
    ((((Orders AS O
JOIN 
    Employees AS E ON O.EmployeeID = E.EmployeeID)
JOIN 
    Customers AS C ON O.CustomerID = C.CustomerID)
JOIN 
    Shippers AS S ON O.ShipperID = S.ShipperID)
JOIN 
    OrderDetails AS D ON O.OrderID = D.OrderID);

我想达到的目标是:我的导师给了我一个小的示例图像作为参考,这就是我希望打印出查询中列名为OrderItems的数量的方式

如果您从SELECT中删除SUM函数,并删除最后一个join table语句,您将看到我的查询正确地聚合了OrderItems之前的所有内容。我还没有添加OrderRevenue列,并按照Revenue值的降序对它进行排序,但是如果您想多花点时间并解释如何解决这个问题,请给您一些大建议。

wztqucjr

wztqucjr1#

使用通过w3c提供的示例数据:

SELECT o.OrderID, DATEPART(YEAR,o.OrderDate) AS OrderYear, DATEPART(QUARTER,o.OrderDate) AS OrderQuarter,
       E.FirstName + ' ' + E.LastName AS EmployeeName, C.CustomerName, S.ShipperName, SUM(d.Quantity) AS Quantity--, SUM(d.Quantity*d.Price) AS OrderRevenue
  FROM Orders o
    INNER JOIN Employees e
      ON o.EmployeeID = e.EmployeeID
    INNER JOIN Customers c
      ON o.CustomerID = c.CustomerID
    INNER JOIN Shippers s
      ON o.ShipperID = s.ShipperID
    INNER JOIN OrderDetails d
      ON o.OrderID = d.OrderID
 GROUP BY o.OrderID, DATEPART(YEAR,o.OrderDate), DATEPART(QUARTER,o.OrderDate),
       E.FirstName + ' ' + E.LastName, C.CustomerName, S.ShipperName
OrderID OrderYear   OrderQuarter    EmployeeName        CustomerName            ShipperName     Quantity
--------------------------------------------------------------------------------------------------------
10249   1996        3               Michael Suyama      Tradicao Hipermercados  Speedy Express  49
10250   1996        3               Margaret Peacocl    Hanari Carnes           United Package  60
10368   1996        4               Andrew Fuller       Ernst Handel            United Package  78
10389   1996        4               Margaret Peacock    Bottom-Dollar Marketse  United Package  81
10418   1996        1               Margaret Peacock    QUICK-Stop              Speedy Express  146
10442   1997        1               Janet Leaverling    Ernst Handel            United Package  170

语法错误是因为您没有定义GROUP BY,也没有引用要聚合到的列。使用聚合函数(如SUMCOUNT)时,还必须告诉引擎将按哪些列进行分组。

相关问题