Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 joining to the same table twice on a date field

Author  Topic 

craigwg
Posting Yak Master

154 Posts

Posted - 2011-10-14 : 16:37:35
I have a table called operations. It has a field called description which is a utcdate() datatype. Nothing fancy.

The records in the table are organized so each record takes place on the first of any given month. For example 2011-02-01 or 2011-03-01 are records.

I am being asked to display records from a month as well as a month before. So, for example someone wants to request the data for March, 2011. I need the query to show the data for March 2011 and February 2011. The purpose is for comparison on a report.

That said, my current query in the SP runs great. But I can't figure out the join. Here is what I have:

[code[
FROM [360Dashboard].dbo.vw_operations o
join [360Dashboard].dbo.vw_operations o2 on o.lobid=o2.lobid and o.description = datediff(o2.description,datepart(mm,o2.description),-1)
[/code]

Of course that is crashing for the syntax errors. But I don't know if datediff() is what I should be using or what.

Help?

Craig Greenwood

craigwg
Posting Yak Master

154 Posts

Posted - 2011-10-14 : 17:12:13
This is where I am currently. I THINK this is right. Not sure.
[code]
FROM [360Dashboard].dbo.vw_operations o
LEFT JOIN [360Dashboard].dbo.vw_operations o2 on o.lobid=o2.lobid and dateadd(mm,-1,o.description) = o2.description
[\code]

Craig Greenwood
Go to Top of Page
   

- Advertisement -