I have a query that is intended to count the elapsed time from a date in the past to today. Easy enough if I wanted a day count ("It's been 45 days since event A"), but the problem is that after 370 days I would want it to say "It's been 1 year and 5 days since event A".I think I've accounted for years and months, but I can't quite figure out the math for days. Here is my current code:/*--total timeselect cast(datediff(year, '2004-08-29 07:00:00.000',getutcdate()) /10 as char) + ' decades'union allselect cast(datediff(year, '2004-08-29 07:00:00.000',getutcdate())as char) + ' years'union allselect cast(datediff(month, '2004-08-29 07:00:00.000',getutcdate())as char) + ' months'union all select cast(datediff(day, '2004-08-29 07:00:00.000',getutcdate())as char) + ' days'union allselect cast(datediff(minute, '2004-08-29 07:00:00.000',getutcdate())as char) + ' minutes'union allselect cast(datediff(second, '2004-08-29 07:00:00.000',getutcdate())as char) + ' seconds'*/declare @weddate datetimedeclare @years intdeclare @months intdeclare @days intdeclare @hours intdeclare @minutes intdeclare @seconds intdeclare @sql nvarchar(2000)set @weddate='2004-08-29 19:30:00.00'--Calculate valuesset @years = datediff(year, @weddate,getutcdate())set @months = datediff(month, @weddate,getutcdate())set @days = datediff(day, @weddate,getutcdate())set @hours = datediff(hour, @weddate,getutcdate())set @minutes = datediff(minute, @weddate,getutcdate())set @seconds = datediff(second, @weddate,getutcdate())select @sql= CASE WHEN @years = 0 THEN '' ELSE cast(@years as varchar)+ ' years, ' ENDselect @sql=@sql + CASE WHEN @months = 0 THEN '' ELSE cast(@months-1-((@years-1)*12) as varchar)+ ' months, ' ENDselect @sql=@sql + CASE WHEN @days = 0 THEN '' ELSE cast(@days-((@years-1)*365) as varchar)+ ' days, ' ENDselect @sql=@sql + CASE WHEN @hours = 0 THEN '' ELSE cast(@hours-((@days-1)*24) as varchar)+ ' hours, ' ENDselect @sql=@sql + CASE WHEN @minutes = 0 THEN '' ELSE cast(@minutes-((@hours-1)*60)-60 as varchar)+ ' minutes, ' ENDselect @sql=@sql + CASE WHEN @seconds = 0 THEN '' ELSE cast(@seconds-((@minutes-1)*60)-60 as varchar)+ ' seconds.' ENDselect @sql=' Since event A ' + @sql select @sql = @sql print @sql
If there is a more efficient way to get my desired output I'm open to ideas. Thanks!Craig Greenwood