Hello All,
I recently built a query in SQL that I can use to look at our payment log and find out an average number of payments made per hour over a period of time. I'm sure there are third party reporting applications that are much more suited for doing the type of calculation I'm trying to do, but just for fun, I'm kind of curious to see what other methods you all might use (in T-SQL) to get the data I'm looking for. I know it's kind of a dumb question, so I won't be offended if you down vote me. But, for anyone else out there that is bored like me, feel free to post your other solutions.
The table is set up with a [CreateDate] column which is the DATETIME value of when the payment posts to the account. I use this to determine which hour they made the payment in.
CREATE TABLE #TempTimes
(
[Time] DATETIME,
)
DECLARE @numDays INT
SET @numDays = 10
DECLARE @time DATETIME
SET @time = DATEADD(dd, DATEDIFF(dd, 0, GETDATE() - @numDays), 0)
WHILE @time < GETDATE()
BEGIN
INSERT #TempTimes
VALUES (@time)
SET @time = DATEADD(hour, 1, @time)
END
GO
/*
I have to join in a table with all of the hours for the time span I'm querying against,
because otherwise, the AVG function won't calculate in the hours where no payments were made.
*/
SELECT DATEPART(hour, [Time]) [Hour], AVG(CAST([Count] AS DECIMAL)) [Average]
FROM
(
SELECT [Time], CASE WHEN [Count] IS NULL THEN 0 ELSE [Count] END [Count]
FROM #TempTimes tt
LEFT JOIN
(
SELECT DATEADD(hour, DATEDIFF(hour, 0, [CreateDate]), 0) [hour], COUNT(*) [Count]
FROM [dbo].[PaymentLog]
GROUP BY DATEADD(hour, DATEDIFF(hour, 0, [CreateDate]), 0)
) t1 ON t1.[hour] = tt.[time]
) t2
GROUP BY DATEPART(hour, tt.[Time])
GO
DROP TABLE #TempTimes
GO
CJ