17

I have this table:

+----+-----+----------+
| id | name| key      |
+----+-----+----------+
| 1  | foo |111000    |
| 2  | bar |111000    |
| 3  | foo |000111    |
+----+-----+----------+

Is there a way to group by the key to get this result?

+----+-----+----------+
| id | name| key      |
+----+-----+----------+
| 2  | bar |111000    |
| 3  | foo |000111    |
+----+-----+----------+

Or this result:

+----+-----+----------+
| id | name| key      |
+----+-----+----------+
| 1  | foo |111000    |
| 3  | foo |000111    |
+----+-----+----------+

If I use this query:

SELECT * FROM sch.mytable GROUP BY(key);

This is not correct I know that, because I should group by all the columns that I need to show.

Is there a solution for this problem?

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140

2 Answers2

27

A query that works for all DB engines would be

select t1.*
from sch.mytable t1
join
(
    SELECT min(id) as id
    FROM sch.mytable 
    GROUP BY key
) t2 on t1.id = t2.id

where min(id) is the function that influences which result you get. If you use max(id) you get the other.

juergen d
  • 201,996
  • 37
  • 293
  • 362
  • For others: In this example 'id' is the 'primary key' column of mytable. (I may be wrong, but That's what I assumed and query worked fine) – supernova May 25 '17 at 20:45
  • Just to note, `join` is the same thing as `inner join` as depicted [here](https://miro.medium.com/max/1200/1*YhYiJJnQLr5Z7PBKNakN2Q.png) – quasipolynomial Jul 17 '19 at 11:14
15

distinct on

select distinct on (key) *
from t
order by key, name

Notice that the order by clause determines which row will win the ties.

Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260