Friday, July 5, 2019

sql - Select all columns with GROUP BY one column




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



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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...