2016-05-31 43 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