如何替换 TSQL 游标和标量函数

发布于 2024-12-29 08:31:51 字数 496 浏览 3 评论 0原文

我有一个对时态数据运行模拟的应用程序。计算并不过分复杂,但计算需要在同一模拟中预先预测时间数据。

我们假设使用 1 周的数据进行模拟,数据点间隔为 15 分钟。预测值的简化计算如下:

PredictedValue = A + B + C + D

为了获得 B、C 和 D 的值,模拟需要先前计算的 t0、t-1、t-95、t-96、t-672 和 t- 的数据。 673.这是当前和先前间隔、前一天的当前和先前间隔以及上周的当前和先前间隔的时间数据。

我有一个可以模拟任何时间段数据的有效实现,但是对于大型数据集,性能非常差。

该实现使用 TSQL 游标来循环模拟下的时态数据,并使用标量函数来检索先前计算的数据。

基本上,数据集越大,模拟运行速度越慢。例如,使用 1 天的数据进行模拟需要 <1 天。 1分钟;一个月数据的模拟需要 2-3 天。

我真的很感兴趣如何在不使用游标或标量函数的情况下提高 TSQL 代码的性能。

I have an application that runs a simulation on temporal data. The calculations are are not overly complicated however the calculation requires previously predicted temporal data in the same simulation.

Let's assume a simulation using 1 week of data with data points at 15 minute interval. The simplified calculation for a predicted value is as follows:

PredictedValue = A + B + C + D

To get the values of B, C, and D, the simulation requires previously calculated data at t0, t-1, t-95, t-96, t-672 and t-673. This is the temporal data for the current and previous interval, previous day's current and previous interval and the previous week's current and previous interval.

I have a working implementation that simulate data over any time period however performance is extremely poor with large datasets.

The implementation uses a TSQL cursor to loop over the temporal data under simulation and scalar function to retrieve the previously calculated data.

Basically the larger the dataset the slower the simulation runs. For example, a simulation using 1 day of data takes < 1 minute; a simulation with a month of data takes 2-3 days.

I'm really interested in how I can improve the performance of the TSQL code without using a cursor or the scalar functions.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苦妄 2025-01-05 08:31:51

在这种情况下,我建议使用自连接。然后,SQL Server 能够将您的查询作为一个集合来处理,从而显着提高速度。

简化的示例,假设该表有两列(日期、值)并称为数据

SELECT (A.value + B.value) as Prediction
FROM [Data] A left join [Data] B
ON B.date = dateadd(day,-1, A.date)

(未经测试完成,因此可能包含拼写错误 - 但我希望您明白)。

祝你好运,奥托。

In this case I would suggest using a self-join. SQL server is then able to process your query as a set giving a tremendous speed increase.

Simplified example, assuming the table has two columns (date, value) and is called Data

SELECT (A.value + B.value) as Prediction
FROM [Data] A left join [Data] B
ON B.date = dateadd(day,-1, A.date)

(done without testing so may contain typo's - but I hope you get the picture).

Good luck, Otto.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文