如何使用GROUP BY子句选择

时间:2017-12-03 16:05:17

标签: sql sql-server

我有任务。 "对于每个订单,输入订购的单位总数和客户的名称。" 数据库:Microsoft SQL Server 12.0.2000.8 我到目前为止编写了这段代码:

    SELECT a.OrderID, SUM(a.Quantity), c.CompanyName FROM [Order Details] as a 
INNER JOIN Orders as b ON b.OrderID = a.OrderID
INNER JOIN Customers as c ON c.CustomerID = b.CustomerID

GROUP BY a.OrderID

但我无法显示CompanyName。每个订单应该只有一个公司名称,我们不需要连接它。我怎样才能做到这一点? 我附上我的数据库图表。 enter image description here

1 个答案:

答案 0 :(得分:1)

您可能遇到的错误是所有非聚合列都应出现在GROUP BY子句中。

所以错误基本上在CompanyName中缺少GROUP BY列。

因此,查询应如下所示:

SELECT
    a.OrderID,
    SUM(a.Quantity) as TotalQuantity,
    c.CompanyName
FROM [Order Details] as a 
INNER JOIN Orders as b ON b.OrderID = a.OrderID
INNER JOIN Customers as c ON c.CustomerID = b.CustomerID
GROUP BY a.OrderID, c.CompanyName

Works