2017-06-06 5 views
0

特定の値を持つすべての行の合計長の計算方法は?PostgreSQLでフィールドが共通する列を集計する方法は?

のは、次の表があるとしましょう。この場合

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 

、テーブルを更新する方法を、1のUNIT_IDているすべての行がUNIT_IDを持っているすべての行の長さの合計を持ってすること1(10 + 4 = 19 + 5)その後、3のUNIT_IDを持って両方の行は、私は

update test.routes 
set total_length = (select sum(length) from test.routes where unit_id = unit_id) where unit_id = unit_id 

を試みたが、何のことはないことはそれだけで全体を更新していることであるしました9.

持っていますテーブル付き同じ値、各unit_idの正しい合計を更新する方法は?

答えて

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

は、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) 
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つのテーブル間の結合を使用することによって、このビットを効率的に実行してからサブクエリを使用することができます

関連する問題