如何使用分组依据和总和更新表

时间:2019-09-24 17:59:02

标签: sql postgresql sql-update

数据表

|id | sysid |

|1  |  938  |

|2  |  938  | 

|3  |   23  | 

这是我想要的更新表

|id|amount|sum_amount|
|1 |200| 200+400     |
|2 |400|  400+200    |
|3 |150| 150         |

查询:-

UPDATE  update_table
SET sum_amount = SUM(amount)
WHERE data_table.id = update_table.id
GROUP BY data_table.sysid;

错误是“组”处或附近的语法错误

2 个答案:

答案 0 :(得分:0)

具有返回总和的CTE:

with cte as (
  select 
    sum(amount) sum_amount, 
    ',' || string_agg(cast(d.id as varchar), ',') || ',' ids
  from data_table d inner join update_table u
  on u.id = d.id
  group by d.sysid
)
update update_table u
set sum_amount = c.sum_amount
from cte c
where c.ids like '%,'|| cast(u.id as varchar) || ',%' 

请参见demo
结果:

> id | amount | sum_amount
> -: | -----: | ---------:
>  1 |    200 |        600
>  2 |    400 |        600
>  3 |    150 |        150

答案 1 :(得分:0)

一个选项是在子查询中联接包含sum(amount)聚合的表,并通过公用表表达式将结果反映到update语句中:

with d as
( 
 select * from
  (
  select d.sysid, sum(u.amount)   
    from data_table d
    join update_table u on u.id = d.id
   group by d.sysid
  ) q1
  right join data_table q2
  on q1.sysid=q2.sysid
)
update update_table u
   set sum_amount = d.sum
  from d
 where u.id = d.id
returning u.*;

id  amount  sum_amount
1   200     600
2   400     600
3   150     150

Demo