简体   繁体   中英

SQL - Select first group in group by

I have this table in DB2:

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

When I group by name by I can extract the table grouped by the name, but how can I automatically only extract the first group, to get this result:

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

How can I solve this?

The MIN function will identify which row is the first one by id, then you can use that to filter the result to show only that row.

SELECT id,name,key
FROM Table1
WHERE id IN (SELECT MIN(ID) FROM Table1 GROUP BY name,key)

You could use a inner join on subselect aggregated by min id

select * from mytable
inner join  (
  select min(id) my_id
  from mytable 
  group by name, key
) t on t.my_id = mytable.id

It looks like you want to get all names that have the same as the min(id). If this us correct then this should work:

Otherwise, please explain what you mean by "first group" and how that is defined.

select * from table
inner join  (
  select name, min(id)  
  from table 
  group by name 
) t on t.name = table.name

In theory, given the way the question is asked you could also just do a simple select on the name you want.

SELECT id,name,key
From Table1
Where name = 'foo'

It really depends what you mean by 'first group'. If you grouped by name and ordered ascending by name then 'bar' would actually be the 'first group', not 'foo'. Maybe if you clarify that we can give you better answers?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM