I’m having trouble getting a query to work. What I’m trying to do is sum a counter by user id but with conditions.
Currently my query gives the following output.
User ID EndDate Date Index
123 5/1/12 1/1/12 -1
123 5/1/12 1/25/12 1
123 5/1/12 2/13/12 -1
456 4/1/12 1/18/12 -1
456 4/1/12 2/15/12 -1
456 4/1/12 2/18/12 1
What I want to do with this list is sum the Index by User Id but with a catch. The Index must be summed in date order, also the min value of the index is -1 and max is 1, so the values can be -1, 0, 1 only. So with user 123, the process would be -1 then you add 1 then you add -1 for a final sum of -1. But for user 456 you start with -1 then you have -1 again but the sum must remain -1 then you have 1, so the final sum is 0. Below is what I’m been trying to do but I can’t figure it out. I would really appreciate some help.
DECLARE @Period char(6)
DECLARE @StatusCount int
SET @Period = '201201'
SET @StatusCount = 0
SELECT Q1.UserID, Q1.End_Date,
Sum(Case
When Index = -1 Then Case When @IndexCount >=0 Then @IndexCount - 1 Else @IndexCount + 0 End
When Index = 1 Then Case When @IndexCount <=0 Then @IndexCount + 1 Else @IndexCount + 0 End
END) as FinalIndex
FROM
(
(SELECT UserID, End_Date, Enter_Dt, 1 as Index
FROM UserTable
WHERE (Code in ('A', 'B') and PRD = @Period)
GROUP BY UserID, End_Date, Enter_Dt)
UNION
(SELECT UserID, End_Date, Enter_Dt, -1 as Index
FROM UserTable
WHERE (Code in ('C', 'D') and PRD = @Period)
GROUP BY UserID, End_Date, Enter_Dt)
) as Q1
GROUP BY Q1.UserID, Q1.End_Date
ORDER BY Q1.UserID ASC, Q1.End_Date ASC
I think my main problem is I can’t figure out how to accumulate the Index properly. I can’t get IndexCount to remember the the previous value and then start again from 0 with the next User ID
The result I get with this query is
User ID EndDate Index
123 5/01/12 -1
456 4/01/12 -1
Which is just summing the Index
I’ll illustrate a running total by userID solution here, leaving out the other details of your query for clarity. Basically, add a IndexRT column populate it with a running total that resets for each new userID.
EDIT: constrain running total to -1,0,1
Result: