I am working on a query where I want the average temperature of a whole month, but I have a challenge. When the new year starts the Month is 1 and i can't use the command:
MONTH(TimestampUTC) = MONTH(DATEADD(MONTH, -1, GETDATE()))
Because month 1 minus 1 is month 0.
Therefor I want to use a case expression to make my code work.
When I run the code below, I get the following warning which doesn't make sense to me, because it worked when I tested it when it wasn't in this query:
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near '='.
It is about the following line:
THEN MONTH(TimestampUTC) = MONTH(DATEADD(MONTH, +11, GETDATE()))
It looks like mssql doesn't accept an = statement after a THEN. I can't find it on the internet. Can somebody help me?
SELECT AVG(Value) AS AVG_temp
FROM(
SELECT Value, TimestampUTC
WHERE SourceName = 'Buitentemperatuur' and
CASE
WHEN MONTH(TimestampUTC) = 1
THEN MONTH(TimestampUTC) = MONTH(DATEADD(MONTH, +11, GETDATE()))
and YEAR(TimestampUTC) = YEAR(DATEADD(YEAR, -1, GETDATE()))
ELSE
MONTH(TimestampUTC) = MONTH(DATEADD(MONTH, -1, GETDATE()))
and YEAR(TimestampUTC) = YEAR(DATEADD(YEAR, 0, GETDATE()))
END
FROM vDataLogChannelValue
) x
The program i work in is Microsoft SQL Server Management Studio 2014. I already did some UNIT tests on the other parts of the code. When i add the CASE the error comes active and the code doesn't work anymore.