0

Between a date range 2017-02-01 - 2017-02-10, i'm calculating a running balance. I have days where we have missing data, how would I include these missing dates with the previous days balance ?

Example data:

enter image description here

we are missing data for 2017-02-04,2017-02-05 and 2017-02-06, how would i add a row in the query with the previous balance? The date range is a parameter, so could change....

Can i use something like the lag function?

3 Answers 3

1

I would be inclined to use a recursive CTE and then fill in the values. Here is one approach using outer apply:

with dates as (
      select mind as dte, mind, maxd
      from (select min(date) as mind, max(date) as maxd from t) t
      union all
      select dateadd(day, 1, dte), mind, maxd
      from dates
      where dte < maxd
     )
select d.dte, t.balance
from dates d outer apply
     (select top 1 t.*
      from t
      where t.date <= d.dte
      order by t.date desc
     ) t;
Sign up to request clarification or add additional context in comments.

Comments

0

You can generate dates using tally table as below:

Declare @d1 date ='2017-02-01'
Declare @d2 date ='2017-02-10'

;with cte_dates as (
    Select top (datediff(D, @d1, @d2)+1) Dates = Dateadd(day, Row_Number() over (order by (Select NULL))-1, @d1) from
        master..spt_values s1, master..spt_values s2
)
Select * from cte_dates left join ....

And do left join to your table and get running total

Comments

0

Adding to the date range & CTE solutions, I have created Date Dimension tables in numerous databases where I just left join to them.

There are free scripts online to create date dimension tables for SQL Server. I highly recommend them. Plus, it makes aggregation by other time periods much more efficient (e.g. Quarter, Months, Year, etc....)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.