Reputation:
I am trying to sum a value in SQL when a date within the table is between max(date of another field)-7 and max(date of data).
Example: sum(case when date from table between max(date from table)-7 and max(date from table) then field to sum else 0 end) as '0-7 Days'
Upvotes: 0
Views: 805
Reputation: 46
What you have is very close, this slight adjustment should do the trick.
DECLARE @DateFromTable DATETIME = GETDATE();
DECLARE @ValuetoSum INT = 5;
SELECT
CASE WHEN @DateFromTable BETWEEN MAX(@DateFromTable) - 7 AND MAX(@DateFromTable)
THEN SUM(@ValuetoSum) ELSE 0 END AS '0-7 Days'
Upvotes: 0