使用PostgreSQL中的查詢結果更新列

我在PostgreSQL 9.2中有下表,其中包含時間戳:

gid [PK](bigserial),timestamp_mes(沒有時區的時間戳),time_diff(interval)

1,2012-01-23 11:03:40,空的

2,2012-01-23 11:03:42,空的

3,2012-01-23 11:03:44,空的

我添加了一個間隔列(time_diff),並希望用此查詢產生的時差值填充它:

SELECT timestamp_mes - lag(timestamp_mes, 1) 
over (order by timestamp_mes) as diff
from gc_entretien.trace order by timestamp_mes

我嘗試了以下查詢來更新time_diff列,但沒有成功:

UPDATE gc_entretien.trace set time_diff = 
(SELECT trace.timestamp_mes - lag(trace.timestamp_mes, 1) 
over (order by trace.timestamp_mes) 
from gc_entretien.trace order by timestamp_mes);

這會導致錯誤:

ERROR: more than one row returned by a subquery used as an expression

我應該如何使用時差查詢生成的值更新time_diff列?

像這樣的東西:
with new_values as (
   SELECT gid, 
          timestamp_mes - lag(timestamp_mes, 1) over (order by timestamp_mes) as diff
   from gc_entretien.trace 
)
update gc_entretien.trace as tr
  set time_diff = nv.diff
from new_values nv
where nv.gid = tr.gid;

翻譯自:https://stackoverflow.com/questions/13767908/updating-a-column-with-the-results-of-a-query-in-postgresql