I am struggling with a query that tried few days back with a suggestion of one of my friend and got it work with the following using LEAD/LAG function:
WITH your_table(ID, STOREDATE, VALUE, INFO)
AS
(
SELECT 1122,'1/1/2020',2,'DONE' UNION ALL
SELECT 1122,'1/2/2020',7,'DONE' UNION ALL
SELECT 1122,'1/3/2020',1,'DONE' UNION ALL
SELECT 1122,'1/4/2020',7,'DONE' UNION ALL
SELECT 4466,'1/1/2020',2,'DONE' UNION ALL
SELECT 4466,'1/2/2020',7,'DONE' UNION ALL
SELECT 4466,'1/3/2020',1,'DONE' UNION ALL
SELECT 4466,'1/4/2020',8,'DONE'
),
CTE AS
(
SELECT ID,
STOREDATE,
VALUE,
CASE
WHEN VALUE = 8 THEN 0
WHEN VALUE + LAG(VALUE) OVER(ORDER BY ID, STOREDATE) = 8
AND ID = LAG(ID) OVER(ORDER BY ID, STOREDATE) THEN 0
WHEN VALUE + LEAD(VALUE) OVER(ORDER BY ID, STOREDATE) = 8
AND ID = LEAD(ID) OVER(ORDER BY ID, STOREDATE) THEN 0
ELSE VALUE
END VALUE2,
INFO
FROM your_table
)
SELECT *,
CASE
WHEN
(
SELECT COUNT(*) FROM CTE A
WHERE A.VALUE2 = 0 AND A.STOREDATE < B.STOREDATE
AND A.ID = B.ID
) >= 1 AND B.VALUE = 8 THEN B.VALUE
WHEN
(
SELECT SUM(A.VALUE)
FROM CTE A
WHERE A.VALUE2 = 0
AND A.STOREDATE < B.STOREDATE
AND A.ID = B.ID
)>= 8 THEN B.VALUE
ELSE B.VALUE2
END VALUE3
FROM CTE B;
My idea is to get sum of 8 or value 8 at any given row for specific id. So for the above input, my expected output is this:
ID STOREDATE VALUE INFO
1122 1/1/2020 2 DONE
1122 1/2/2020 0 //1 + 7 = 8; it'll update both the rows with zero
1122 1/3/2020 0 //For this, it's just fine
1122 1/4/2020 8 DONE //Will not update as I've the sum of 8 or 8 above once
Now my problem is with the below inputs that I can't figure out how to get expected result set.Here are the samples:
Input:
ID STOREDATE VALUE INFO
1122 1/1/2020 2 DONE
1122 1/2/2020 1 DONE
1122 1/3/2020 2 DONE
1122 1/4/2020 7 DONE
Expected Output:
ID STOREDATE VALUE INFO
1122 1/1/2020 2 DONE
1122 1/2/2020 0
1122 1/3/2020 2 DONE
1122 1/4/2020 0
Input:
ID STOREDATE VALUE INFO
1122 1/1/2020 2 DONE
1122 1/2/2020 2 DONE
1122 1/3/2020 2 DONE
1122 1/4/2020 2 DONE
Expected Output:
ID STOREDATE VALUE INFO
1122 1/1/2020 0
1122 1/2/2020 0
1122 1/3/2020 0
1122 1/4/2020 0
I am not sure how to get the result set and is there a way I can make tweaks to the above query to make work? Any idea would be highly appreciated - Thanks.