Skip to content
Advertisement

years between two dates in sql server with starting and end date of each of them in sql server

i want to get years between two dates with their starting and end dates.Suppose if i enter startdate as “07/06/2017” and enddate as “18/09/2019”, i want list the years in between with their starting and end date respectively.Kindly suggest me how it can be achieved.

Input Table:

Output Table:

I need to split the dates into months i.e. if BusinessGoal.Period = ‘Month’ and i need a single query that splits the dates according to the Period mentioned in the BusinessGoal table and given in the input and output table for both “Year” and “Month” respectively. Input Table (BusinessGoal):

Output Table (BusinessGoal):

Advertisement

Answer

You need a table of numbers, here i use the simplest one

EDIT

See the fiddle This is the version of my query with more conditions regarding which rows needed (note differencies in ON clause) and how to compute end date. It uses Soundappan’s ddl and data (extended) which are allegebly satifactory close to the real ddl and data. The main idea is the same, use a table of numbers. You may want to have instantiated table in your DB to use it in other similar queries.

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