I have the SQL table BaseData
(values in value
column are random):
------------------------------------------------------
| Date | Value | Day | Moth | Year |
------------------------------------------------------
| 01-07-2020 | 1 | 1 | 7 | 2020 |
| 02-07-2020 | 2 | 2 | 7 | 2020 |
| 03-07-2020 | 3 | 3 | 7 | 2020 |
| 04-07-2020 | 4 | 4 | 7 | 2020 |
| 05-07-2020 | 5 | 5 | 7 | 2020 |
| 06-07-2020 | 6 | 6 | 7 | 2020 |
| 07-07-2020 | 7 | 7 | 7 | 2020 |
| 08-07-2020 | 8 | 8 | 7 | 2020 |
| 09-07-2020 | 9 | 9 | 7 | 2020 |
| 10-07-2020 | 10 | 10 | 7 | 2020 |
------------------------------------------------------
What I need is, to query data from the BaseData
in a way that for each row, I will have the SUM of the Values
from the last 7 days (not including the current day).
For example, for July 8th we should have the SUM of Values between July 1st and July 7th.
For example, this should be my result table for the given example from above:
----------------------------
| Date | ResultSum |
----------------------------
| 01-07-2020 | 0 | //assuming this is the first record
| 02-07-2020 | 1 | //SUM = 1
| 03-07-2020 | 3 | //SUM = 1 + 2
| 04-07-2020 | 6 | //SUM = 1 + 2 + 3
| 05-07-2020 | 10 | //SUM = 1 + 2 + 3 + 4
| 06-07-2020 | 15 | //SUM = 1 + 2 + 3 + 4 + 5
| 07-07-2020 | 21 | //SUM = 1 + 2 + 3 + 4 + 5 + 6
| 08-07-2020 | 28 | //SUM = 1 + 2 + 3 + 4 + 5 + 6 + 7
| 09-07-2020 | 35 | //SUM = 2 + 3 + 4 + 5 + 6 + 7 + 8
| 10-07-2020 | 42 | //SUM = 3 + 4 + 5 + 6 + 7 + 8 + 9
----------------------------
What I have so far is:
SELECT Date,
(SELECT SUM(nestedTable.Value)
FROM BaseData AS nestedTable
WHERE DATEADD(dd, DATEDIFF(dd, 0, Date), 0) BETWEEN
DATEADD(day, DATEDIFF(day, 0, DATEADD(d,-1, Date)), 0) AND
DATEADD(day, DATEDIFF(day, 0, DATEADD(d,-8, Date)), 0)
) AS ResultSum
FROM BaseData
But seems it's not working. I found some similar question here, but I am not able to figure out how can I use those answers here.