选择每个组中的SECOND LAST记录

时间:2013-03-16 18:48:50

标签: mysql greatest-n-per-group mysql-workbench dml sqlyog

表格Remark包含如下所示的数据:

       SerialNo | RemarkNo  | Desp
=============================================
             10 |         1 | rainy
             10 |         2 | sunny
             11 |         1 | sunny
             11 |         2 | rainy
             11 |         3 | cloudy
             11 |         4 | sunny
             12 |         1 | rainy

什么查询将返回以下结果:

             10 |         1 | rainy
             11 |         3 | cloudy
             12 |      null | null

也就是说,应该返回每组中的第二个最后一条记录?

假设SerialNo的所有RemarkNo都是连续的。备注数量越大,评论越晚。因此,序列号10的第二个RemarkNo是1,Desp'rainy'。

3 个答案:

答案 0 :(得分:5)

尝试:

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.

答案 1 :(得分:0)

这里有一些sql伪代码可以帮助你入门:

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

答案 2 :(得分:0)

完全无效的解决方案,但有效...

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

工作示例:http://sqlfiddle.com/#!2/a1f89/22