填写结果集中的每小时时间间隔

在某些时候,我使用时间戳将数据插入DB。我希望每小时查看一行没有记录填充最后记录数据的行: 表 日期时间值 12 4 15 6    期望的结果 日期时间值 12 4 13 4 14 4 15 6 16 6 它应该是可能的,但我想不出任何有效的方法.. 如何才能做到这一点?     
已邀请:
好了,误读了一次这个问题并提供了一个有效留下空白的答案;为了在sql中获取最后一个值,您需要循环效率较低的数据。
Create Table tblMyValues (MyHours int, MyValue int)
Insert into tblMyValues select 12, 4
Insert into tblMyValues select 15, 6
Insert into tblMyValues select 15, 6


Create Table tblResult (MyHour int, ReportValue Int)

Declare @i Int = 0, @LastValue Int
While @i <= 24
Begin

select @i = @i + 1
Select @LastValue = coalesce(MyValue, @LastValue)
From tblMyValues
Where MyHours = @i

    insert into tblResult 
    Select @i, @LastValue

End

select * from tblResult
drop table tblMyValues
drop table tblResult
这回来了
MyHour      ReportValue
----------- -----------
1           NULL
2           NULL
3           NULL
4           NULL
5           NULL
6           NULL
7           NULL
8           NULL
9           NULL
10          NULL
11          NULL
12          4
13          4
14          4
15          6
16          6
17          6
18          6
19          6
20          6
21          6
22          6
23          6
24          6
    
这需要第二张桌子。每小时都会有一排 时间戳,无论该时间戳是否有行 你描述的表。 说你的桌子是:
CREATE TABLE [dbo].[TimeStamp](
    [DateTimeHour] [int] NULL,
    [Value] [int] NULL
)
新表是:
CREATE TABLE [dbo].[DateTimeTally](
    [DateTimeHour] [int] NULL
)
将行插入表TimeStamp,将行0-23插入表DateTimeTally。 所以,最后的查询是:
SELECT DateTimeHour,
        ISNULL((SELECT VALUE FROM TimeStamp ST1 WHERE ST1.DateTimeHour = 
            (SELECT MAX(DateTimeHour)FROM TimeStamp ST2 
                             WHERE ST2.DateTimeHour <= 
                              A.DateTimeHour)),0) Value --Not equal, actually less than or equal
 FROM
(SELECT D.DateTimeHour DateTimeHour,T.Value Value FROM TimeStamp T
        RIGHT OUTER JOIN DateTimeTally D
        ON(T.DateTimeHour = D.DateTimeHour))A
返回:
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
希望有帮助:)     

要回复问题请先登录注册