SQL Server 聚合性能

发布于 2024-11-17 16:06:01 字数 240 浏览 3 评论 0原文

我想知道如果您在查询中喜欢聚合,或者再次使用聚合,SQL Server 是否知道“缓存”。

例如,

Select Sum(Field),
       Sum(Field) / 12
From   Table

SQL Server 是否知道它已经计算了第一个字段的 Sum 函数,然后将第二个字段除以 12?或者它会再次运行 Sum 函数然后将其除以 12?

谢谢

I am wondering whether SQL Server knows to 'cache' if you like aggregates while in a query, if they are used again.

For example,

Select Sum(Field),
       Sum(Field) / 12
From   Table

Would SQL Server know that it has already calculated the Sum function on the first field and then just divide it by 12 for the second? Or would it run the Sum function again then divide it by 12?

Thanks

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

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

发布评论

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

评论(3

捶死心动 2024-11-24 16:06:01

它计算一次

Select
   Sum(Price),
   Sum(Price) / 12
From
   MyTable

计划给出:

|--Compute Scalar(DEFINE:([Expr1004]=[Expr1003]/(12.)))
  |--Compute Scalar(DEFINE:([Expr1003]=CASE WHEN [Expr1010]=(0) THEN NULL ELSE [Expr1011] END))
     |--Stream Aggregate(DEFINE:([Expr1010]=Count(*), [Expr1011]=SUM([myDB].[dbo].[MyTable].[Price])))
        |--Index Scan(OBJECT:([myDB].[dbo].[MyTable].[IX_SomeThing]))

该表有 135 万行

It calculates once

Select
   Sum(Price),
   Sum(Price) / 12
From
   MyTable

The plan gives:

|--Compute Scalar(DEFINE:([Expr1004]=[Expr1003]/(12.)))
  |--Compute Scalar(DEFINE:([Expr1003]=CASE WHEN [Expr1010]=(0) THEN NULL ELSE [Expr1011] END))
     |--Stream Aggregate(DEFINE:([Expr1010]=Count(*), [Expr1011]=SUM([myDB].[dbo].[MyTable].[Price])))
        |--Index Scan(OBJECT:([myDB].[dbo].[MyTable].[IX_SomeThing]))

This table has 1.35 million rows

冰火雁神 2024-11-24 16:06:01

根据执行计划,它不会重新对列求和。

According to the execution plan, it doesn't re-sum the column.

朦胧时间 2024-11-24 16:06:01

好问题,我认为答案是否定的,它不会缓存它。

我运行了一个包含大约 3000 个计数的测试查询,它比只有几个计数的查询要慢得多。仍然想测试查询是否会像选择普通列一样慢

编辑:好的,我只是尝试选择大量列或仅选择一个列,并且列的数量(当谈论返回数千列时)确实会影响速度。

总的来说,除非您在查询中多次使用该总数,否则应该没问题。到了紧要关头,您始终可以将结果保存到变量中并在事后进行数学计算。

good question, i think the answer is no, it doesn't not cache it.

I ran a test query with around 3000 counts in it, and it was much slower than one with only a few. Still want to test if the query would be just as slow selecting just plain columns

edit: OK, i just tried selecting a large amount of columns or just one, and the amount of columns (when talking about thousands being returned) does effect the speed.

Overall, unless you are using that aggregate number a ton of times in your query, you should be fine. Push comes to shove, you could always save the outcome to a variable and do the math after the fact.

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