sql server—哪种sql成本更高?为什么?

lztngnrs  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(284)

关闭。这个问题需要更加突出重点。它目前不接受答案。
**想改进这个问题吗?**通过编辑这篇文章更新这个问题,使它只关注一个问题。

9个月前关门了。
改进这个问题

Select DISTINCT Dept,SUM(Salary) OVER (PARTITION BY Dept) from Table

Select Dept, SUM(Salary) FROM Table GROUP BY Dept

以上两个查询产生相同的结果。在我看来,第二个查询的开销更大,因为它使用的是groupby函数,而groupby函数的开销更大。如果ans是正确的,这是正确的解释还是其他的解释?

8cdiaqws

8cdiaqws1#

与任何有关性能的问题一样,最好在系统上测试对数据的查询。索引和表大小等因素可以决定哪个更快。如果你对这样的问题感兴趣,你需要学习执行计划以及如何阅读它们。
也就是说,我希望第一个更昂贵,因为总工资可能是首先计算,然后与每一行对齐。然后删除重复项。
但是优化器可以自由地做它想做的事情,包括为两个查询生成完全相同的执行计划。

pnwntuvh

pnwntuvh2#

你怎么得出结论 group by 功能更昂贵?
如果您使用的是microsoftsqlservermanagementstudio,那么您可以让应用程序告诉您哪个版本更贵。请参见下面屏幕截图中的指导原则。
我的初步调查结果(没有任何数据)表明 group by 对于sql引擎来说,版本不那么密集。

vs91vp4v

vs91vp4v3#

检查计划并测量两个查询的cpu和逻辑io开销。如

use AdventureWorks2017
go
set statistics time on 
set statistics IO on 
go

select JobTitle, sum(SickLeaveHours) SickLeaveHours
from HumanResources.Employee 
group by JobTitle

select distinct JobTitle, sum(SickLeaveHours) over (partition by JobTitle) SickLeaveHours
from HumanResources.Employee

go
set statistics time off
set statistics IO off

第二个查询的计划更复杂,成本更高:
按查询分组

Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, page server reads 0, read-ahead reads 0, page server read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob page server reads 0, lob read-ahead reads 0, lob page server read-ahead reads 0.
Table 'Employee'. Scan count 1, logical reads 9, physical reads 0, page server reads 0, read-ahead reads 0, page server read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob page server reads 0, lob read-ahead reads 0, lob page server read-ahead reads 0.

不同查询

Table 'Worktable'. Scan count 3, logical reads 849, physical reads 0, page server reads 0, read-ahead reads 0, page server read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob page server reads 0, lob read-ahead reads 0, lob page server read-ahead reads 0.
 Table 'Employee'. Scan count 1, logical reads 9, physical reads 0, page server reads 0, read-ahead reads 0, page server read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob page server reads 0, lob read-ahead reads 0, lob page server read-ahead reads 0.

相关问题