2012-08-10 2 views
0

결과의 각 레코드에 대한 하위 레코드 수를 반환 하시겠습니까? 여기 하위 레코드 수 또는 bool

lists 
listid,name 
---------------- 
1,foods 
2,fruits 
3,veggies 
4,counties 
5,blah /* other list types */ 


listitems 
listid,listitemId,listname 
---------------- 
1,1,fruits 
2,1,veggies 
3,3,carrots 
4,3,broccoli 

내가 함께 일해야 쿼리의 :

declar @listid int 
select @listid = 1 --as an example 
select * from listitems where [email protected] 

results: 
1,1,fruits 
2,1,veggies 

목표 : 내가이 예에서는 과일과 채소를 위해 존재하는 항목의 수를 표시 할

listitems 
listitemid,listid,name,childcount 
1,1,fruits,0 
2,1,veggies,2 

다음은 어떻게 대답을 생각해 냈습니다.

select *, 
(
    select (select case when COUNT(*)>0 then 1 else 0 end as reccount 
    from ListItems li3 where li3.listid = l.listid) 
    from Lists l where li2.name = l.listname 
) as haschildrecords 
from ListItems li2 where listid=1 
나는 카운트 또는 비트를 반환하려면 난 아직 결정하고

...

이 올바른지 가장 좋은 방법이 있나요?

답변

0
select *, 
(
    select (select case when COUNT(*)>0 then 1 else 0 end as reccount 
    from ListItems li3 where li3.listid = l.listid) 
    from Lists l where li2.name = l.listname 
) as haschildrecords 
from ListItems li2 where listid=1 
1

이게 당신이 쓴거야? ,

select 
    lists.listid, 
    lists.name, 
    count(distinct listitemid) as itemcount, 
    convert(bit,sign(count(distinct listitemid))) as itemexists  
from 
    lists 
    left join 
    listitems on lists.listid = listitems. listid 
group by 
    lists.listid,lists.name 

나는 말할 수 없다,하지만 당신은 계층 구조를 구성하는 경우, 당신은 common table expressions보고 싶을거야, 및/또는 HierarchyID

+0

나도 말할 수 없다 내가 물려받은 것. – Rod

+0

원하는 게시물을 보려면 원래 게시물의 목표 섹션을 참조하십시오. – Rod

관련 문제