34,838
社区成员




create table tb_1(名称 nvarchar(10), 数量 float)
create table tb_2(名称 nvarchar(10),所属用户 nvarchar(10))
insert into tb_1 values('用户A',0)
insert into tb_1 values('用户B',0)
insert into tb_1 values('用户C',0)
insert into tb_2 values('名称1','用户A')
insert into tb_2 values('名称2','用户B')
insert into tb_2 values('名称3','用户C')
insert into tb_2 values('名称4','用户A')
insert into tb_2 values('名称5','用户A')
insert into tb_2 values('名称6','用户A')
UPDATE tb_1 set 数量 = (select count(*) from tb_2 where tb_2.所属用户 = tb_1.名称)
select * from tb_1
if object_id('tb1') is not null drop table tb1
go
create table tb1 ([名称] char(10) , [数量] int)
insert into tb1 select '用户A' , 0
union all select '用户B' , 0
union all select '用户C' , 0
if object_id('tb2') is not null drop table tb2
go
create table tb2 ([名称] char(10) , [所属用户] char(10))
insert into tb2 select '名称1' , '用户A'
union all select '名称2' , '用户B'
union all select '名称3' , '用户C'
union all select '名称4' , '用户A'
union all select '名称5' , '用户A'
union all select '名称6' , '用户A'
select * from tb1
结果
名称 数量
用户A 0
用户B 0
用户C 0
update tb1
set 数量 = b.数量
from tb1 a ,(select count(1) 数量,
所属用户
from tb2
group by 所属用户) b
where a.名称 = b.所属用户
select * from tb1
结果
名称 数量
用户A 4
用户B 1
用户C 1
drop table tb1 , tb2
select a.名称,
isnull(count(1),0) 数量
from a left join b
on a.名称 = b.所属用户
group by a.名称
update 表1 set 数量=t.数量 from
(select 所属用户,count(1) as 数量
from 表2
group by 所属用户) t
where 表1.名称=t.所属用户
update a
set 数量=b.数量
from 表1 a,(select 所属用户,count(所属用户)as 数量 from 表2 group by 所属用户)b
where a.名称=b.所属用户
如果A,B两表能一一对应,直接内连即可。
select a.名称 , count(1) 数量
from a , b
where a.名称 = b.所属用户
group by a.名称
update 表1
set 数量=b.数量
from 表1 as a,
(select 所属用户 as 名称,count(1)as 数量
from 表2
group by 所属用户)as b
where a.名称=b.名称
select a.名称 , isnull(count(1),0) 数量
from a left join b
on a.名称 = b.所属用户
group by a.名称
select count(所属用户) from 表2 group by 所属用户
update a
set 数量=b.数量
from 表1 a,(select count(数量)数量,
所属用户
from 表1
group by 所属用户)b
where a.名称=b.所属用户