【问题标题】:Get latest record from each group and number of group rows in MySQL获取 MySQL 中每个组的最新记录和组行数
【发布时间】:2018-07-06 08:15:09
【问题描述】:

我有一张这样的桌子:

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

我想从每个组中的最新记录中取回 column_value 以及组中的行数。

所以结果应该是这样的:

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 不能很好地工作。

我不知道如何结合两个版本的优势。 任何帮助表示赞赏。

【问题讨论】:

    标签: mysql group-by count


    【解决方案1】:

    试试这个

    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
    

    【讨论】:

    • 在 Google 上搜索了几个小时后,您可以节省我的时间!泰:)
    猜你喜欢
    • 1970-01-01
    • 2017-02-05
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多