使用PostgreSQL中的查询结果更新列

栏目: 数据库 · PostgreSQL · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/13767908/updating-a-column-with-the-results-of-a-query-in-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


以上所述就是小编给大家介绍的《使用PostgreSQL中的查询结果更新列》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Rails Cookbook

Rails Cookbook

奥西尼 / 江苏东南大学 / 2007-6 / 68.00元

Rails是业界领先的新一代Web 2.0应用程序开发框架,而这本《Rails Cookbook》里充满了为了让你成为Rails开发专家而准备的各种解决方案。讨论范围覆盖了从基本概念,如安装Rails及设置开发环境,到最新的各种技巧,如开发符合REST协议规范的Web服务等。 Rails可提供更轻量级的代码、更丰富的功能和更快捷的量身定制过程,由此带来了一场Web开发革命。《Rails Co......一起来看看 《Rails Cookbook》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具