Monday, January 25, 2010

TSQL Function - Current Date to Midnight

I find that I perform an awful lots of aggregations for the reports that I am writing these days. In Tsql this basically means plenty of sum, count, avg etc. But it also means that I am using alot of group by. These days I am grouping by date and each given day. I needed a TSQL inline function to set the current date to midnight. Here's what I cam up with in 1 line!

Create function dbo.SetDatetoMidnight(@inputdate datetime)
returns datetime
begin
return dateadd(d,datediff(d,0,@inputdate),0)
end

Quick breakdown of the code here. If you run the following select statement "select datediff(d,0,getdate())" in query analyzer or SQL Server Management Studio you will see an int value result depending on the actual date you use as an input parameter. This int value is the number of days between day 0 (zero) and the input date. 1900-01-01 is widely recognized as day 0. Don't believe me? Run this test:

declare @d datetime
set @d = GETDATE() -- or whatever date you want.

select @d

declare @num_of_days int
set @num_of_days = (select datediff(d,0,getdate()))

select @num_of_days

select DATEADD(d, - @num_of_days ,@d)


Now for the datadd portion of the function. By adding the number of days that is represented by a datediff between the inputdate and day zero I get the same number of days between day zero and the input date. this effectively strips off the time portion and gives me the YYYY-MM-DD with a midnight representation for time.

select sum(sales_number),dbo.SetDatetoMidnight(datetime_column)
from sales_data_table
where datetime_column between "some start" and "some end"
group by dbo.SetDatetoMidnight(datetime_column)\

I have also created functions for month, quarter and year for longer term reporting. Those will be posted in the coming days and weeks. Good luck with dates and grouping.

Labels:

0 Comments:

Post a Comment

<< Home