簡體   English   中英

獲取每個組的最新記錄以及MySQL中的組行數

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

我有一張這樣的桌子:

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)

這個版本也是錯誤的,因為如果沒有分組依據,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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM