3个链接表SQL Server之间的总和

时间:2016-04-19 00:28:27

标签: sql sql-server

我想从链接表中提取一笔钱。

顺序

OrderID     LocationID  OrderDate
100         1           1/1/2000
200         2           1/2/2000

OrderedItems

ID          OrderID     ItemID
1           100         1
2           200         2
3           200         2
4           100         3

OrderItem的

ItemID      ItemName    Cost
1           Mobile1     100.00
2           Mobile2     200.00
3           Mobile3     300.00

Order表实际上是一组OrderedItemsOrderedItems中的每一行都通过OrderItem链接回ItemID

我正在尝试在下面的查询中添加一个列以获得订单总数。

Order Number    Location    Date Ordered    Order Total
-------------------------------------------------------
100             Sydney      1/1/2000        400
200             Brisbane    1/2/2000        400

我当前的查询是:

SELECT  
    Order.OrderID AS [Order Number],
    OL.Name AS [Location],
    Order.OrderDate AS [Date Ordered]
FROM
    Order
LEFT JOIN 
    Office_Locations AS OL ON OL.id = Order.LocationID

我试图关注this link但是我需要链接3个表格来添加值。

任何肝脏都会很棒!

2 个答案:

答案 0 :(得分:2)

你没有从三张桌子中找到一笔钱。您正在从一个表中找到一个总和:OrderItem表。唯一的诀窍是正确完成JOINGROUP BY表达式,以使该列可用。

SELECT o.OrderID As [Order Number], l.Name As Location
    , o.OrderDate As [Date Ordered], SUM(i.Cost) As [Order Total]
FROM [Order] o
INNER JOIN Office_Locations l on l.id = o.LocationID
INNER JOIN OrderedItems oi on oi.OrderID = o.OrderID
INNER JOIN OrderItem i ON i.ItemID = oi.ItemID
GROUP BY o.OrderID, l.Name, o.OrderDate

SQLFIDDLE

答案 1 :(得分:1)

您需要使用SUM获取总Cost

SQL Fiddle

SELECT
    [Order Number]  = o.OrderID,
    Location        = ol.Name,
    [Date Ordered]  = o.OrderDate,
    [Order Total]   = SUM(i.Cost)
FROM [Order] o
INNER JOIN OrderedItems oi
    ON oi.OrderId = o.OrderId
INNER JOIN OrderItem i
    ON i.ItemID = oi.ItemID
LEFT JOIN Office_Locations ol
    ON ol.id = o.LocationID
GROUP BY
    o.OrderID, o.OrderDate, ol.Name

正如Joel Coehoorn评论的那样,quantity表中的OrderedItems字段比重复它更为正常。根据他的建议,你的OrderedItems表应该是:

ID          OrderID     ItemID  Quantity
1           100         1       1
2           200         2       2
3           100         3       1

附加说明:

  • 使用有意义的别名来提高可读性。
  • 不要使用保留字作为对象名称,例如Order可以重命名为OrderHeader