我只是SQL Server的初学者。我很少关注使用循环或临时表之间的性能差异。有没有简单的方法
(x+y ) + (x+y ) + (x+y ) / sum(x)
在单个查询中。
这就是我所做的
select cast(datetime as date) as date,DATEPART(hour,datetime) as hour,sum(product) as Total
from temp_aggregated_speed
group by cast(datetime as date), DATEPART(hour,datetime)
order by cast(datetime as date),DATEPART(hour,datetime);
会将其存储在变量和进程中(在那里再查询一次以查找x的总和)。有没有办法在单个查询中执行此操作?
答案 0 :(得分:0)
使用一些基本代数简化您的等式通常会提高性能,同时也会使您的设计变得更简单。您的示例等式可以重写如下:
( (x+y) + (x+y) + (x+y)...) / sum(x)
= ( sum(x+y) ) / sum(x)
= ( sum(x) + sum(y) ) / sum(x)
= sum(x)/sum(x) + sum(y)/sum(x)
= 1 + sum(y)/sum(x)
如果X和Y在同一个表中,则SQL查询就这么简单:
select blah, 1 + sum(y)/sum(x) as FinalAnswer
from thetable
group by blah
确保您的数据类型兼容,您可能需要进行一些类型转换才能使数学部分按照您想要的方式运行。例如:
select blah, cast(1.0 as float) + sum(cast(y as float))/sum(cast(x as float)) as FinalAnswer
from thetable
group by blah