Select the SECOND LAST record in each group

别等时光非礼了梦想. 提交于 2019-11-30 14:29:01

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.)

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!