Signaling the last SQL record

Asked

Viewed 46 times

2

I have the following SQL:

select cod_nota, cod_local, cod_produto, valor from pedido
order by
cod_nota,cod_local,cod_produto

With the result:

|cod_nota|cod_local|cod_produto| Valor | 
|  501   |   01    |   124714  | 150,00|
|  501   |   01    |   328180  | 120,00|
|  501   |   260   |   58014   | 100,00|
|  502   |   10    |   24587   | 50,00 | 
|  502   |   10    |   154547  | 20,00 |
|  502   |   10    |   154547  | 189,00|
|  502   |   15    |   24587   | 50,00 | 
|  503   |   10    |   154547  | 20,00 |
|  503   |   10    |   154547  | 189,00|

I wish to have the following result:

|cod_nota|cod_local|cod_produto| Valor |ULtimo| 
|  501   |   01    |   124714  | 150,00|      |
|  501   |   01    |   328180  | 120,00|  S   |
|  501   |   260   |   58014   | 100,00|  S   |
|  502   |   10    |   24587   | 50,00 |      | 
|  502   |   10    |   154547  | 20,00 |      |
|  502   |   10    |   154547  | 189,00|  S   |
|  502   |   15    |   24587   | 50,00 |  S   | 
|  503   |   10    |   154547  | 20,00 |      |
|  503   |   10    |   154547  | 189,00|  S   |

Where I’m dialing an "S" on the last note from Local.

  • I think you need something to identify the "greatest"

  • That’s right I want to identify the biggest.

1 answer

2


Assuming the latter is to have no larger product* in the same location/note , I make a subselect in the same table counting the largest if greater than zero is not last , if it is not.

select cod_nota, cod_local, cod_produto, valor  ,
       (select (case when count(*) > 0 then 'n' else 's' end) ultimo
        from  pedido p2 
        where p2.cod_local = p1.cod_local
        and   p2.cod_nota = p1.cod_nota
        and   p2.cod_produto > p1.cod_produto)
from pedido p1
order by cod_nota,cod_local,cod_produto

the subselect simulates a column, it counts the notes that exist and are "higher" than the note of the line in question , being greater than zero is not the "last" being = 0 is the "last"

  • I find it strange to do for the product (would have another key) ?
  • 1

    Cool worked. I just didn’t understand internally how this subselect is made, but it’s worth.

  • 1

    Edited solution for explanation

  • As I would do to identify the interval of records, for example, I would like to identify the last record in the interval of each 3 records and mark with 'F', and continue identifying the last one with 'F''.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.