I have the following table
create table summry(
id varchar(12),
Desc varchar(50),
Qty decimal(25),
code varchar(20),
Date int,
Days int)
Days is calculated based on Date for that id and Code.
For ex:if id-294 code-123 has Date 16/1 then Days is 1
if the same id-294 and code-123 has Date 17/1 then Days is 2 with second entry followed
How to write SQL query for this update?
Insert into summary(id, code,date,days)values(294,123,’12/1/24′,1)
Data:
Id | code | date | days |
---|---|---|---|
294 | 123 | 12/1/24 | 1 |
294 | 123 | 13/1/25 | 1 |
294 | 123 | 15/1/25 | 1 |
294 | 123 | 16/1/25 | 1 |
294 | 123 | 17/1/25 | 1 |
Expected :
Id | code | date | days |
---|---|---|---|
294 | 123 | 12/1/25 | 1 |
294 | 123 | 13/1/25 | 2 |
294 | 123 | 15/1/25 | 1 |
294 | 123 | 16/1/25 | 2 |
294 | 123 | 17/1/25 | 3 |
Since 14th not der hence days calculation starts from 1 again.so majorly days is calculted based on date for a particular I’d and code
2
Answers
It seems like a gap and island problem where island is a continuous sequence and gaps are missing value like in your case missing dates.
Island
CTE identifies the continuous dates by first ranking within each id and code and then subtracting those many days.Then outer query ranks within each id, code and continuous dates
Final Query combining the two steps
Example Fiddle
Output
I have included an update statement but was unsure if you wanted to update
Result
Output after update