SQL 连接 3 个表并按 ProductId 分组但添加数量值

SQL that joins 3 tables and group by ProductId but adds the quantity value

我有 3 个表的数据,我需要将这些数据加入一份报告,该报告将运输地点的产品总数分组。

表格是:

这是我试过的。

SELECT B.ShippingLocation, A.ProductId, C.ProductName, A.Quantity
FROM OrderItem A
INNER JOIN Order B ON A.OrderId = B.Id
INNER JOIN Product C ON A.ProductId = C.Id
ORDER BY ShippingLocation

我的输出如下所示:

ShippingLocation     ProductId    Name    Quantity
---------------------------------------------------
loc 1                   1          name1      4
loc 1                   1          name1      2
loc 2                   1          name1      6
loc 2                   1          name1      4

希望是

ShippingLocation     ProductId    Name    Quantity
---------------------------------------------------
loc 1                   1          name1      6
loc 2                   1          name1      10

感谢您的帮助。

您可以用 SUMGROUP BY 求和:

SELECT B.ShippingLocation
     , A.ProductId
     , C.ProductName
     , SUM(A.Quantity) AS Quantity
FROM OrderItem A
JOIN Order B ON A.OrderId = B.Id
JOIN Product C ON A.ProductId = C.Id
GROUP BY B.ShippingLocation
       , A.ProductId
       , C.ProductName
ORDER BY B.ShippingLocation