oracle 如何在SQL中获得倒数第二个结果?

slwdgvem  于 2023-10-16  发布在  Oracle
关注(0)|答案(3)|浏览(367)

我想在查询中得到倒数第二个结果,但我不知道如何做到这一点。
我有一个代码,实际上得到了最后一行:

  1. (select sja.descricao
  2. from ldesk.jur_andamento sja
  3. where sja.id_andamento =
  4. (select max(id_andamento)
  5. from ldesk.jur_andamento sja2
  6. where sja2.id_assunto = a1.id_assunto
  7. and data_inclusao in
  8. (select max(data_inclusao)
  9. from ldesk.jur_andamento sja2
  10. where sja2.id_assunto = a1.id_assunto
  11. and data in
  12. (select max(data)
  13. from ldesk.jur_andamento
  14. where id_assunto = a1.id_assunto)))) ult_andamento_descr

在这段代码中,我从jur_andamento表中获得最后一个结果(descricao列),有没有办法获得倒数第二个结果?

20jt8wwn

20jt8wwn1#

使用DENSE_RANK解析函数。因此,如果您试图为每个id_assunto查找按data然后data_inclusao然后id_andamento排序的第二大行,则可以使用用途:

  1. SELECT *
  2. FROM (
  3. SELECT j.*,
  4. DENSE_RANK() OVER (
  5. PARTITION BY id_assunto
  6. ORDER BY data DESC, data_inclusao DESC, id_andamento DESC
  7. ) AS rnk
  8. FROM ldesk.jur_andamento j
  9. )
  10. WHERE rnk = 2;

如果你想要最大的data,然后是data_inclusao,然后是第二高的id_andamento,你可以分两步过滤:

  1. SELECT *
  2. FROM (
  3. SELECT t.*,
  4. DENSE_RANK() OVER (
  5. PARTITION BY id_assunto
  6. ORDER BY id_andamento DESC
  7. ) AS id_rnk
  8. FROM (
  9. SELECT j.*,
  10. DENSE_RANK() OVER (
  11. PARTITION BY id_assunto
  12. ORDER BY data DESC, data_inclusao DESC
  13. ) AS data_rnk
  14. FROM ldesk.jur_andamento j
  15. ) t
  16. WHERE data_rnk = 1
  17. )
  18. WHERE id_rnk = 2;
展开查看全部
mctunoxg

mctunoxg2#

而不是最大xou可以使用窗口函数ROW_NUMBER获得第二行,或任何其他的问题

  1. select sja.descricao
  2. from ldesk.jur_andamento sja
  3. where sja.id_andamento =
  4. (SELECT id_andamento FROM
  5. (select id_andamento, ROW_NUMBER() OVER(PARTITION BY id_assunto ORDER BY id_andamento DESC) rn
  6. from ldesk.jur_andamento sja2
  7. where sja2.id_assunto = a1.id_assunto
  8. and data_inclusao in
  9. (select max(data_inclusao)
  10. from ldesk.jur_andamento sja2
  11. where sja2.id_assunto = a1.id_assunto
  12. and data in
  13. (select max(data)
  14. from ldesk.jur_andamento
  15. where id_assunto = a1.id_assunto)
  16. )
  17. ) andamento
  18. WHERE rn = 2)
  1. ORA-00942: table or view does not exist

fiddle

展开查看全部
avwztpqn

avwztpqn3#

首先,如前所述,您应该适当地重写代码以使用ORDER BY子句。倒数第二个最大值相当于第二个最小值。
然后,执行这种类型任务的适当函数是row_number()。

  1. (SELECT descricao
  2. FROM (SELECT sja.descricao,
  3. row_number() over(ORDER BY sja.data, sja.data_inclusao, sja.id_andamento) rn
  4. FROM ldesk.jur_andamento sja)
  5. WHERE rn = 2) ult_andamento_descr

但是,也可以使用OFFSET:

  1. (SELECT descricao FROM ldesk.jur_andamento sja
  2. ORDER BY sja.data, sja.data_inclusao, sja.id_andamento
  3. OFFSET 1 rows FETCH FIRST 1 rows ONLY) ult_andamento_descr

相关问题