使用postgresql基于其他列更新列

时间:2015-10-13 08:00:52

标签: sql postgresql sql-update

我有一个包含以下列的表:

id  integer
sumqty numeric
maxqty  numeric

id, sumqty会定期更新其他功能。 我需要编写一个传递这两列的函数并更新maxqty列。

例如:

id, sumqty, maxqty
5    20
5    70
5    45
3    20
1    12
1    2.5

在函数运行后,所需的输出将为:

id, sumqty, maxqty
5    20      45
5    10      45
5    45      45
3    20      20
1    12      12
1    2.5     12

我写了这段代码:

update A set maxqty= (select MAX(sumqty)  OVER (PARTITION BY id))

但它并不总是有效。有时它并没有给我实际MAX。

我的代码有什么问题?

2 个答案:

答案 0 :(得分:1)

改为使用相关子查询:

<强> SqlFiddleDemo

UPDATE mytable t1
SET maxqty= (SELECT MAX(sumqty) 
             FROM mytable t2
             WHERE t1.id = t2.id );

结果:

╔═════╦═════════╦════════╗
║ id  ║ sumqty  ║ maxqty ║
╠═════╬═════════╬════════╣
║  5  ║ 20      ║     45 ║
║  5  ║ 10      ║     45 ║
║  5  ║ 45      ║     45 ║
║  3  ║ 20      ║     20 ║
║  1  ║ 12      ║     12 ║
║  1  ║ 2.5     ║     12 ║
╚═════╩═════════╩════════╝

更有效的方式:

WITH cte AS
( 
  SELECT id, MAX(sumqty) AS sumqty
  FROM mytable
  GROUP BY id
)
UPDATE mytable m
SET maxqty = c.sumqty
FROM cte c
WHERE m.id = c.id;

您的原始查询:

update mytable 
set maxqty= (select MAX(sumqty)  OVER (PARTITION BY id);

给出:

╔═════╦═════════╦════════╗
║ id  ║ sumqty  ║ maxqty ║
╠═════╬═════════╬════════╣
║  5  ║ 20      ║ 20     ║
║  5  ║ 10      ║ 10     ║
║  5  ║ 45      ║ 45     ║
║  3  ║ 20      ║ 20     ║
║  1  ║ 12      ║ 12     ║
║  1  ║ 2.5     ║ 2.5    ║
╚═════╩═════════╩════════╝

这是因为UPDATE每行都有效。而且你的子查询只有一行来处理它们。

答案 1 :(得分:0)

update mytable 
set maxqty=t.max 
    from (select id,max(sumqty) from mytable group by id) t
where t.id=mytable.id

SQLFIDDLE

相关问题