Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Counting Sub Categories

Status
Not open for further replies.

louissto56

Programmer
Dec 18, 2007
3
AU
Hello. I have a recursion type application and need to count the category database including subcategorys.

It is setup like this:

catID - PK
catName - varchar
parentID - integer

For example:
Accomodation (catID = 1) is a top level category (parentID = 0).
Shared Houses is a sub category of accomodation (parentID = 1)
Hotels is a sub category of accomodation (parentID = 1)

Say I have 2 records in shared houses and 1 in hotels, how would I count it so Accomodation has a count value of 3?

Thanks
Louis
 
depends

do you want to count all the subcategories, no matter how many levels down?

you'll need to write recursive application logic

do you want to count all the subcategories but only one level down?

that's easy :)
Code:
select top.catName
     , count(down1.catID) as subcategories
  from categories as top
left outer
  join categories as down1
    on down1.parentID = top.catID
 where top.parentID = 0
group
    by top.catName


r937.com | rudy.ca
 
Hey. Thanks for your help. I wanted to count no matter how many levels down.

Thanks.
 
OH sorry I forgot to mention. I wanted to count items in another table called "items". It has a column called "catID" and is equal to any given category in the category table.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top