SQL Server 2008:计算存储在类别中的记录数

时间:2013-04-06 18:09:12

标签: sql sql-server-2008

我是SQL Server的新手,我遇到了一个令我困惑的问题。

我有2个数据表CategoryProduct。下面是详细的表格。

分类

------------------------------------------------------
 categoryId | categoryName      | desc
------------------------------------------------------
 1          | Shirt             | Men's Shirt
 2          | Jeans             | Men's Pants
 3          | Accessories       | Women's Accessories
------------------------------------------------------

产品

---------------------------------------------------------------
productID   | desc                     | categoryId
---------------------------------------------------------------
 1          | Slim-fit Classic Shirt   | 1
 2          | Denim Slim-fit jeans     | 2
 3          | Denim Regular-fit jeans  | 2
 4          | Bracelet                 | 3
---------------------------------------------------------------

如何获得如下的确切输出?

-------------------------------------------------------------------
 categoryId | categoryName      | numOfRecord | desc
-------------------------------------------------------------------
 1          | Shirt             | 1           | Men's Shirt
 2          | Jeans             | 2           | Men's Pants
 3          | Accessories       | 1           | Women's Accessories
-------------------------------------------------------------------

抱歉我的英语不好。

1 个答案:

答案 0 :(得分:1)

您可以使用COUNTGROUP BY

试试这个:

SELECT c.categoryId, c.categoryName, count(*) as numOfRecord, p.[desc]
FROM dbo.Category AS c INNER JOIN dbo.Product AS p
ON c.categoryId = p.categoryId
GROUP BY c.categoryId, c.categoryName, p.[desc];