SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Creating a row for each month
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

singularity
Posting Yak Master

151 Posts

Posted - 01/24/2013 :  11:26:35  Show Profile  Reply with Quote
I have data as follows:

assessment_date
2/29/2012
9/11/2012
10/17/2012

I need to create a row for every month based on the latest assessment_date as of that month:

assessment_date month
2/29/2012 2/29/2012
2/29/2012 3/31/2012
2/29/2012 4/30/2012
2/29/2012 5/31/2012
2/29/2012 6/30/2012
2/29/2012 7/31/2012
2/29/2012 8/31/2012
9/11/2012 9/30/2012
10/17/2012 10/31/2012
10/17/2012 11/30/2012
10/17/2012 12/31/2012

I have a calendar table but can't figure out how to achieve this result.

Thanks in advance.












James K
Flowing Fount of Yak Knowledge

3724 Posts

Posted - 01/24/2013 :  12:39:02  Show Profile  Reply with Quote
select
	b.assessment_date,
	a.date_month
from
	calendar a
	outer apply
	(
		select top (1) b.assessment_date
		from assessment_table b
		where b.assessment_date <= a.date_month
		order by b.assessment_date desc
	)b
Go to Top of Page

singularity
Posting Yak Master

151 Posts

Posted - 01/24/2013 :  18:16:52  Show Profile  Reply with Quote
Thank you, that worked great. Just out of curiosity, is there any way to achieve the same result without using APPLY?
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52325 Posts

Posted - 01/25/2013 :  01:56:41  Show Profile  Reply with Quote

select *
from CalendarTable f
INNER JOIN assessment_table t
ON t.assessment_date = (SELECT TOP 1 assessment_date
                        FROM assessment_table 
						WHERE assessment_date<=f.[Date]
						ORDER BY assessment_date DESC)


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

singularity
Posting Yak Master

151 Posts

Posted - 01/25/2013 :  21:38:21  Show Profile  Reply with Quote
Thank you, James and Visakh
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52325 Posts

Posted - 01/26/2013 :  00:37:24  Show Profile  Reply with Quote
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.08 seconds. Powered By: Snitz Forums 2000