SQL Query - Doubt Condition Dates

Asked

Viewed 58 times

2

Guys, good afternoon! I’m having difficulty in the consultation below. I want you to bring all the tasks only when their salary (tarexpiration field) is equal to the month after the opening date (tardata). However, nothing came in the consultation.

select * 
from Tarefa 
where TarID = 173151 
    and MONTH(TarVencimento) = DATEADD(MONTH,1,TarData)
  • It is strange this consultation, explain better Tarid example Tarid = 173151 with several salaries?

  • Renan ?

  • @Rovannlinhalis, you solved

3 answers

3

Just putting the @Rovann response in context

The DATEADD returns a date. O MONTH returns an integer representing the date month.

Soon your cloistered Where MONTH(TarVencimento) = DATEADD(MONTH,1,TarData) doesn’t seem to make sense.

It makes more sense, you cloister where, changing her to MONTH(TarVencimento) = MONTH(DATEADD(MONTH,1,TarData)). Where you add 1 month to the field TarData, takes the month and last compares with the month of TarVencimento.

Seeing your question, I see that I stopped in time with the studies of SQL Server, because I still use the DATEPART to pick up the month in the date fields, getting something like: DATEPART(MONTH, TarVencimento) = DATEPART(MONTH, DATEADD(MONTH,1,TarData)), which is still right too, because the DATEPART returns an integer representing the datepart of the specified date.

2

If I understand correctly: ?!

select * 
from Tarefa 
where TarID = 173151 
    and MONTH(TarVencimento) = MONTH(DATEADD(MONTH,1,TarData))

1


I believe that’s more or less what you need, follow my test:

CREATE TABLE teste(tarId INT, TarVencimento DATE);

INSERT INTO teste VALUES(173151,'2017-12-01'),(173151,'2018-01-01'),(173151,'2018-02-01');

SELECT
    *
FROM
teste a
INNER JOIN
(
select
    tarId,
    TarVencimento 
from teste
where tarId = 173151
) as aux
ON a.tarId = aux.tarId
WHERE month(aux.TarVencimento) = month(a.TarVencimento + interval 1 month)

Upshot:

inserir a descrição da imagem aqui

Invoice 1 refers to 2 (later month) and invoice 2 to 3 (later month)

If you want to catch only 1 you can sort by ASC Tarexpiration and add a LIMIT 1

Browser other questions tagged

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