sql server update+select(子查询修改)20190304

if OBJECT_ID('tempdb..##t2') is not null drop table ##t2;
create table ##t2
(
a int,
b int,
c datetime,
d varchar(100),
e varchar(100),
f int,
g int
);
select * from ##t2;

update ##t2
set f = t3.f,
g = t3.g
FROM ##t2,(select f.NID,count(s.NID) skuCount,sum(s.Qty) skuSum
from table1(nolock) t1,table2(nolock) t2
where f.NID = s.nid
group by f.NID) t3
where ##t2.b = t3.NID;
go

 

--TestDemo
if OBJECT_ID('tempdb..##t1') is not null drop table ##t1;
create table ##t1
(
    id int
);
if OBJECT_ID('tempdb..##t2') is not null drop table ##t2;
create table ##t2
(
    id int,
    id2 int,
    quantity int
);
if OBJECT_ID('tempdb..##t3') is not null drop table ##t3;
create table ##t3
(
    id int,
    id3 int,
    quantity2 int
);
insert into ##t1 values(1);
insert into ##t1 values(2);
insert into ##t1 values(3);
insert into ##t1 values(4);
insert into ##t1 values(5);
go
insert into ##t2 values(1,1,1);
insert into ##t2 values(2,1,2);
insert into ##t2 values(3,1,3);
insert into ##t2 values(4,2,4);
insert into ##t2 values(5,2,5);
go
insert into ##t3 values(1,1,6);
insert into ##t3 values(2,1,7);
insert into ##t3 values(3,2,8);
insert into ##t3 values(4,2,9);
insert into ##t3 values(5,2,10);
go
if OBJECT_ID('tempdb..##t4') is not null drop table ##t4;
create table ##t4
(
    id1 int,
    id2 int,
    quantityCount int,
    quantitySum int
);
go
insert into ##t4(id1,id2)
select t1.id,t2.id
from ##t1 t1,##t2 t2
where t1.id = t2.id2;
update ##t4
set quantityCount = t1.quantityCount,
quantitySum = t1.quantitySum
FROM ##t1,(select t2.id,
count(t3.id) quantityCount,sum(t3.quantity2) quantitySum 
from ##t2 t2,##t3 t3
where t2.id = t3.id3
group by t2.id) t1
where ##t4.id2 = t1.id;
go
select * from ##t4;
go

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值