Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all columns with GROUP BY one column [duplicate]

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?

like image 893
YCF_L Avatar asked Oct 02 '16 10:10

YCF_L


People also ask

How do I select all columns in a GROUP BY in SQL?

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

Does GROUP BY clause remove duplicates?

GROUP BY does not remove duplicates.

Does GROUP BY allow duplicates?

GROUP BY only treats two rows as duplicates if all the column values in both the rows are the same. If even a single column value in either of the row is non-matching, they are treated as unique.

Can we use select * with GROUP BY?

Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause. The original idea was to create the table in beginning of the query, so the (SELECT * FROM #TBL) could be used on the query itself, instead of defining the names on each GROUP BY.


1 Answers

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.

like image 192
juergen d Avatar answered Sep 29 '22 12:09

juergen d