I have a table with the following columns:
id integer
sumqty numeric
maxqty numeric
The columns id, sumqty are updated by other functions regularly.
I need to write a function that pass on these two columns and update the maxqty column.
for example:
id, sumqty, maxqty
5 20
5 70
5 45
3 20
1 12
1 2.5
after function runs, desired output will be:
id, sumqty, maxqty
5 20 45
5 10 45
5 45 45
3 20 20
1 12 12
1 2.5 12
I wrote this code:
update A set maxqty= (select MAX(sumqty) OVER (PARTITION BY id))
but it doesn't always works. Sometimes it doesn't give me the actualy MAX.
What is the problem with my code?
Use correlated subquery instead:
SqlFiddleDemo
UPDATE mytable t1
SET maxqty= (SELECT MAX(sumqty)
FROM mytable t2
WHERE t1.id = t2.id );
Result:
╔═════╦═════════╦════════╗
║ id ║ sumqty ║ maxqty ║
╠═════╬═════════╬════════╣
║ 5 ║ 20 ║ 45 ║
║ 5 ║ 10 ║ 45 ║
║ 5 ║ 45 ║ 45 ║
║ 3 ║ 20 ║ 20 ║
║ 1 ║ 12 ║ 12 ║
║ 1 ║ 2.5 ║ 12 ║
╚═════╩═════════╩════════╝
More efficient way:
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;
Your original query:
update mytable
set maxqty= (select MAX(sumqty) OVER (PARTITION BY id);
Gives:
╔═════╦═════════╦════════╗
║ id ║ sumqty ║ maxqty ║
╠═════╬═════════╬════════╣
║ 5 ║ 20 ║ 20 ║
║ 5 ║ 10 ║ 10 ║
║ 5 ║ 45 ║ 45 ║
║ 3 ║ 20 ║ 20 ║
║ 1 ║ 12 ║ 12 ║
║ 1 ║ 2.5 ║ 2.5 ║
╚═════╩═════════╩════════╝
It is because UPDATE works per row. And your subquery has only one row to process not bunch of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With