Possible Duplicate:
Getting count from sql tables.
I have already asked earlier on same data and tables but this time requirement is slight different. So please do not vote it to close or downvote.
I have 4 tables, as displayed in image 3 tables and another is tbl_Company.:

Now in the map table, the primary keys of the rest three tables. Also in table sub category we have various childs of category, marked with category id 2, but if you see in map we have only 4 items with categoryid 2 and has two unique companies 7 and 8.
So what I want is to display when a category is chosen, all its subcategories will get listed with the number of companies. Like in map table cat id 2 has 4 rows and has 12 sub cats (actually in table its 44). SO my output will have all 44 subcat with displaying 4 sub cat has companies and rest 0. Something like this
SubCategoryName TotalCompanies
--------------- --------------
Badges, Emblems 0
Fashion scarves 1
… …
and so on.
I used this query
SELECT tbl_SubCategory.Name AS SubCategoryName, TotalCompanies = (Select COUNT(CompanyId) From tbl_Company_Category_Map WHERE CategoryId=2 )
FROM tbl_Category RIGHT JOIN
tbl_SubCategory ON tbl_Category.Id = tbl_SubCategory.CategoryId
LEFT JOIN
tbl_Company_Category_Map ON tbl_SubCategory.Id = tbl_Company_Category_Map.SUbCategoryId
WHERE (tbl_Category.Id = 2)
Group By tbl_SubCategory.Name
ORDER BY tbl_SubCategory.Name
but it returns me 4 companies for all 44 subcategories where as my actual output should be only 4 rows should have companies and rest 0
This particular query doesn’t seem to require the
tbl_Categorytable: