想要返回结果中每条记录的子记录计数吗?
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
我仍在决定是否要返回计数或位...
这是正确的还是最好的方法?