Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Get the count of a subcategories

Author  Topic 

mary_itohan
Posting Yak Master

191 Posts

Posted - 2012-11-08 : 09:32:17
hi guys,
am a bit confused as a have a table with a PK and FK using categories and sub categories tables.

The fk is the categoryID which is an int ( and not the name )

How do i get the count of the categories in the sub_cat table

here is my code

many thanks

SELECT     dbo.Gifts_Category.CategoryName, COUNT(dbo.Gifts_SubCategory.SCName) AS 'mary'
FROM dbo.Gifts_Category INNER JOIN
dbo.Gifts_SubCategory ON dbo.Gifts_Category.CategoryID = dbo.Gifts_SubCategory.CategoryID
GROUP BY dbo.Gifts_SubCategory.SCName, dbo.Gifts_Category.CategoryName


_____________________


Yes O !

jimf
Master Smack Fu Yak Hacker

2875 Posts

Posted - 2012-11-08 : 09:45:51
If you just want a count of how many sub categories are associated with a CategoryName:

SELECT dbo.Gifts_Category.CategoryName, COUNT(DISTINCT dbo.Gifts_SubCategory.SCName) AS 'mary'
FROM dbo.Gifts_Category INNER JOIN
dbo.Gifts_SubCategory ON dbo.Gifts_Category.CategoryID = dbo.Gifts_SubCategory.CategoryID
GROUP BY dbo.Gifts_Category.CategoryName

You don't ever want to count, sum, etc. things you are grouping by

Jim



Everyday I learn something that somebody else already knew
Go to Top of Page

mary_itohan
Posting Yak Master

191 Posts

Posted - 2012-11-08 : 11:05:19
ok tnx

_____________________


Yes O !
Go to Top of Page
   

- Advertisement -