For our internal dashboard work, we're looking at metrics for the previous month. While I could create a SQL Server stored procedure to pass these dates from a user form, I really want to create a SQL view that will show last month's information. That way, whenever the view is opened, it always shows data for last month.
I know in VB that there are FirstDayOfMonth and LastDayOfMonth functions, but I've been unable to find similar functions in SQL. In my research, I've found "Date and Time Manipulation in SQL Server 2000" helpful. I came up with this SQL:
It returns these results:
SELECT
CAST(CONVERT(CHAR(10), DATEADD(dd,-(DAY(GETDATE())-1),GETDATE()),101) AS smalldatetime) AS StartDate,
CAST(CONVERT(CHAR(10), DATEADD(dd,-(DAY(DATEADD(mm,1,GETDATE()))),DATEADD(mm,1,GETDATE())),101) AS smalldatetime) AS EndDate,
CAST(CONVERT(CHAR(10), DATEADD(dd,-(DAY(DATEADD(mm,-1,GETDATE()))-1),DATEADD(mm,-1,GETDATE())),101) AS smalldatetime) AS PrevMonthStartDate,
CAST(CONVERT(CHAR(10), DATEADD(dd,-(DAY(DATEADD(mm,1,GETDATE()))),GETDATE()),101) AS smalldatetime) AS PrevMonthEndDate
StartDate | EndDate | PrevMonthStartDate | PrevMonthEndDate |
---|---|---|---|
2008-08-01 00:00:00 | 2008-08-31 00:00:00 | 2008-07-01 00:00:00 | 2008-07-31 00:00:00 |
-----
Check out my other blogs:
Daniel Johnson, Jr.
Get That Job!
Journey Inside My Mind Blog
Journey Inside My Mind Podcast
QuotesBlog
Twitter.com/danieljohnsonjr
Connect on LinkedIn
Interesting Things I've Read
Related tags: daniel+johnson+jr sql+server
No comments:
Post a Comment