0

想要返回结果中每条记录的子记录计数吗?

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 listid=@listid

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

我仍在决定是否要返回计数或位...

这是正确的还是最好的方法?

4

2 回答 2

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

于 2012-08-10T19:48:45.893 回答
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
于 2012-08-16T18:14:11.130 回答