CREATE FUNCTION dbo.TimeSerial (@hrs int, @min int, @sec bigint)
RETURNS nvarchar(10)
AS
BEGIN
DECLARE @result nvarchar(10), @total bigint, @AMorPM nvarchar(2)
DECLARE @hours int, @minutes int, @seconds int
-- convert everything to seconds handling null params with isnull or coalesce
SET @total = IsNull(@sec,0) + IsNull(@min,0) * 60 + IsNull(@hrs,0) * 3600
SET @total = 86400 + @total % 86400 -- handle negative time relative to midnight
;
-- calculate the hour portion
SET @hours = 0
IF (@total >= 3600)
BEGIN
SET @hours = floor(@total/3600) % 24
SET @total = @total % 3600
END
-- set am/pm based on hours in HH format
SET @AMorPM = 'PM'
IF @hours < 12
BEGIN
SET @AMorPM = 'AM'
END
-- adjust hours to non-military time
IF @hours > 12 OR @hours = 0
BEGIN
SET @hours = abs(@hours - 12)
END
;
-- calculate the minutes and seconds portion
SET @minutes = 0
IF (@total >= 60)
BEGIN
SET @minutes = floor(@total/60)
SET @total = @total % 60
END
;
-- set seconds to remainder
SET @seconds = @total
SET @result = Cast(@hours As nvarchar(2)) + ':'
+ RIGHT('0'+Cast(@minutes As nvarchar(2)), 2)
SET @result = @result + ':'
+ RIGHT('0'+Cast(@seconds As nvarchar(2)),2) + @AMorPM
;
RETURN @result ;
END
;
SELECT dbo.TimeSerial(14, 30, 0)
;
SELECT dbo.TimeSerial(Hr, Mi, 0) As [Hour], Count(*) AS [NoOfCalls]
FROM (
SELECT DatePart(hh, CallDateTime) As [Hr],
FLOOR(DatePart(n, CallDateTime)/30) * 30 As [Mi],
Customer
FROM (
SELECT '2009-01-01 14:02:23' AS CallDateTime, 'Fred' AS Customer
UNION SELECT '2009-02-01 15:43:13', 'Barney'
UNION SELECT '2009-04-01 00:13:15', 'Wilma'
UNION SELECT '2009-04-01 12:13:15', 'Betty'
UNION SELECT '2009-04-01 23:12:19', 'Bam Bam'
) CustomerCalls
) CallsByTime
GROUP BY Hr, Mi
ORDER BY Hr, Mi
;
12:00:00AM 1
12:00:00PM 1
2:00:00PM 1
3:30:00PM 1
11:00:00PM 1
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (0)