34,590
社区成员
发帖
与我相关
我的任务
分享
--查询
select a.id,a.NAME,b.price from [A] INNER JOIN (select aid,SUM(price)price from [B] GROUP BY aid) b ON a.id=b.aid
--更新
UPDATE a
SET a.price=b.price
FROM (select aid,SUM(price)price from [B] GROUP BY aid) B
WHERE a.id=b.aid
--drop table a,b
create table A(ID int , Name varchar(10), Price int)
insert into A
select 1 ,'张三', 0 union all
select 2 ,'李四', 0 union all
select 3 ,'王二', 0
create table B(ID int, AID int, Price int)
insert into B
select 1 ,1 ,6 union all
select 2 ,1 ,4 union all
select 3 ,2 ,100 union all
select 4 ,2 ,10 union all
select 5 ,2 ,1 union all
select 6 ,3 ,1
go
update a
set Price = (select SUM(Price) from b where a.id = b.aid group by b.aid)
select *
from a
/*
ID Name Price
1 张三 10
2 李四 111
3 王二 1
*/
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-02-24 14:49:41
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go
create table [A]([ID] int,[Name] varchar(4),[Price] int)
insert [A]
select 1,'张三',0 union all
select 2,'李四',0 union all
select 3,'王二',0
--> 测试数据:[B]
if object_id('[B]') is not null drop table [B]
go
create table [B]([ID] int,[AID] int,[Price] int)
insert [B]
select 1,1,6 union all
select 2,1,4 union all
select 3,2,100 union all
select 4,2,10 union all
select 5,2,1 union all
select 6,3,1
--------------开始查询--------------------------
select a.id,a.NAME,b.price from [A] INNER JOIN (select aid,SUM(price)price from [B] GROUP BY aid) b ON a.id=b.aid
----------------结果----------------------------
/*
id NAME price
----------- ---- -----------
1 张三 10
2 李四 111
3 王二 1
*/