11

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?

4

2 回答 2

15

像这样的东西应该可以工作(至少在 sql server 上 - 你没有指定你的引擎)。

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
于 2013-05-27T09:19:39.007 回答
5

请试试:

select
    *,
    (select COUNT(*) from Orders o where o.branch_id=b.id) OrderCount,
    (select COUNT(*) from Products p where o.branch_id=p.id) ProductCount
From 
    branches b
于 2013-05-27T09:19:42.450 回答