【问题标题】:Setting a column equal to the value of a subquery in postgres将列设置为等于 postgres 中子查询的值
【发布时间】:2021-04-11 18:13:45
【问题描述】:

我在 postgres 中有一个名为 mytable 的 4 列表。第四列 - batch - 仅包含空值。我的目标是使用UPDATE... SET 命令更新它,方法是将其设置为等于使用该表的查询结果(在本例中为NTILE(), which assigne each row to one of four equal-sized bins)。例如:

UPDATE mytable
    SET batch = (SELECT 
                    NTILE(4) OVER()
                    FROM
                    mytable)

当我尝试上述方法时,代码失败并出现错误:

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

查询本身运行成功。如何在 postgres 中使用一个命令更新此列?

【问题讨论】:

    标签: sql postgresql sql-update


    【解决方案1】:

    如果你想这样设置批处理,那么你需要使用主键:

    update mytable t
        set batch = t2.new_batch
        from (select t2.*, ntile(4) over () as new_batch
              from mytable t2
             ) t2
        where t2.pk = t.pk;
    

    请注意,使用 ntile() 而不使用 order by 是非常不正统的,但这就是您的问题对函数调用的表达方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多