I have a table and want to replace the column value with value from other column value based on some condition.
+---------------------+
| Cntry | Code | Value |
+---------------------+
| US | C11 | A |
| US | C12 | B |
| US | C13 | C |
| US | C14 | D |
| US | C15 | E |
| UK | C11 | A |
| UK | C12 | B |
| UK | C13 | C |
| UK | C14 | D |
| UK | C15 | E |
+---------------------+
I want to replace the value of C14 based on the value of C11 based on Cntry
So my output should be like this.
+---------------------+
| Cntry | Code | Value |
+---------------------+
| US | C11 | A |
| US | C12 | B |
| US | C13 | C |
| US | C14 | A |<====Repalce with C11 for US
| US | C15 | E |
| UK | C11 | G |
| UK | C12 | B |
| UK | C13 | C |
| UK | C14 | G |<====Repalce with C11 for UK
| UK | C15 | E |
+---------------------+
Is there anyway to do this in postgresql?
Thanks
2
Answers
Create sample data:
Sample query:
If you want to actually change the contents of your table, then an UPDATE query will do the trick.
For obvious reasons, you should be super careful with UPDATE queries. There are a couple of ways to avoid mistakes that I sometimes use:
SELECT * INTO tablecopy FROM mytable
) and then DROP TABLE (DROP tablecopy
) on the copy.