如何计算具有特定值的所有行的总长度?
我们假设有下表:
id | unit_id | length | column to be filled with total length
1 | 1 | 10
2 | 1 | 4
3 | 1 | 5
4 | 2 | 3
5 | 3 | 3
6 | 3 | 6
在这种情况下,如何更新表,使unit_id为1的所有行都具有unit_id为1(10 + 4 + 5 = 19)的所有行长度的总和,然后是两行有一个unit_id为3有9。
我试过
update test.routes
set total_length = (select sum(length) from test.routes where unit_id = unit_id) where unit_id = unit_id
但它的作用是它只是用相同的值更新整个表,如何更新每个unit_id的正确总和?
答案 0 :(得分:2)
尝试CTE:
t=# with a as (select *, sum(length) over (partition by unit_id) from routes)
t-# update routes u set total_length = a.sum
t-# from a
t-# where a.id = u.id;
UPDATE 6
Time: 0.520 ms
t=# select * from routes ;
id | unit_id | length | total_length
----+---------+--------+--------------
1 | 1 | 10 | 19
2 | 1 | 4 | 19
3 | 1 | 5 | 19
4 | 2 | 3 | 3
5 | 3 | 3 | 3
6 | 4 | 6 | 6
(6 rows)
答案 1 :(得分:1)
您需要限定对属性unit_id
的引用。否则,像where unit_id = unit_id
这样的约束(除了空值之外)始终为真,因此将总结所有内容:
update test.routes r1 set total_length = (select sum(length) from test.routes r2 where r2.unit_id = r1.unit_id)
答案 2 :(得分:0)
这应该做的工作。
update
routes as s
inner join (
select unit_id, sum(length) as total_length from routes group by unit_id
) as g
set
s.total_length = g.total_length
where
s.unit_id = g.unit_id
这里我们创建一个临时表,其中unit_id
的总长度。通过使用2个表之间的连接,我们可以有效地使用子查询