I am trying to count (by hour) the number of entries into a database. I have successfully written a query that counts by hour, but it omits hours with zero entries. I need the results to include the zeroes. I have looked around the internet, and have found a lot of suggestions. I have created a View that has one column with datetime entries by minute. I've tried joining the main table to this view and I get the same results as without the join. Still no zeroes. Wondering how to get this query to return zeroes. I am using MS SQL 2008 R2. any suggestions?
declare @limit datetime;
use InputArchive
set @limit = current_timestamp;
set @limit = DATEADD(hour, -72, @limit);
SELECT DATEADD(hour, datediff(hour, 0, ArchivedItems.RecordCreated), 0) as TimeHour, COUNT(ISNULL((ArchivedItems.RecordCreated),' ')) as NumPerHour
FROM ArchivedItems
LEFT OUTER JOIN vw_hoursalot
ON vw_hoursalot.dtHr = ArchivedItems.RecordCreated
where InputTypeId = 5 or InputTypeId = 6 or InputTypeId = 8 and (ArchivedItems.RecordCreated >= @limit)
Group BY DATEADD(hour, Datediff(hour, 0, ArchivedItems.RecordCreated), 0)
order by DATEADD(hour, datediff(hour, 0, ArchivedItems.RecordCreated), 0) desc
option (MAXRECURSION 0)
Update: I changed the hoursalot view to be by the hour I'm sorry but I'm not sure what you mean by full view SQL.
I can't put any strait info from the archivedItems table for legal reasons but the RecordCreated column is a strait timestamp ie '2013-04-05 14:09:59.167'
Here is what I came up with:
Here is what I used to create the test data
Try putting the vw_hoursalot as the leftmost table in the condition - this will mean that all rows from the view will be returned, whether a corresponding record in ArchivedHours is found or not.
I've edited again - this time I took the time to mock up some dummy data, and I realized that a problem in the code, both mine and yours, is that the
ArchivedItems.RecordCreated
column is being used as a filter in the WHERE condition. Therefore, only records with an existingRecordCreated
value will be returned.I've moved that condition to the JOIN, and run the query below against some very basic data I mocked up. Assuming that your
vw_HoursALot
view is returning twenty-four integers numbered 0-23, this ought to get you the data you are looking for.PLEASE NOTE: I made the assumption that
InputTypeID
is fromArchivedItems
.