首先是有关表:
我想在表格中显示以下详细信息:
CategoryName | DateCreated | DateUpdate | No. of Products
现在,第四列No. of Products
是我的问题。如您在数据库映像中所看到的:
CategoryID
是外键 tblProduct
因此,this(No. of Products
)列应包含总数。属于特定类别的产品。
我对如何得到这个感到困惑COUNT
。
这是我尝试过的:
select tblCategory.*,
COUNT(tblProduct.CategoryID) AS 'Cat_Count'
from tblCategory
inner join tblProduct on tblCategory.CategoryID = tblProduct.CategoryID;
我收到以下错误:
Msg 8120, Level 16, State 1, Line 1
Column 'tblCategory.CategoryID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
它是一个带有group by子句的简单连接。您只需要将分组CategoryID
:
SELECT cat.CategoryName, cat.DateCreated, cat.DateUpdate, COUNT(pro.ProductID) [No. of Products]
FROM tblCategory cat JOIN tblProduct pro
ON cat.CategoryID = pro.CategoryID
Group By cat.CategoryID, cat.CategoryName, cat.DateCreated, cat.DateUpdate
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句