"I’m working with a database table in SQL and I want to retrieve the first row of each group based on a certain column. The table has columns ‘group_id’ and ‘value’, and I want to retrieve the row with the lowest ‘value’ for each unique ‘group_id’. How can I achieve this using SQL?"
based on the example table above i would like to get just the name alex and brown
Here is what i have tried
SELECT * FROM tailors
WHERE id IN(
SELECT min(id)
FROM tailors
GROUP BY cat_id,id,name,status
)
but i am getting all the record when i am just trying to get the first data of each matching category id
3
Answers
To return only one row use
LIMIT 1
:You just need to take out id and name from your group by clause –
If the logic remains same throughout the table, and the version of the DB is 8.0+, then use such an aggregation :
assuming
id
is a primary key column, there will be only one minimum value per eachcat_id
.GROUP BY cat_id
is handled byPARTITION BY cat_id
and the other columns(name
andstatus
) following it should be removed.