当前位置: 代码网 > it编程>数据库>MsSqlserver > 解锁 SQL Server 2022的时间序列数据功能(示例详解)

解锁 SQL Server 2022的时间序列数据功能(示例详解)

2024年08月03日 MsSqlserver 我要评论
sql server2022在处理时间序列数据时,sql server 提供了一些优化和功能,比如 date_bucket 函数、窗口函数(如 first_value 和 last_value)以及其

sql server2022在处理时间序列数据时,sql server 提供了一些优化和功能,比如 date_bucket 函数、窗口函数(如 first_value 和 last_value)以及其他时间日期函数,以便更高效地处理时间序列数据。

 generate_series函数

sql server 2022 引入了一个新的函数 generate_series,它用于生成一个整数序列。
这个函数非常有用,可以在查询中生成一系列连续的数值,而无需创建临时表或循环。

generate_series ( start, stop [, step ] )
start:序列的起始值。
stop:序列的终止值。
step:每次递增或递减的步长(可选)。如果省略,默认为1。

 使用场景包括快速生成一系列数据用于测试或填充表或者结合日期函数生成一系列日期值。

示例

生成的结果集将包含 20 行,每行显示从 '2019-02-28 13:45:23' 开始,按分钟递增的时间。

select dateadd(minute, s.value, '2019-02-28 13:45:23') as [interval]
from generate_series(0, 20, 1) as s;

对于每一个 s.value,dateadd 函数将基准日期时间增加相应的分钟数。

date_bucket函数

sql server 2022 引入了一个新的函数 date_bucket,用于将日期时间值按指定的时间间隔分组(即分桶)。

这个函数在时间序列分析、数据聚合和分段分析等场景中非常有用。

date_bucket ( bucket_width, datepart, startdate, date )
bucket_width:时间间隔的大小,可以是整数。
datepart:时间间隔的类型,例如 year, month, day, hour, minute, second 等。
startdate:起始日期,用于定义时间间隔的起点。
date:需要分组的日期时间值。

使用 date_bucket 函数时,指定的时间间隔单位(如 year、quarter、month、week 等)以及起始日期(origin)决定了日期时间值被分配到哪个存储桶。这种方式有助于理解时间间隔的计算是如何基于起始日期来进行的。

示例

declare @date datetime = '2019-09-28 13:45:23';
declare @origin datetime = '2019-01-28 13:45:23';
select 'now' as [bucketname], @date as [datebucketvalue]
union all
select 'year', date_bucket (year, 1, @date, @origin)
union all
select 'quarter', date_bucket (quarter, 1, @date, @origin)
union all
select 'month', date_bucket (month, 1, @date, @origin)
union all
select 'week', date_bucket (week, 1, @date, @origin)
--假如日期时间值如下:
now: 2019-09-28 13:45:23
--按年分组:
date_bucket(year, 1, @date, @origin)
从 2019-01-28 13:45:23 开始的年度存储桶,2019-09-28 落入 2019-01-28 至 2020-01-28 的存储桶中。
结果:2019-01-28 13:45:23
--按季度分组:
date_bucket(quarter, 1, @date, @origin)
从 2019-01-28 13:45:23 开始的季度存储桶,每个季度 3 个月。
2019-09-28 落入第三个季度存储桶(即从 2019-07-28 13:45:23 到 2019-10-28 13:45:23)。
结果:2019-07-28 13:45:23
--按月分组:
date_bucket(month, 1, @date, @origin)
从 2019-01-28 13:45:23 开始的月度存储桶,每个月一个存储桶。
2019-09-28 落入第九个存储桶(即从 2019-09-28 13:45:23 到 2019-10-28 13:45:23)。
结果:2019-09-28 13:45:23
--按周分组:
date_bucket(week, 1, @date, @origin)
从 2019-01-28 13:45:23 开始的每周存储桶。
2019-09-28 落入从 2019-09-23 13:45:23 到 2019-09-30 13:45:23 的存储桶。
结果:2019-09-23 13:45:23

select 'now' as [bucketname], getdate() as [bucketdate]
union all
select '5 minute buckets', date_bucket (minute, 5, getdate())
union all
select 'quarter hour', date_bucket (minute, 15, getdate());
now:
bucketname: now
bucketdate: 2024-07-26 16:14:11.030
这是当前时间,即 getdate() 返回的系统当前时间。
5 minute buckets:
bucketname: 5 minute buckets
bucketdate: 2024-07-26 16:10:00.000
这是将当前时间按 5 分钟间隔进行分组的结果。date_bucket(minute, 5, getdate()) 返回当前时间所在的 5 分钟区间的起始时间。在这个例子中,16:14:11 落在 16:10:00 到 16:15:00 之间,因此返回 16:10:00。
quarter hour:
bucketname: quarter hour
bucketdate: 2024-07-26 16:00:00.000
这是将当前时间按 15 分钟间隔进行分组的结果。date_bucket(minute, 15, getdate()) 返回当前时间所在的 15 分钟区间的起始时间。在这个例子中,16:14:11 落在 16:00:00 到 16:15:00 之间,因此返回 16:00:00。

更多实际场景示例

按自定义起始日期分组
假设我们有一系列事件时间 eventtime,希望从'2023-01-01'日期开始,每周进行分组统计事件数量。

--创建表 events:
use [testdb]
go
create table events (
    eventid int primary key,
    eventtime datetime
);
insert into events (eventid, eventtime) values
(1, '2023-01-02 14:30:00'),
(2, '2023-01-08 09:15:00'),
(3, '2023-01-09 17:45:00'),
(4, '2023-01-15 12:00:00'),
(5, '2023-01-16 08:00:00'),
(6, '2023-01-22 19:30:00'),
(7, '2023-01-29 11:00:00');
--从'2023-01-01'起始日期开始,每周进行分组统计事件数量。
declare @origin datetime = '2023-01-01';
select
    date_bucket(week, 1, eventtime, @origin) as weekstart,
    count(*) as eventcount
from
    events
group by
    date_bucket(week, 1, eventtime, @origin)
order by
    weekstart;

按自定义时间间隔分组
假设我们有一个传感器数据表 sensorreadings

use [testdb]
go
create table sensorreadings (
    readingid int primary key,  --唯一标识
    readingtime datetime,  --读数的时间
    value float  --读数的值
);
insert into sensorreadings (readingid, readingtime, value) values
(1, '2023-07-26 10:03:00', 23.5),
(2, '2023-07-26 10:05:00', 24.1),
(3, '2023-07-26 10:09:00', 22.8),
(4, '2023-07-26 10:15:00', 25.0),
(5, '2023-07-26 10:20:00', 23.9),
(6, '2023-07-26 10:27:00', 24.3),
(7, '2023-07-26 10:29:00', 24.5);
--我们希望按 10 分钟的间隔将数据分组,并计算每个间隔的平均读数值。
select
    date_bucket(minute, 10, readingtime) as bucketstarttime,
    round(avg(value),4) as averagevalue
from
    sensorreadings
group by
    date_bucket(minute, 10, readingtime)
order by
    bucketstarttime;

如果是传统方法需要使用公用表表达式cte才能完成这个需求

--查询:按 10 分钟间隔分组并计算平均值
with timeintervals as (
    select
        readingid,
        readingtime,
        value,
        --将分钟数归约到最近的 10 分钟的整数倍, 从2010年到现在有多少个10分钟区间
        dateadd(minute, (datediff(minute, '2000-01-01', readingtime) / 10) * 10, '2010-01-01') as bucketstarttime  
    from
        sensorreadings
)
select
    bucketstarttime,
    round(avg(value), 4) as averagevalue
from
    timeintervals
group by
    bucketstarttime
order by
    bucketstarttime;

with timeintervals as (...)公共表表达式(cte)用于计算每条记录的 bucketstarttime。
datediff(minute, '2000-01-01', readingtime) / 10 计算 readingtime 到基准时间 '2000-01-01' 的分钟数,然后除以 10,得到当前时间点所在的 10 分钟区间的索引。
dateadd(minute, ..., '2000-01-01') 将该索引转换回具体的时间点,即区间的起始时间。

查询主部分:
选择 bucketstarttime 和相应区间内读数值的平均值。
使用 group by 按 bucketstarttime 分组,并计算每个分组的平均值。
order by 用于按照时间顺序排列结果。

first_value 和 last_value 窗口函数

在 之前版本的sql server 中,first_value 和 last_value 是窗口函数,用于在一个分区或窗口中返回第一个或最后一个值。

sql server 2022 引入了新的选项 ignore nulls 和 respect nulls 来处理空值(null)的方式,从而增强了这些函数的功能。

基本语法

first_value
返回指定窗口或分区中按指定顺序的第一个值。
first_value ( [scalar_expression ] ) 
over ( [ partition_by_clause ] order_by_clause [ rows_range_clause ] )
last_value
返回指定窗口或分区中按指定顺序的最后一个值。
last_value ( [scalar_expression ] ) 
over ( [ partition_by_clause ] order_by_clause [ rows_range_clause ] )
新功能:ignore nulls 和 respect nulls
ignore nulls: 忽略分区或窗口中的 null 值。
respect nulls: 默认行为,包含分区或窗口中的 null 值。

示例

假设我们有一个表 machinetelemetry,包含以下数据:

create table machinetelemetry (
    [timestamp] datetime,
    sensorreading float
);
insert into machinetelemetry ([timestamp], sensorreading) values
('2023-07-26 10:00:00', 23.5),
('2023-07-26 10:00:15', 24.1),
('2023-07-26 10:00:30', null),
('2023-07-26 10:00:45', 25.0),
('2023-07-26 10:01:00', null),
('2023-07-26 10:01:15', 23.9),
('2023-07-26 10:01:30', null),
('2023-07-26 10:01:45', 24.3);

默认行为(包含 null 值)

--使用 first_value 和 last_value 进行差距分析
--默认行为(包含 null 值)
select 
    [timestamp],
    date_bucket(minute, 1, [timestamp]) as [timestamp_bucket],
    sensorreading,
    first_value(sensorreading) over (
        partition by date_bucket(minute, 1, [timestamp]) 
        order by [timestamp] 
        rows between unbounded preceding and unbounded following
    ) as [default_first_value (respect nulls)],
    last_value(sensorreading) over (
        partition by date_bucket(minute, 1, [timestamp]) 
        order by [timestamp] 
        rows between unbounded preceding and unbounded following
    ) as [default_last_value (respect nulls)]
from machinetelemetry
order by [timestamp];

忽略 null 值

--忽略 null 值
select 
    [timestamp],
    date_bucket(minute, 1, [timestamp]) as [timestamp_bucket],
    sensorreading,
    first_value(sensorreading) ignore nulls over (
        partition by date_bucket(minute, 1, [timestamp]) 
        order by [timestamp] 
        rows between unbounded preceding and unbounded following
    ) as [first_reading (ignore nulls)],
    last_value(sensorreading) ignore nulls over (
        partition by date_bucket(minute, 1, [timestamp]) 
        order by [timestamp] 
        rows between unbounded preceding and unbounded following
    ) as [last_reading (ignore nulls)]
from machinetelemetry
order by [timestamp];

 总结

实际上,对于时间序列我们一般使用专业的时间序列数据库,例如influxdb 。

它使用 tsm(time-structured merge tree)作为存储引擎称,这是 lsm 树的一种变体,专门优化用于时间序列数据的写入和查询性能。

另外,sql server 的时间序列功能是使用行存储引擎(row store)作为其存储引擎,这意味着数据是按行进行存储和处理的。

在大部分场景下面,如果性能不是要求非常高,其实sql server 存储时间序列数据性能是完全足够的,而且额外使用influxdb数据库需要维护多一个技术栈,对运维要求更加高。

特别是现在追求数据库一体化的趋势背景下,无论是时间序列数据,向量数据,地理数据,json数据都最好在一个数据库里全部满足,减轻运维负担,复用技术栈,减少重复建设成本是比较好的解决方案。

参考文章

https://sqlbits.com/sessions/event2024/time_series_with_sql_server_2022

https://www.microsoft.com/en-us/sql-server/blog/2023/01/12/working-with-time-series-data-in-sql-server-2022-and-azure-sql/

https://www.mssqltips.com/sqlservertip/6232/load-time-series-data-with-sql-server/

到此这篇关于解锁 sql server 2022的时间序列数据功能的文章就介绍到这了,更多相关sql server 2022时间序列数据内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com