August 11, 2013 at 11:05 am
I need to write a SQL when i pass Max & Min Date like (2013-04-01,2010-01-01)
i should get below result which is 6 months difference
Mindate MaxDate
2010-01-012010-07-01
2010-07-012011-01-01
2011-01-012011-07-01
2011-07-012012-01-01
2012-01-012012-07-01
2012-07-012013-01-01
2013-01-012013-04-01
August 11, 2013 at 2:06 pm
DECLARE @minDate DATE = '2010-01-01';
DECLARE @maxDate DATE = '2013-04-01';
SELECT DATEADD(mm,6 * number,@mindate) AS ResultDate
FROM master.dbo.spt_values
WHERE type = 'P' AND DATEADD(mm,6 * number,@mindate) < @maxDate
ORDER BY number asc;
I used the numbers system table to get a sequential list of integers, starting from 0.
This is called a tally table. There are other (and better) ways to generate tally tables. A quick google search will lead you to them.
Need an answer? No, you need a question
My blog at https://sqlkover.com.
MCSE Business Intelligence - Microsoft Data Platform MVP
August 12, 2013 at 10:35 pm
To get exactly the expected results you specified, a very minor modification to Koen's query is in order:
DECLARE @minDate DATE = '2010-01-01';
DECLARE @maxDate DATE = '2013-04-01';
SELECT DATEADD(mm,6 * number,@mindate) AS MinDate
,CASE WHEN DATEADD(mm,6+6 * number,@mindate) > @maxDate
THEN @maxDate ELSE DATEADD(mm,6+6 * number,@mindate) END AS MaxDate
FROM master.dbo.spt_values
WHERE type = 'P' AND DATEADD(mm,6 * number,@mindate) < @maxDate
ORDER BY number asc;
My thought question: Have you ever been told that your query runs too fast?
My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.
Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
Since random numbers are too important to be left to chance, let's generate some![/url]
Learn to understand recursive CTEs by example.[/url]
[url url=http://www.sqlservercentral.com/articles/St
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply