Search code examples
sqlpostgresqlcoalesce

Coalesce values in one column based on another column


How do I coalesce values in a column grouped by another column?

e.g. How do I coalesce column 2 values by column 1 values? So turn the following:

Column 1|Column 2
-----------------
A       |Bob
A       |
B       |Mary
C       |
C       |Kevin
C       |
D       |
D       |

Into this:

Column 1|Column 2
-----------------
A       |Bob
B       |Mary
C       |Kevin
D       |

Thanks!


Solution

  • Use aggregation. Here is one way:

    select col1, max(col2)
    from t
    group by col1;