#Table A(RoomId,CurrentPeoNum)(房间id,当前人数)
表A里有如下数据
1   0
2   0
3   0
4   0#TableB(RecordId,RoomId)(id,房间id"外键")
1   1
2   1
3   2
4   3
5   3
6   3
我通过分组(Roomid)可以得到
Roomid    count(*)
1         2
2         1
3         3
怎么把我分组后得到记录更新到#TableA中去
#TableA 后的记录为
RoomId CurrentPeoNum
1        2
2        1
3        3
4        0
该怎么写啊?现在这儿谢谢大家了!
 

解决方案 »

  1.   

    declare @t table(RoomId int,CurrentPeoNum int)
    insert into @t select 1,0
    union all select 2,0
    union all select 3,0
    union all select 4,0declare @a table(RecordId int,RoomId int)
    insert into @a select 1,1
    union all select 2,1
    union all select 3,2
    union all select 4,3
    union all select 5,3
    union all select 6,3update a set CurrentPeoNum=b.cnt from @t a,(select Roomid,count(*) as cnt from @a group by Roomid) b where a.Roomid=b.Roomidselect * from @t
      

  2.   

    update a set a.CurrentPeoNum=p.num from #tablea a,(select roomid,count(*) as num from #tableb group by roomid) p where a.roomid=b.roomid