儿童记录的计数或布尔

时间:2012-08-10 19:28:41

标签: sql sql-server sql-server-2008

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

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

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

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

2 个答案:

答案 0 :(得分: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

答案 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