2016-05-31 47 views
-2

我要找到每个存储的产品数量为那家商店的顾客是商店/数两项罪名被

Customer     
Id | dealerId   
1 | 10    
2 | 11    
3 | 10      

Product    
Id | CustomerId   
100 | 1    
200 | 3 
300 | 2  

store 
Id 
10 
11 

对于上面例子中的结果将是:

StoreId | value 

10  | 2/2 
11  | 1/1 
+0

能否请您为我们提供了一个[SQL小提琴(http://sqlfiddle.com/)或在这里证明tableVariables一些样本数据:HTTP:// stackoverflo w.com/questions/37530075/sql-filling-missing-dates/37532218#37532218 – Ralph

回答

1
SELECT 
    c.dealerID as Store, 
    COUNT(DISTINCT c.ID) as NumOfCustomers, 
    COUNT(p.ID) as NumOfProducts 
FROM 
    Customers C 
    INNER JOIN 
    Products p on p.CustomerId = c.Id 
GROUP BY 
    c.dealerID 
+1

我认为即使样本数据不能使用,客户数量上也可能需要一个“count(distinct ...)”它清楚这是否可以实际发生。 – shawnt00

+0

够公平@ shawnt00 :) – scsimon

0
select S.Id AS StoreId, COUNT(p.Id) AS ProductId, COUNT(CAST.Id) AS CustomerId 
from Store S 
    left join Customer C on C.dealerId = Scheduler.StoreId 
    left join Product P on P.CustomerId = CAST.Id 
group by S.Id