我有两张桌子:
资源
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
有人可以指出我正确的方向吗?
答案 0 :(得分:1)
使用COUNT
和GROUP 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