Search code examples
sqlpostgresqlgreatest-n-per-group

Selecting rows but disregarding repetition of cell values


I have a table of customers that has repetition of first names and last names. I don't know what type of select query should I use to display specific row regarding their same entries.

Example: Table: customers

customer_id|firstname|lastname
-----------+---------+---------
0000000001 |Peter    |Griffin
0000000002 |Peter    |Pan
0000000003 |Mary     |Magdalene
0000000003 |Mary     |Jane

And the output I want is like is:

customer_id|firstname|lastname
-----------+---------+---------
0000000001 |Peter    |Griffin
0000000003 |Mary     |Magdalene

I know this is easy but I'm new to SQL.


Solution

  • One way to do this is with DISTINCT ON:

    SELECT DISTINCT ON (firstname)
           customer_id, firstname, lastname 
    FROM   customers
    ORDER  BY firstname, customer_id;
    

    See: