[英]Mysql select distinct values and last row
很簡單。
msg_id msisdn message
----------------------------------
1000 661000 text1
1001 661002 text2
1002 661004 text3
1003 661002 text4
1004 661002 text5
1005 661002 text6
我需要獲取從最新到最舊的不同 msisdn 值以及最后一行中的所有值。 請理解,實際查詢中有更多列,因此我需要獲取不同的 msisdn - 以及該 msisdn 的最后一行的所有數據。
msisdn msg_id message
-----------------------------
661002 1005 text6
661004 1002 text3
661000 1000 text1
謝謝!
只是要清楚。 我開始於:
按 msisdn 從表組中選擇 distinct(msisdn), max(msg_id)
但是,提取有關 max(msg_id) 的所有信息是問題...我需要查詢中的整行,而不僅僅是 msg_id...
希望現在一切都清楚了。
您可以使用包含每個msisdn
的最大msg_id
的派生表,然后加入該表以獲取其余列:
select t1.*
from mytable as t1
inner join (
select msisdn, max(msg_id) as last_id
from mytable
group by msisdn
) as t2 on t1.msisdn = t2.msisdn and t1.msg_id = t2.last_id
select msisdn,msg_id,max(message)
from table1
group by msg_id,msisdn
order by msg_id desc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.