获取MySQL中每个组的最新记录和组行数
我有一张这样的桌子:获取MySQL中每个组的最新记录和组行数,mysql,group-by,count,Mysql,Group By,Count,我有一张这样的桌子: 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 我想从每个组的最新记录中获取列_值,并计算组中的行数 因此,结果应该是: count(id) | column_value 2 | 3,6 2 |
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
我想从每个组的最新记录中获取列_值,并计算组中的行数
因此,结果应该是:
count(id) | column_value
2 | 3,6
2 | 2
1 | 4,7
1 | 5,8,9,11
我试图通过以下两条途径实现这一点:
select count(id), column_value
from table
group by column_a
这个版本从组中取回第一个记录,所以对我来说不合适
select count(id), column_value
from table
where id in (select max(id)
from table
group by column_a)
这个版本也是错误的,因为没有group by,count无法正常工作
我想不出如何将两个版本的优势结合起来。
感谢您的帮助。试试这个
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
在谷歌上搜索几个小时后,你就拯救了我的一天!泰:)