Skip to content
Advertisement

SQL Result showing same value only once

maybe a simple question I am just not finding an answer for. Im having an MySQL result like

Col1 | Col2    
A    | 1    
A    | 2   
B    | 1

I want it to output the following:

Col1 | Col2
A    | 1
     | 2
B    | 1

How can I do that? When using GROUP BY he still shows all “A”s in the first column, I want to be shown only once at first occurence.

Thanks in advance!

Advertisement

Answer

Use a CASE expression with NOT EXISTS:

select
  case when not exists (select 1 from tablename where col1 = t.col1 and col2 < t.col2) then t.col1 end col1,
  t.col2
from tablename t
order by t.col1, t.col2

See the demo.
Results:

| col1 | col2 |
| ---- | ---- |
| A    | 1    |
|      | 2    |
| B    | 1    |
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement