如何在SQL中获取倒数第二条查询结果?已有获取最后行的SQL代码
获取倒数第二条数据的SQL修改方案
方法一:基于原有逻辑调整
原SQL通过多层MAX()嵌套获取最新记录,要拿到倒数第二条,只需在取最大id_andamento的子查询里,新增条件排除掉当前最大的那个id,就能得到第二大的id对应的记录:
(select sja.descricao from ldesk.jur_andamento sja where sja.id_andamento = (select max(id_andamento) from ldesk.jur_andamento sja2 where sja2.id_assunto = a1.id_assunto and data_inclusao in (select max(data_inclusao) from ldesk.jur_andamento sja2 where sja2.id_assunto = a1.id_assunto and data in (select max(data) from ldesk.jur_andamento where id_assunto = a1.id_assunto)) -- 排除最大的id_andamento,取第二大的 and sja2.id_andamento < (select max(id_andamento) from ldesk.jur_andamento sja3 where sja3.id_assunto = a1.id_assunto and data_inclusao in (select max(data_inclusao) from ldesk.jur_andamento sja4 where sja4.id_assunto = a1.id_assunto and data in (select max(data) from ldesk.jur_andamento where id_assunto = a1.id_assunto))))) ult_andamento_descr
方法二:用窗口函数简化实现(推荐)
如果你的数据库支持窗口函数(比如MySQL 8.0+、PostgreSQL、Oracle等),用ROW_NUMBER()排序后直接取第二行会更简洁,逻辑也更清晰:
(select descricao from ( select sja.descricao, -- 按id_assunto分组,按data、data_inclusao、id_andamento降序排序 ROW_NUMBER() OVER (PARTITION BY sja.id_assunto ORDER BY sja.data DESC, sja.data_inclusao DESC, sja.id_andamento DESC) as rn from ldesk.jur_andamento sja where sja.id_assunto = a1.id_assunto ) t -- 取排序后的第二行,即倒数第二条 where rn = 2) ult_andamento_descr
这里的排序规则和你原SQL的逻辑完全一致,确保取到的是符合你原有“最新”定义的倒数第二条记录。
内容的提问来源于stack exchange,提问作者user21051730
相关产品推荐
相关产品推荐

