简体   繁体   中英

How to select LAST record in group by using mysql

I am trying to select the LAST of the record in group by in sql. In my case I use this code

SELECT c_id
     , Max(transaction_num)
     , Max(trans_date) trans_date
     , doc_type
     , amount as balance
  from tbl_ledger 
 where doc_type = 'B' 
 group 
    by c_id

and the data of the selected column is this在此处输入图片说明

so I basically trying to get the last balance amount. how can i select the last amount in sql?

the whole table content here : tbl_ledger 在此处输入图片说明

my output is getting the first balance amount: 在此处输入图片说明

The following query gives you the record that has the latest trans_date for each c_id :

select t.*
from tbl_ledger t
where 
    doc_type = 'B'
    and trans_date = (
        select max(t1.trans_date)
        from tbl_ledger t1
        where t1.doc_type = 'B' and t1.c_id = t.c_id
    )

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