试图计算两个表

时间:2017-08-03 10:17:43

标签: sql oracle

我有两张桌子:

资源

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 个答案:

答案 0 :(得分: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