SQL Compare values in other rows

Asked

Viewed 193 times

-1

I have a table called transferencia that has data on the movement of a guest in a hotel, for example

inserir a descrição da imagem aqui

The table has no date of departure, so the date of departure is the data_entrada in which the transferencia is equal to transferencia + 1.

I need to make a query that returns an extra column with the date of exit described in the paragraph above and in case the last transferencia be equal to null, should return the current number of days, considering the current date of the consultation (in this case today, that is why the guest is still staying). If the value of the last record of transferencia be it <> null, is why the guest has already left and the system has calculated the amount of days he stayed.

My DBDS is Firebird 2.5

  • I didn’t understand your explanation after all x is never mathematically equal to x+1. In your example the date of exit is 07/01/2019 or 08/01/2019? For the data presented try to put what the expected result.

  • Why the departure date has to be the next record, not the input data_but the qtde_days column?

2 answers

1

You can use a subquery to search for the next record. This way also there is no danger of breaking the logic if there is a "hole" in the sequences:

SELECT t.*,
       (SELECT FIRST 1 t2.data_entrada
          FROM tranferencia t2
         WHERE t2.codigo_hospede = t.codigo_hospede
           AND t2.transferencia > t.transferencia
         ORDER BY t2.transferencia) AS data_saida
  FROM transferencia t
  • Thanks Sorack, I script was of great help

  • @Rafaelchristófano if the answer has met you do not forget to brand there as chosen

  • I added your answer to the calculation to count the number of days if the guest stays.

0

Answering my own question, with the help of Sorack, further increasing the question of counting the days if the guest stays.

select transf.codigo_hospede, transf.transferencia, transf.data_entrada, transf.quarto, 
iif(transf.qtde_dias is null,  DATEDIFF(day, transf.data_entrada, current_date),transf.qtde_dias),
from (
       SELECT t.*,
           (SELECT FIRST 1 t2.data_entrada
             FROM tranferencia t2
             WHERE t2.codigo_hospede = t.codigo_hospede
             AND t2.transferencia > t.transferencia
             ORDER BY t2.transferencia) AS data_saida
        FROM transferencia t) as transf

Browser other questions tagged

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