I need to bring these fields filtering by day 31/01, 28(or 29)/02, 31/03, 30/04, etc.
The date field is E8_DTSALAT
From what I understand, want the query return the information on 31/1/2018, 28/2/2018, ..., 31/12/2018. At first each month has always the same number of days, except in leap years, for the month of February.
Here is a suggestion, which informs the year; from it the last day of each month of that year is generated through CTE (common table Expression).
-- código #1
-- informe o ano
declare @Ano smallint;
set @Ano= 2018;
--
with
Inicio_Meses as (
SELECT convert (date, ('1/'+cast(n as varchar(2))+'/'+cast(@Ano as char(4))), 103) as Data_Inicio
from (values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12)) as Mes (n)
),
Fim_Meses as (
SELECT dateadd (day, -1, dateadd (month, +1, Data_Inicio)) as Data_Fim
from Inicio_Meses
)
-- a consulta
SELECT E8_FILIAL, E8_AGENCIA, E8_CONTA,
E8_DTSALAT, E8_SALATUA
from SE8010 AS SE8
where SE8.E8_CONTA in ('84361','22700')
and SE8.D_E_L_E_T_ <> '*'
and SE8.E8_DTSALAT in (SELECT Data_Fim from Fim_Meses);
CTE Fim_months generates the last day of each month, according to the reported year. For testing purposes, try:
-- código #2 v2
declare @Ano smallint;
set @Ano= 2020;
with
Inicio_Meses as (
SELECT convert (date, ('1/'+cast(n as varchar(2))+'/'+cast(@Ano as char(4))), 103) as Data_Inicio
from (values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12)) as Mes (n)
),
Fim_Meses as (
SELECT Data_Inicio,
dateadd (day, -1, dateadd (month, +1, Data_Inicio)) as Data_Fim
from Inicio_Meses
)
SELECT * from Fim_Meses;
Which database?
– Marciano Machado
@Marcianomachado Sql Server
– Thiago Alessandro
If I understand your doubt, you want to filter from the 31st until the 1st, is that it? In this case could use a
order by E8_DTSALAT desc
.– bruno101
@Thiagoalessandro Encapsulating column in the WHERE clause with function is not a good practice as it makes the code non sargable. See article
Construindo códigos T-SQL eficientes: Sargability
in https://portosql.wordpress.com/2018/10/04/construindo-codigos-t-sql-eficientes-sargability/– José Diz