SQL 中每小时重复一组记录
Repeat set of records for each hour in SQL
我有 table 称为“数据”。这包含三列Time(datetime),Tag(int),Value(float)下面给出的示例数据
Time
Tag
Value
2022-01-24 00:00:00
1001
12
2022-01-24 00:00:00
1002
50
2022-01-24 00:00:00
1003
24
2022-01-24 01:00:00
1001
0
2022-01-24 02:00:00
1001
34
2022-01-24 02:00:00
1002
45
2022-01-24 02:00:00
1003
10
从上面 table 您可以看出标签 1002 和 1003 缺少时间戳,因为这些标签在 2022-01-24 没有值 01:00:00
但是我想创建一个查询来为没有空值的标签填充我缺少的时间戳
输出 table 应该是这样的
Time
Tag
Value
2022-01-24 00:00:00
1001
12
2022-01-24 00:00:00
1002
50
2022-01-24 00:00:00
1003
24
2022-01-24 01:00:00
1001
0
2022-01-24 01:00:00
1002
null
2022-01-24 01:00:00
1003
null
2022-01-24 02:00:00
1001
34
2022-01-24 02:00:00
1002
45
2022-01-24 02:00:00
1003
10
谁能帮我解决这个问题
提前致谢
您可以首先使用 cross-join 已知值生成完整的预期 data-set,然后将其外连接到现有数据。这是假设您的 SQL 服务器标签是正确的:
with alldates as (
select [time], tag
from (select distinct [time] from data)d
cross join (select distinct tag from data)t
)
select ad.[time], ad.tag, d.[value]
from alldates ad
left join data d on d.[time] = ad.[time] and d.tag = ad.tag
order by ad.[time], ad.tag;
我有 table 称为“数据”。这包含三列Time(datetime),Tag(int),Value(float)下面给出的示例数据
Time | Tag | Value |
---|---|---|
2022-01-24 00:00:00 | 1001 | 12 |
2022-01-24 00:00:00 | 1002 | 50 |
2022-01-24 00:00:00 | 1003 | 24 |
2022-01-24 01:00:00 | 1001 | 0 |
2022-01-24 02:00:00 | 1001 | 34 |
2022-01-24 02:00:00 | 1002 | 45 |
2022-01-24 02:00:00 | 1003 | 10 |
从上面 table 您可以看出标签 1002 和 1003 缺少时间戳,因为这些标签在 2022-01-24 没有值 01:00:00
但是我想创建一个查询来为没有空值的标签填充我缺少的时间戳
输出 table 应该是这样的
Time | Tag | Value |
---|---|---|
2022-01-24 00:00:00 | 1001 | 12 |
2022-01-24 00:00:00 | 1002 | 50 |
2022-01-24 00:00:00 | 1003 | 24 |
2022-01-24 01:00:00 | 1001 | 0 |
2022-01-24 01:00:00 | 1002 | null |
2022-01-24 01:00:00 | 1003 | null |
2022-01-24 02:00:00 | 1001 | 34 |
2022-01-24 02:00:00 | 1002 | 45 |
2022-01-24 02:00:00 | 1003 | 10 |
谁能帮我解决这个问题
提前致谢
您可以首先使用 cross-join 已知值生成完整的预期 data-set,然后将其外连接到现有数据。这是假设您的 SQL 服务器标签是正确的:
with alldates as (
select [time], tag
from (select distinct [time] from data)d
cross join (select distinct tag from data)t
)
select ad.[time], ad.tag, d.[value]
from alldates ad
left join data d on d.[time] = ad.[time] and d.tag = ad.tag
order by ad.[time], ad.tag;