简体   繁体   中英

Get latest record from each group and number of group rows in MySQL

I got a table like this:

id | column_a | column_value
1  | x        | 5 
2  | y        | 7
3  | z        | 4,7
4  | x        | 3,6
5  | y        | 2
6  | w        | 5,8,9,11

I would like to get back column_value from latest record in each groups AND a count number of rows in the groups.

So the result should be this:

count(id) | column_value
2         | 3,6
2         | 2
1         | 4,7
1         | 5,8,9,11

I tried to reach this on the following two path:

select count(id), column_value 
from table 
group by column_a

This version get back the first records from the groups so its not ok for me.

select count(id), column_value 
from table 
where id in (select max(id) 
             from table 
             group by column_a)

This version also wrong because count cannot works well without group by.

I cannot figure it out how can I combine two versions advantages. Any help is appreciated.

Try this

Select cnt, column_value
from tst t inner join (
Select  column_a, count(id) cnt, max(id) as max_id
from tst
group by column_a ) x on (t.column_a= x.column_a and t.id = x.max_id)
order by cnt desc

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