Skip to content
Advertisement

In SQL how to calculate days in a year based on a start date and the number of days lapsed

What would be the SQL to calculate the number of days in each year if I had a start date and the number of days that have lapsed?

For example, the date (ymd) 2013-01-01 and the days lapsed is 1000.

I would like the result to look like this

2013 = 365

2014 = 365

2015 = 270

Can this be written as a function like datediff?

I have tried using a calendar table, but of course, linking to this just gives me 2013 = 1000

My calendar table looks like this.

This is what i have tried.

SELECT

D.FISCAL_YEAR, SUM([DAYS]) AS NUMBER_OF_DAYS

FROM [dbo].[FACT] F

LEFT JOIN [dbo].[DIM_DATE] D ON D.DATE_ID = F.DATE_ID

GROUP BY

D.FISCAL_YEAR

The result for this is.

Advertisement

Answer

I would personally build a tally table to do this. Once you build that, you can easly get every date and count the number of days in each year:

As a function:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement