简体   繁体   中英

Selecting the last entry from each group in MYSQL

I am very new to MySQL (I tried groupby, but didnt get the result) This my sample data

ticket year status data
111    2007 1      32
111    2007 2      46
111    2007 3      40
111    2007 4      38
111    2009 1      15
111    2009 2      12
115    2009 1      2 
115    2009 2      5

I want to select the last entry for each company, for each year. Output should be:

ticket year status data
111    2007 4      38 
111    2009 2      12
115    2009 2      5

as status field values looks incremental order. we can simply apply max after groupby.

select a.* from a 
inner join (select ticket,year,max(status) as sta from a group by ticket,year) as b 
on a.status=b.sta 
and a.ticket=b.ticket and a.year=b.year;

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