从sql表中获取计数

前端之家收集整理的这篇文章主要介绍了从sql表中获取计数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有三个表,其中两个是主表,另一个是map.它们如下.

> tbl_Category,具有列Id(PK)和名称

/ *

  1. ID NAME
  2. 1 Agriculture & Furtilizers
  3. 2 Apparel & Garments
  4. 3 Arts & Crafts
  5. 4 Automobiles

* /
> tbl_SubCategory

  1. /*
  2. Id SubCategoryName CategoryId (FK,PK of above)
  3. 2 Badges,Emblems,Ribbons & Allied 2
  4. 3 Barcodes,Stickers & Labels 2
  5. 4 Child Care & Nursery Products 2
  6. 9 Fabrics & Textiles 2
  7.  
  8.  
  9.  
  10. */

现在第三个表是tbl_Company_Category_Map,其中我持有公司的所有类别及其子类别.下面是它的架构和数据.

  1. /*
  2.  
  3. CompanyCategoryId SubCategoryId CategoryId CompanyId
  4. 10 36 11 1
  5. 11 38 11 1
  6. 12 40 11 1
  7.  
  8.  
  9. */

上面,第一列是tbl_Company_Category_Map的PK,第二列是tbl_SubCategory的PK,第三列是tbl_Category的PK,最后一列是公司ID.
现在我想要的是显示一个类别的每个子类别中列出的显示总公司.有点像这样.

  1. Subcategory Name Total COmpanies
  2. Apparel,Clothing & Garments 1153
  3. Badges,Ribbons & Allied Products 4100
  4. Barcodes,Stickers & Labels 998
  5. Child Care & Nursery Products 2605
  6. Cotton Bags,Canvas Bags,Jute Bags & Other Fabric Bags 2147

我正在使用查询

  1. BEGIN
  2.  
  3.  
  4. SELECT tbl_SubCategory.Name AS SubCategoryName,tbl_Category.Name AS CategoryName,TotalCompanies=(Select COUNT(*) From tbl_Company_Category_Map WHERE CategoryId = @Id)
  5. FROM tbl_Category INNER JOIN
  6. tbl_Company_Category_Map ON tbl_Category.Id = tbl_Company_Category_Map.CategoryId INNER JOIN
  7. tbl_SubCategory ON tbl_Company_Category_Map.SubCategoryId = tbl_SubCategory.Id
  8. WHERE (tbl_Company_Category_Map.CategoryId = @Id)
  9. Group By tbl_SubCategory.Name,tbl_Company_Category_Map.CategoryId,tbl_Category.Name
  10. ORDER BY tbl_Company_Category_Map.CategoryId
  11.  
  12. END

我的问题是我每行的公司总数相同.请帮帮我.

解决方法

尝试这个:
  1. BEGIN
  2.  
  3.  
  4. SELECT tbl_SubCategory.Name AS SubCategoryName,COUNT(*) AS TotalCompanies
  5. FROM tbl_Category INNER JOIN
  6. tbl_Company_Category_Map ON tbl_Category.Id = tbl_Company_Category_Map.CategoryId INNER JOIN
  7. tbl_SubCategory ON tbl_Company_Category_Map.SubCategoryId = tbl_SubCategory.Id
  8. WHERE (tbl_Company_Category_Map.CategoryId = @Id)
  9. Group By tbl_SubCategory.Name
  10. ORDER BY tbl_SubCategory.Name
  11.  
  12. END

猜你在找的MsSQL相关文章