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
  • 605,456
  • 145
  • 1,078
  • 1,228
user2160696
  • 699
  • 3
  • 8
  • 21

2 Answers2

5
select utm, min(tracking_id)
from t
group by utm
Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260
3

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
  • 107,110
  • 28
  • 195
  • 197