1

I have been dealing with this for quite sometime now and I could not be able get around this. It is like this, I have table with case_no (alphanumeric), first_name, last_name and description.

What I want do is to select only one row for each distinct first_name/last_name combination. So, for example

     case_no         |         first_name         |         last_name
---------------------+----------------------------+------------------------
     AAAAAAA         |          john              |          doe
     BBBBBBB         |          Dog               |          dawg
     CCCCCCC         |          Cat               |          kitten
     DDDDDDD         |          john              |          doe

Given that example I want to retrieve the following rows:

     case_no         |         first_name         |         last_name
---------------------+----------------------------+------------------------
     BBBBBBB         |          Dog               |          dawg
     CCCCCCC         |          Cat               |          kitten
     DDDDDDD         |          john              |          doe

How do I do this?

vyegorov
  • 21,787
  • 7
  • 59
  • 73
oneofakind
  • 552
  • 17
  • 41

2 Answers2

6

Try this,

SELECT MAX(CASE_NO), FIRST_NAME, LAST_NAME
FROM TABLE
GROUP BY FIRST_NAME, LAST_NAME;
Orangecrush
  • 1,970
  • 2
  • 15
  • 26
3

In PostgreSQL:

SELECT DISTINCT ON (2, 3)
       case_no, first_name, last_name
FROM   tbl
ORDER  BY 2, 3, case_no DESC NULLS LAST;

About DISTINCT ON:

Difference to the version with max():

  • Results are ordered by first_name, last_name. You may or may not want that.
  • Performance is similar. If you need ordered results this is probably faster, else max() may be faster.
  • You can easily add more columns from the same row.
Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228