Here's a handy function that I use for reporting; it lets you specify a start date and number of days per "chunk". Use it in a group by to easily have the same report function for per-day, per-week, per-month, etc.For example,select dbo.f_util_DateChunk('2003-01-01',7,sales_date),sum(sales_price)from salesgroup by dbo.f_util_DateChunk('2003-01-01',7,sales_date)order by dbo.f_util_DateChunk('2003-01-01',7,sales_date) asc
will give weekly sales totals. Replace the "7" in both DateChunk functions with "30" and use the same report to get monthly totals. Makes it easy to parameterize reports.Cheers-bCREATE FUNCTION dbo.f_util_DateChunk (@dStartDate datetime,@iInterval int,@dDate datetime)RETURNS datetime AS BEGIN DECLARE @iDays intselect @dStartDate=dbo.f_util_DateOnly(@dStartDate)select @dDate=dbo.f_frnk_util_DateOnly(@dDate)select @iDays=datediff(day,@dStartDate,@dDate)select @iDays=@iDays/@iIntervalselect @dDate=dateadd(day,@iDays*@iInterval,@dStartDate)return @dDateENDCREATE FUNCTION dbo.f_util_DateOnly (@dDate as datetime) RETURNS datetime AS BEGIN DECLARE @d datetimeselect @d=convert(datetime,convert(varchar(10),@dDate,101))return @dEND
Edited by - aiken on 04/05/2003 14:17:47