0

I have a table with fields utm and tracking_id. There may be many tracking_ids for each utm. So I need to select distinct utm and any one tracking id for each utm (let`s say thefirst one).

For example, we got the table:

utm   | tracking_id
-------------------
ddff  |      1
ddff  |      2
llzz  |      3
ddff  |      4
ohoh  |      5
ohoh  |      6

And as an output i want to get:

utm   | tracking_id
-------------------
ddff  |      1
llzz  |      3
ohoh  |      5

I use PostgreSQL 9.1.
Is there a way to do it with SQL?

Erwin Brandstetter
  • 539,169
  • 125
  • 977
  • 1,137
user2160696
  • 689
  • 3
  • 8
  • 19

2 Answers2

5
select utm, min(tracking_id)
from t
group by utm
Clodoaldo Neto
  • 108,856
  • 25
  • 211
  • 247
2

if you have only one column, than simple aggregate is what you want, go with Clodoaldo Neto's advice. If you have more than one columns, you can use dictinst on syntax:

select distinct on(utm)
    utm, tracking_id, column1, column2, ...
from t
order by utm, tracking_id

sql fiddle demo

Roman Pekar
  • 99,839
  • 26
  • 181
  • 193