Friday 5 July 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...