In the SQL Server 2008 you can do something like this:
SELECT
SUM(DIFERENÇA) AS Mesanterior
FROM
TOTALIZADOR
WHERE
NID = 252 AND
DATAHORA BETWEEN
DATEADD(s,-1,DATEADD(mm,DATEDIFF(m,0,GETDATE()),0))
AND
DATEADD(s,1,DATEADD(s,-1,DATEADD(mm,DATEDIFF(m,0,GETDATE())-1,0)));
Retrieves the date of the first day of last month:
SELECT DATEADD(s,-1,DATEADD(mm,DATEDIFF(m,0,GETDATE()),0));
Retrieves the date from the last day of last month:
SELECT DATEADD(s,1,DATEADD(s,-1,DATEADD(mm,DATEDIFF(m,0,GETDATE())-1,0)));
If your server is equal to or higher than SQL Server 2012, you can use the function facility EOMONTH()
to obtain the last day of the month:
SELECT
SUM(DIFERENÇA) AS Mesanterior
FROM
TOTALIZADOR
WHERE
NID = 252 AND
DATAHORA BETWEEN
DATEADD( DAY, 1, EOMONTH(GETDATE(), -2))
AND
EOMONTH( GETDATE(), -1 );
Retrieves the date of the first day of last month:
SELECT DATEADD( DAY, 1, EOMONTH(GETDATE(), -2));
Retrieves the date from the last day of last month:
SELECT EOMONTH( GETDATE(), -1 );
Reference:
https://docs.microsoft.com/en-us/sql/t-sql/functions/eomonth-transact-sql
Possible duplicate of Select from previous months
– Pedro Paulo
Was any of the answer helpful? Don’t forget to choose one and mark it so it can be used if someone has a similar question!
– Sorack