簡體   English   中英

在SQL select語句中顯示引用行的行和計數

[英]Display row and count of referenced row in SQL select statement

我有兩張桌子。 如下

表:類別

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查詢中實現此目的? 我需要一個查詢,而不是一個帶變量的過程:(

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

試試這個查詢

SELECT c.categoryID,  c.categoryName, count(*) as 'ItemCount' 
FROM Category c, Items i 
WHERE c.categoryID = i.categoryID 
GROUP BY c.categoryID,  c.categoryName;

小提琴

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM