2017-08-03 164 views
1

我有這樣兩個表可以這麼算:試圖跨越兩個表

資源

ID | Resource 
1 | 1234 
2 | 1356 
3 | 1456 

產品

ID | Product 
1 | North 
1 | South 
1 | West 
2 | North 
3 | East 
3 | West 

我想實現每個產品的數量的計數使用資源時,結果如下:

Resource | Products 
1234  | 3 
1356  | 1 
1456  | 2 

我寫的SQL是:

SELECT R.Resource, count (P.Product) as Products 
from Resource R 
left join Product P on R.ID = P.ID 
GROUP BY R.Resource, P.Product; 

但這給出以下結果

Resource | Product 
1234  | 1 
1234  | 1 
1234  | 1 
1356  | 1 
1456  | 1 
1456  | 1 

可有人請點我朝着正確的方向嗎?

回答

1

使用COUNTGROUP BY和你一樣,但使用INNER JOIN

SELECT r."Resource", COUNT(p."Product") AS Products 
FROM Resources r 
INNER JOIN Products p ON r."ID" = p."ID" 
GROUP BY r."Resource" 

輸出

Resource PRODUCTS 
1356  1 
1456  2 
1234  3 

SQL小提琴:http://sqlfiddle.com/#!4/7c01a/27/0