使用相同的SUM和Group BY更新两列

时间:2013-01-28 07:55:33

标签: sql sql-server-2008

我想使用此查询中的值进行更新,但是它说的是错误...我试图将其最小化。

update p
set a10=t.sumgc
from temp as p inner join 
(SELECT     SUM(gcsanad) as sumgc,good_gr
fROM         dbo.fgoodgroup 
WHERE     (flag = 2)
group by good_gr ) as t
on t.good_gr=p.a3
,
a11=t.sumgc
from temp as p inner join 
(SELECT     SUM(gcsanad) as sumgc,good_gr
fROM         dbo.fgoodgroup 
WHERE     (flag = 4) 
group by good_gr ) as t
on t.good_gr=p.a3

1 个答案:

答案 0 :(得分:1)

试试这个

update p
set a10=t.sumgc
,
a11=t.sumgc1

from temp as p inner join 
(SELECT 
  (case when  flag = 2 then   SUM(gcsanad)  end) as sumgc,
  (case when  flag = 4 then   SUM(gcsanad)  end) as sumgc1
fROM         dbo.fgoodgroup 
group by good_gr ) as t
on t.good_gr=p.a3