我有两张桌子。如下
categoryID categoryName
---------- -------------
1 Fruit
2 Country
3 Car
ItemID CategoryID ItemName
------- ---------- ----------
1 1 Apple
2 1 Mango
3 1 Banana
4 2 USA
5 2 Japan
6 3 Honda
7 3 Toyota
我需要一个选择查询,它会给我分类,以及每个类别下的项目数。像这样:
categoryID categoryName ItemCount
---------- ------------- ----------
1 Fruit 3
2 Country 2
3 Car 2
如何在SQL查询中实现此目的?我需要一个查询,而不是带变量的过程:(
答案 0 :(得分:2)
select c.categoryID, c.categoryName, count(*) as ItemCount
FROM category c
inner join items i on i.categoryId = c.categoryId
GROUP BY c.categoryID, c.categoryName
答案 1 :(得分:0)
尝试此查询
SELECT c.categoryID, c.categoryName, count(*) as 'ItemCount'
FROM Category c, Items i
WHERE c.categoryID = i.categoryID
GROUP BY c.categoryID, c.categoryName;
希望这有帮助