使用postgresql中每个id的列值之和更新表

时间:2018-04-20 17:05:38

标签: sql postgresql

我有这样的表A:

id     amount
1      2
1      3
2      0
1      4
2      1

我怎么能像这样更新它: (按id计算金额总和并删除重复行)

id  amount
1   9
2   1

我试过了:

update a
set amount=sum(amount)
from a group by id;

并出现语法错误,仍在处理...

我使用的实际表是:

row_id | subject_id | hostay
----------------------------

我需要使用sum(hostay)更新hostay并通过subject_id删除重复的行。

我试过的命令:

WITH cte AS (DELETE FROM ht returning *)
INSERT INTO ht (row_id,subject_id,hostay)
SELECT row_id,subject_id,SUM(hostay)
FROM cte 
GROUP BY row_id,subject_id;

并且重复的行仍然存在。

3 个答案:

答案 0 :(得分:0)

  

通过id

从表组中选择id,sum(amount)作为数量

答案 1 :(得分:0)

如果我理解正确,您实际上想要更改表格中的记录。最简单的方法是删除并重新插入:

WITH cte AS (DELETE FROM your_table RETURNING *)
INSERT INTO your_table (id, amount)
SELECT id, SUM(amount)
FROM cte 
GROUP BY id

答案 2 :(得分:0)

最后,我通过以下代码解决了这个问题:

with B as( select sum(hostay) as hostay ,subject_id from ht  group by row_id,subject_id )

UPDATE ht  SET hostay=B.hostay  FROM B  where ht.subject_id=B.subject_id;


DELETE FROM
    ht a2
        USING ht b2 WHERE
    a2.row_id < b2.row_id
    AND a2.subject_id = b2.subject_id;

丑陋但有效:(