加入一个小组

时间:2012-03-29 19:33:59

标签: sql

假设我有三个表,客户,订单和订单详细信息。

我这样做:

SELECT orders.ordersId, sum(orderDetails.total)
FROM orders
LEFT OUTER JOIN orderDetails ON orders.ordersId = orderDetails.ordersId 
GROUP BY orders.ordersId 

但是我们可以说订单表包含customersId。如何加入customers表,以便我还可以将客户的名称添加到所选字段中?

谢谢,

百里

2 个答案:

答案 0 :(得分:3)

SELECT orders.ordersId, sum(orderDetails.total), customer.name
FROM orders
LEFT OUTER JOIN orderDetails ON orders.ordersId = orderDetails.ordersId
LEFT OUTER JOIN customer on customer.customerid = orders.customerid 
GROUP BY orders.ordersId , customer.name

尝试一下或类似的东西。

答案 1 :(得分:2)

您可以这样做,如果需要,您可以获得超过客户名称的信息:

SELECT o.ordersId, o.orderTotal, c.customername, c.(other customer data)
FROM 
(
    SELECT orders.ordersId
            , sum(orderDetails.total) as orderTotal
            , orders.customersid
    FROM orders
    LEFT OUTER JOIN orderDetails 
            ON orders.ordersId = orderDetails.ordersId 
    GROUP BY orders.ordersId, orders.customersid
) o
LEFT JOIN customers c
    ON o.customersid = c.customersid