首页 > 解决方案 > 如何在 SQL Server 中的查询中添加每分钟没有数据的“空”记录

问题描述

我的查询由日期、时间(基本上是时间戳)和计算每小时补偿的字段组成。

date        time      comp/H
---------- ----- ----------------------
2019-09-10 07:01 13640,416015625
2019-09-10 07:02 8970,3193359375
2019-09-10 07:03 6105,4990234375
2019-09-10 07:04 7189,77880859375
2019-09-10 07:08 2266,73657226563
2019-09-10 07:57 163,527984619141

我想填补时间戳之间的空白,并为每分钟添加一条没有分配任何数据的新记录(例如,添加 07:05、07:06、07:07 的记录)。我会为这些记录的 comp/h 字段分配 0 值,但我不知道该怎么做。

最终目标是制作上述数据的折线图,在其中可以直观地看到停机时间。(因此“空记录”的值为 0)

原始查询:

select cast(p_timestamp as date) as 'datum', CONVERT(VARCHAR(5), p_timestamp, 108) as 'time', avg(((AantalPCBperPaneel*(AantalCP+AantalQP))/deltasec)* 3600) as 'comp/h'
from Testview3
where p_timestamp > '2019-09-01' 
group by CONVERT(VARCHAR(5), p_timestamp, 108), cast(p_timestamp as date)
order by cast(p_timestamp as date) asc , CONVERT(VARCHAR(5), p_timestamp, 108) asc

标签: sql-servertsql

解决方案


create or alter function range(@from int, @to int) returns @table table(val int) as
begin
    while @from <= @to begin
        insert @table values(@from)
        set @from = @from + 1;
    end;
    return;
end;

select h.val hour, m.val minute from range(0, 23) h cross join range(0, 59) m;

这将为您提供 1440 行,用于一天中每个小时的每一分钟。您可以将其加入您的数据以获得您想要的。


推荐阅读