簡體   English   中英

如何使用mysql選擇組中的最后一條記錄

[英]How to select LAST record in group by using mysql

我正在嘗試在 sql 中選擇 group by 中記錄的最后一個。 就我而言,我使用此代碼

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

所選列的數據是這樣的在此處輸入圖片說明

所以我基本上試圖獲得最后的余額。 如何在sql中選擇最后一個金額?

整個表格內容在這里:tbl_ledger 在此處輸入圖片說明

我的輸出是第一個余額: 在此處輸入圖片說明

以下查詢為您提供每個c_id具有最新trans_date的記錄:

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
    )

暫無
暫無

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

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