Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining on a group by

Tags:

sql

Lets say that I have three tables, customers, orders and orderDetails.

I'm doing this:

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

But lets say the orders table contains customersId. How do I join on the customers table so that I can also add the customer's name to the fields selected?

Thanks,

Barry

like image 378
Baz Avatar asked Dec 07 '25 21:12

Baz


2 Answers

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

Try that out or something similar.

like image 72
Adam Avatar answered Dec 10 '25 09:12

Adam


you can do it this way, which will let you get more than customer name if needed:

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
like image 33
Taryn Avatar answered Dec 10 '25 09:12

Taryn