Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql select count of multiple relationships with left join

Tags:

sql

I have a table for "branches", "orders" and "products. Each order and product are connected to a branch with branch_id. I need an sql statement to get a list of all branches with a field for how many orders and a field for how many products.

This works:

SELECT b.*, COUNT(o.id) AS orderCount FROM branches b LEFT JOIN orders o ON (o.branch_id = b.id) GROUP BY b.id

but it only gets the amount of orders, not products. If I change it to add amount of products, the amounts are wrong because it's getting amount of orders * amount of products.

How can I get the amount of both the orders and the products in the same SQL statement?

like image 702
user2306941 Avatar asked May 27 '13 09:05

user2306941


People also ask

How do I count multiple values in SQL?

Learn MySQL from scratch for Data Science and Analytics You can count multiple COUNT() for multiple conditions in a single query using GROUP BY. SELECT yourColumnName,COUNT(*) from yourTableName group by yourColumnName; To understand the above syntax, let us first create a table.

Does Count work with GROUP BY?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

Can we use count without GROUP BY?

Using COUNT, without GROUP BY clause will return a total count of a number of rows present in the table. Adding GROUP BY, we can COUNT total occurrences for each unique value present in the column. we can use the following command to create a database called geeks.


1 Answers

Something like this should work (on sql server at least - you didn't specify your engine).

SELECT 
    b.id
   ,COUNT(distinct o.id) AS orderCount 
   ,COUNT(distinct p.id) AS productCount 
FROM branches b 
LEFT JOIN orders o 
    ON (o.branch_id = b.id)
left join products p
    on p.product_id=b.id)
GROUP BY 
    b.id
like image 170
AdamL Avatar answered Oct 19 '22 23:10

AdamL