I have a table as below
name | item | inum |
---|---|---|
na1 | k1 | 5 |
na2 | k1 | 6 |
na3 | k2 | 7 |
na4 | k3 | 7 |
na5 | k3 | 8 |
If 2 item has the same value, then their inum needs to updated with the highest value
eg,
k1 has 2 rows(na1 and2) with different inum. I need to update inum of na1 with 6 since it is the highest among the 2 k1 inums. Same with k3 as well
name | item | inum |
---|---|---|
na1 | k1 | 6 |
na2 | k1 | 6 |
na3 | k2 | 7 |
na4 | k3 | 8 |
na5 | k3 | 8 |
Can anyone suggest a postgres code for the same?
Thanks
2
Answers
There are multiple ways to do that and one is to use the lateral join. ie:
DBfiddle demo
Another one is to group by and then join. ie:
DBFiddle demo
You can phrase your query like you phrased your description: tell
update
that each row has to use the highestinum
it can find of the sameitem
. Demo at db<>fiddle:That’s a correlated scalar subquery. The
returning
clause is there only to show what it did.