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?
Answer
select distinct on (key) *
from t
order by key, name
Notice that the order by
clause determines which row will win the ties.
No comments:
Post a Comment