Skip to content
Advertisement

Creating new view psql table by updating duplicate rows in old table

I have a table named t1 and it has 3 columns c1,c2,c3.In t1 there are rows which have duplicate values of c1 but different values of c2 and c3.Now, I wanted to create a psql view table which checks for duplicate c1 and updates the row where it takes the c2 value from the row which has highest value of c3 and adds all c3 values to the new row and creates a distinct row so there are no duplicates. The problem I am having is on how to update the column values based on the criteria. There can be multiple duplicate rows . Any help on this would be appreciated.Thank you

Advertisement

Answer

If I understand correctly, one method is aggregation:

select c1,
       (array_agg(c2 order by c3 desc))[1] as c2,
       sum(c3)
from t1
group by c1;

Another method would be distinct on:

select distinct on (c2) c1, c2, sum(c3) over (partition by c1)
from t1
order by c1, c3 desc;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement