简化SQL查询

时间:2014-04-09 07:27:13

标签: sql sql-server

想知道是否有更好的方法来获取这些信息?

while (t0 < t1 ) do

    tag1Val=(select avg from aggregates where name= tag1 and ts between t0-03:00 and t0 and period=01:00);
    tag2Val=(select avg from aggregates where name=tag2 and ts between t0-03:00 and t0 and period=01:00);
    tagRes = ((1000*tag1Val)/tag2Val);
    if tagRes not like '' then
        insert into module.ddtemp(ts,value) values (t0, tagRes);
    end;
    t0 = t0+03:00;
end;

1 个答案:

答案 0 :(得分:1)

select avg 
from aggregates,
     (select t0 as period
      union all
      select t0+03:00  as period
      union all
      select t0+06:00  as period
...
      union all
      select t1 as period) periods 
where name=tag2 
  and ts between periods.period -03:00  and periods.period
  and period=01:00

您可以传递子查询中的所有句点并仅提取一次结果。

如果有很多间隔,会很慢。

您可以提取所有

select avg 
from aggregates 
where name= tag1 and ts between t0-03:00 and t1 and period=01:00

并浏览每个间隔的结果提取数据