首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

咨询个,求和有关问题~实在不会写了。

2013-03-27 
咨询个,求和问题~~~~~~~~实在不会写了。。。。。。。。。。。有个表T,结构如下ID:intGroupID:intPrice:int现在想把Gro

咨询个,求和问题~~~~~~~~实在不会写了。。。。。。。。。。。
有个表T,结构如下
ID:int
GroupID:int
Price:int

现在想把GroupID=1和GroupID=2的相同ID的项的Price进行求和,写到GroupID=1的那个ID的Price里

比如
GroupID    ID        Price
1          100       1000
2          100       2000
1          101       500
2          101       500

执行完后
GroupID    ID        Price
1          100       3000
2          100       2000
1          101       1000
2          101       500

我这样写,貌似语法有问题。。。求解
update hockshop_item as T1 set Price=(select sum(Price) from hockshop_item where (GroupID=1 or GroupID=2) and ID=T1.ID) sql
[解决办法]


update a set a.price=(select sum(price) from table b
where a.id=b.id)
from table a
where a.groupid=1


[解决办法]

create table tb
(
GroupIDint,
IDint,
Priceint
)

insert into tb values(1,100,1000)
insert into tb values(2,100,2000)
insert into tb values(1,101,500)
insert into tb values(2,101,500)

update a set a.price = b.price
from tb a, (
select id,sum(price)price from tb
where groupid in(1,2)
group by id) b
where a.groupid = 1

select * from tb
/*
GroupID ID Price
1 100 3000
2 100 2000
1 101 1000
2 101 500

(4 行受影响)

[解决办法]
declare @t table(id int ,groupid int, n int)
insert @t select 1,          100    ,   1000
union all select 2 ,         100   ,    2000
union all select 1  ,        101 ,      500
union all select 2   ,       101,       500

update a set n = N + (select SUM(n) m from @t where groupid=a.groupid and id=2)
from @t a
where  a.id=1
select * from @t

热点排行