I have a SQL Server table that has columns
[Username], [Team], [ID] (* primary key), [DateEntered], [Task], [T_ID], [ValueAmount]
The [T_ID]
can be grouped as there could be 5 different tasks which all have the same T_ID
example (a,b,c,d,e with the T_ID
of 1).
What I am trying to do is see the [ValueAmount]
, LastWeeks_ValueAmount
side by side but can't figure it out.
I have tried the following SQL
SELECT
UserName, Team, ID, [DateEntered], [Task], T_ID, ValueAmount,
LAG(ValueAmount) OVER (ORDER BY DateEntered) AS PreviousWeek,
DATEADD(dd, ((DATEDIFF(dd, '17530101', DateEntered) / 7) * 7) - 7, '17530101') StartPW,
DATEADD(dd, ((DATEDIFF(dd, '17530101', DateEntered) / 7) * 7) , '17530101') EndPW,
ROW_NUMBER() OVER (PARTITION BY [T_ID] ORDER BY DateEntered DESC) AS rn
FROM
Table
This returns the previous row, but not for the previous week so it's still not working. I think maybe a CTE with a case statement might work, but I can't figure it out and I hope someone can help?
I have tried to use the post below cut still can't get it to work:
To add some more detail there can be a multiple rows within the same week for example the one week there could be 2 rows for the same Task, Team etc, one being T_ID 1 and one being T_ID 26 the expected result would pick up the value for both on the previous week as they are for the same Team, Task and UserName.