atabrizi
atabrizi

Reputation: 918

How to get all child of a given id in SQL Server query

I have two tables in SQL Server database:

category( 
   itemid, 
   parentid
)

ArticleAssignedCategories(
   categid, 
   artid
)

categid is a foreign key of itemid

I want to get count of artids and child of that for given itemid (child means categories with parentid of given itemid.)

For example; If given itemid = 1 and in table category have (3,1),(4,1)(5,3)

All of 3, 4, 5 are child of 1

Can anyone help me to write a good query?

Upvotes: 0

Views: 1422

Answers (2)

Philippe Banwarth
Philippe Banwarth

Reputation: 17725

Recursive queries can be done using CTE

with CTE(itemid, parentid)
as (
  -- start with some category
  select itemid, parentid
  from category where itemid = <some_itemid>
union all 
  -- recursively add children
  select c.itemid, c.parentid
  from category c 
  join CTE on c.parentid = CTE.itemid
)
select count(*)
from ArticleAssignedCategories a
join CTE on CTE.itemid = a.categid

Upvotes: 1

Prabhakaran
Prabhakaran

Reputation: 3993

Here is the query. I hope this may help you

select b.artid,count(b.artid) from category a
inner join ArticleAssignedCategories b on a.itemid = b.artid
group by b.artid

Upvotes: 0

Related Questions