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)
 Calculating the count of items in category

Author  Topic 

iulianionescu
Starting Member

14 Posts

Posted - 2012-01-25 : 16:30:27
This should be easy but I can't figure it out... I have 2 tables:

dir_Category
CategoryID int
ParentID int (if top category, this is -1)
Name char

dir_Entries
EntryID int
CategoryID int
(other)

The data is used for a simple directory and on the main page, the one that shows the top categories, I want to put the number of items in brackets, for example: Auto (1200), Travel (2000), etc...

I am not sure how to count the number of entries that belong to any category that is a descendant of a top category.

For example, if I had

Auto>Cars>200 entries
Auto>Vans>100 entries

The total on Auto would be (300)

Is there a way to do it in SQL?

Thank you!

Iulian


Regards,

Iulian

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-01-25 : 16:46:48
yep. you need to use recursive cte for that

see this example below
http://msdn.microsoft.com/en-us/library/ms186243.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -