这样一个树形结构,统计会议总数,包含国家级会议,省级会议,市级会议,区级会议,...下面等等。我点选全国,要将二级区域省的会议统计出来,形成列表展示(省要包含自身省级会议以及各自市,区,乡镇会议等等);我点选某个省,比如江苏省,要把各个市的会议总数总计出来(市要包含它自身市级会议,它下面各级会议)依此类推。这个例子举的比较牵强,但是需求的意思是这样的,我写了快四天了,没写出合适的,看看论坛里有没有大侠相助。sqlserver2008数据库,有区域表areas(areaID,parentID,areaName);会议表meeting(meetingID,meetingAreaID,meetingName),meetingAreaID和areaID是可以关联的,都是地址的ID数据库sqlserver存储过程数据库递归

解决方案 »

  1.   

    你是要测试数据吗?这个需求是我剥离出来的,实际的表要比这多几个。
    数据形式大概是:
    区域表areas:
    areaID  areaName  parentID
    1          全国      null
    2          江苏       1
    3          浙江       1
    4          南京       2
    ...
    ...会议表meeting:
    meetingID  meetingAreaID  meetingName
    1               1             人代会
    2               2             江苏政协一次会议
    3               4             南京人大
    4               1             全国劳模表彰
    5               3             浙江工商业大会
    ...
    ...
      

  2.   


    with a(meetingID,  meetingAreaID,  meetingName) as (
    select 1,               1,             '人代会' union all
    select 2,               2,             '江苏政协一次会议' union all
    select 3,               4,             '南京人大' union all
    select 4,               1,             '全国劳模表彰' union all
    select 5,               3,             '浙江工商业大会'
    )
    ,b(areaID , areaName,  parentID) as(
    select 1,          '全国',      null union all
    select 2,          '江苏',       1 union all
    select 3,          '浙江',       1 union all
    select 4,          '南京',       2
    ),c as(
    select meetingareaid as a,count(meetingareaid) b from a
    group by meetingareaid
    )
    ,d as(
    select areaname a,parentid d,isnull(areaID,0) c,c.b from b left join c on b.areaID=c.a
    )
    ,e as(
    select a , c, d=c, b from d
    union all
    select e.a , d.c, e.d, d.b from e,d  where d.d=e.c
    )
    select a,sum(b) from e
    group by a
    option ( maxrecursion 0) 
      

  3.   


    你写的我不是太能懂,怎么在语句中出现具体数据呢,不过只有你一人辛苦回答,分就给你了。
    我后来参考别人写的,也实现了功能:我的存储过程如下:--取出所有符合条件的活动及其归属地
    select at.*,ue.JurisdictionalUnitArea into #tAct from Activities at inner join UserExtendInfos ue on at.CreatedBy=ue.UserID
    where at.CheckStatus=1 and IsDeleted=0
    and ((@categoryID is not null and at.CategoryID=@categoryID)or (@categoryID is null and 1=1))
    and((@createdOnMax is not null and at.CreatedOn<@createdOnMax)or(@createdOnMax is null and 1=1))
    and ((@createdOnMin is not null and at.CreatedOn>@createdOnMin)or(@createdOnMin is null and 1=1))
    --使用GetSubAreas函数,取得每一个二级区域的子区域,子子区域...等的AreaID,看活动的归属地是不是在其中,若在,就将计数atvCount加1,最终得到每一个二级区域的atvCount
    select ROW_NUMBER() over (order by AreaName)as rowNum,AreaName,atvCount=(select COUNT(*) from #tAct where JurisdictionalUnitArea in(select AreaID from GetSubAreas(AreaID))) 
    into #tAct2 from Areas where ParentAreaID=@areaId