Select the SECOND LAST record in each group

前端 未结 3 1702
暖寄归人
暖寄归人 2021-01-02 18:36

There is a table Remark that contains data as shown below:

       SerialNo | RemarkNo  | Desp
=============================================
             


        
相关标签:
3条回答
  • 2021-01-02 19:06

    Here is some sql pseudo-code to get you started:

    select
      penultimate.*
    from data as penultimate
    left join (
      /* query on data to return last row frome each group */
    ) as ultimate
      on /* sql to join 2nd last record on each group to last group */
    where not ultimate.SerialNo is null
    
    0 讨论(0)
  • 2021-01-02 19:25

    Completely ineffective solution, but works ...

    SELECT
      SerialNo,
      RemarkNo,
      (SELECT Desp
       FROM Remarks
       WHERE SerialNo = r3.SerialNo AND RemarkNo = r3.RemarkNo) Desp
    FROM (
      SELECT
          r.SerialNo,
          (SELECT r2.RemarkNo
           FROM Remarks r2
           WHERE r.SerialNo = r2.SerialNo
           ORDER BY r2.RemarkNo DESC
           LIMIT 1, 1) RemarkNo
      FROM (SELECT DISTINCT SerialNo FROM Remarks) r) r3
    

    Working example: http://sqlfiddle.com/#!2/a1f89/22

    0 讨论(0)
  • 2021-01-02 19:32

    Try:

    select s.SerialNo, r.RemarkNo, r.Desp
    from (select SerialNo, max(RemarkNo) maxRemark from Remark group by SerialNo) s
    left join Remark r on s.SerialNo = r.SerialNo and s.maxRemark-1 = r.RemarkNo
    

    (SQLFiddle here.)

    0 讨论(0)
提交回复
热议问题