rah*_*rma 3 sql sqlperformance sql-server-2008-r2
我必须在where子句的基础上总结一些列,以便更好地理解我在这里实现一个临时表
declare @tbl table(a int ,b int,c int)
insert into @tbl values(1,2,3)
insert into @tbl values(2,2,3)
insert into @tbl values(1,3,1)
insert into @tbl values(1,2,3)
insert into @tbl values(1,2,3)
Run Code Online (Sandbox Code Playgroud)
并且用于找出a,b,c ob的总和a,b,c的值; 我正在使用以下查询
SELECT (
SELECT SUM(a) from @tbl where a=1
)AS a ,
(SELECT SUM(b) from @tbl where b=2
)AS b ,
(SELECT SUM(c) from @tbl where c=3
)AS c
Run Code Online (Sandbox Code Playgroud)
我问我的一个朋友对这项工作进行单行查询,他建议我按行
select sum((case when a=1 then a else null end)),
sum((case when b=2 then b else null end)),
sum((case when c=3 then c else null end))
from @tbl
Run Code Online (Sandbox Code Playgroud)
现在我正在考虑性能,如果我有27列和数百万条记录,这将更快地工作?
或任何其他方法来实现这一点,这将比这两个更好地改善性能
扩展Martin的答案 - 这取决于你拥有的索引以及列的填充程度(可以为空).考虑这个例子.
create table tbl (id int identity primary key, a int ,b int,c int, d int)
insert tbl values(1,2,3,null)
insert tbl values(2,null,3,1)
insert tbl values(1,null,1,4)
insert tbl values(1,null,3,5)
insert tbl values(1,null,3,6)
insert tbl select a,b,c,d from tbl --10
insert tbl select a,b,c,d from tbl --20
insert tbl select a,b,c,d from tbl --40
insert tbl select a,b,c,d from tbl --80
insert tbl select a,b,c,d from tbl --160
insert tbl select a,b,c,d from tbl --320
insert tbl select a,b,c,d from tbl --640
insert tbl select a,b,c,d from tbl --1280
insert tbl select a,b,c,d from tbl --2560
insert tbl select a,b,c,d from tbl --5120
insert tbl select a,b,c,d from tbl --10240
Run Code Online (Sandbox Code Playgroud)
列b创建为可空,只有20%非空.现在,对表运行查询(没有索引).在运行之前,请确保按Ctrl-M(显示实际执行计划).在同一批次中运行两个查询,即突出显示两个查询的文本并执行.
SELECT (SELECT SUM(a) from tbl where a=1) AS a ,
(SELECT SUM(b) from tbl where b=2) AS b ,
(SELECT SUM(c) from tbl where c=3) AS c
select sum((case when a=1 then a else null end)),
sum((case when b=2 then b else null end)),
sum((case when c=3 then c else null end))
from tbl
Run Code Online (Sandbox Code Playgroud)
我不会在这里给你带来图片,但是看看这个计划会显示出与最高查询相比约75%的成本和25%的最低查询成本.这是预期的,75%:25%= 3:1,这是由于第一次查询完全通过表3次.现在创建这三个索引:
create index ix_tbl_a on tbl(a)
create index ix_tbl_b on tbl(b)
create index ix_tbl_c on tbl(c)
Run Code Online (Sandbox Code Playgroud)
然后,重新运行查询批处理(两者一起).这一次,您将看到约51%至49%的成本.相当接近.原因是因为只有索引页面才能(b)很容易地填充稀疏列SUM.通过检索每个索引页面的行数比数据页面上的聚簇索引(包含所有列)更多的行来帮助其他2列.
当您将其扩展为27列时,如果每个列都是稀疏填充的,并且如果每个列都有一个索引,则第一个表单可以运行得更快.一个很大的问题,即便如此,它可能只会非常快.
| 归档时间: |
|
| 查看次数: |
3110 次 |
| 最近记录: |