在 Postgres 中使用带有聚合和 groupby 的子查询进行更新

Gus*_*Gus 2 sql postgresql aggregate-functions sql-update

我正在尝试使用由另一列分组的该列的最大值来更新表中的列。

例如,假设我们有一个名为 transactions 的表,其中包含两列:quantityitem_name。而无论出于何种原因,我们要设置quantity等于最大quantity发现每个item_name

我很不擅长在 SQL 中做这样的事情,但这是我到目前为止所拥有的:

UPDATE transactions 
SET
quantity = subquery.quantity
FROM (select max(quantity), item_name
      from transaction group by item_name) AS subquery
WHERE  and item_name = subquery.item_name;
Run Code Online (Sandbox Code Playgroud)

Erw*_*ter 5

除了@Gordon 已经指出的语法错误之外,排除空更新通常是一个好主意:

UPDATE transaction t
SET    quantity = sub.max_quantity
FROM  (
   SELECT item_name, max(quantity) AS max_quantity
   FROM   transaction
   GROUP  BY 1
   ) sub
WHERE t.item_name = sub.item_name
AND  t.quantity IS DISTINCT FROM sub.max_quantity;
Run Code Online (Sandbox Code Playgroud)

无需在不更改任何内容的情况下编写新的行版本(几乎全部成本)。(除非您想触发触发器。)