This requires a second table. It will have a row for each hourly timestamp, regardless of whether there are rows for these timestamps for the table that you described.
Say your table:
CREATE TABLE [dbo].[TimeStamp]( [DateTimeHour] [int] NULL, [Value] [int] NULL )
And a new table:
CREATE TABLE [dbo].[DateTimeTally]( [DateTimeHour] [int] NULL )
Insert rows into the TimeStamp table and rows 0-23 into the DateTimeTally table. So the final request:
SELECT DateTimeHour, ISNULL((SELECT VALUE FROM TimeStamp ST1 WHERE ST1.DateTimeHour = (SELECT MAX(DateTimeHour)FROM TimeStamp ST2 WHERE ST2.DateTimeHour <= A.DateTimeHour)),0) Value
This returns:
DateTimeHour Value ----------- ----------- 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 10 0 11 0 12 4 13 4 14 4 15 6 16 6 17 6 18 6 19 6 20 6 21 6 22 6 23 6
Hope that helps :)
user547541
source share