这个Sql怎样写才高效???急急急!!!100分奉上(100分)

  • 主题发起人 微湖水生
  • 开始时间

微湖水生

Unregistered / Unconfirmed
GUEST, unregistred user!
问题是这样的:我那有两个表,一个是灌溉站表T1(F_StaCode(站编号),
F_PreWeirCode(前一测量站编号),F_NextWeirCode(前一测量站编号)),一个是
测量站测量值表T2(F_WeirCode(测量站编号),F_Time(测量时间),F_Value(测量值));
现在要求出某年个灌溉站的总耗用值(即上下两测量站值之差)。
另注:测量站每5分钟一次数据;如果灌溉站位于水渠最后则没有下一个测量。
我是这样写的:
select T1.F_StaCode,
case
when F_NextWeirCode='' then (Sum(L1.F_Value)-Sum(L2.F_Value))
else Sum(L1.F_Value)
end as ValueUse
from T1 join T2 as L1 on T1.F_PreWeirCode=L1.F_WeirCode
and DATEPART(yy,L1.F_Time)='2002'
left join T2 as L2 on T_1.F_NextWeirCode=L2.F_WeirCode
and DATEPART(yy,L2.F_Time)='2002'
Group By T1.F_StaCode,F_NextWeirCode

库中有11个灌溉站,只有各测试站一天的数据,而该查询语句用时30S;请各位
富翁看看,有何高招??
 
select 测试站编号,
(select sum(测量值)
from T2
where 测量站编号=AAA.前一测量站编号 and DATEPART(yy,测试时间)='2002')-
isnull((select sum(测量值)
from T2
where 测量站编号=AAA.下一测量站编号 and DATEPART(yy,测试时间)='2002'),0)
from T1 AAA
order by 测试站编号

没测试过,出错莫怪,呵
 
你用下面的试一下:
select T1.F_StaCode,Sum(IsNULL(L1.F_Value,0))-Sum(IsNULL(L2.F_Value,0)) as ValueUse
from T1
left outer join T2 as L1on L1.F_WeirCode=T1.F_PreWeirCode and year(L1.F_Time)=2002
left outer join T2 as L2 on L2.F_WeirCode=T1.F_NextWeirCode and year(L2.F_Time)=2002
Group by T1.F_StaCode
如果效率没有提高的话,在改用如下的写法
select T1.F_StaCode,IsNULL(L1.F_Value,0)-IsNULL(L2.F_Value,0) as ValueUse
from T1
left outer join
(
select F_WeirCode,sum(F_Value) as F_Value
from T2
where Year(F_Time)=2002
Group by FWeirCode
) as L1 on L1.F_WeirCode=T1.F_PreWeirCode
left outer join
(
select F_WeirCode,sum(F_Value) as F_Value
from T2
where Year(F_Time)=2002
Group by FWeirCode
) as L2 on L2.F_WeirCode=T1.F_NextWeirCode
多表关联时,多用group by 把每一个子表变小,整体的速度就会提高。
 
QuickSilver兄的办法是对的,而且比我做的要快的多;不过,结果不一样,能不能说说
我的办法有什么问题??谢!
 
jin_sue兄的第一个方法和我的没什么区别,效率不理想,也需要28秒左右;
不过第二个方法很好,仅1秒多;并且谢谢jin_sue兄有益的提示!
 
我现在不考虑你最后一下站的情况,其实你可以将最后一站的下一个测量
设置为一个不存在的编号,因为空格可能和什么都匹配。如果以下语句对
最后一个不正确,这么改一下就行了:

select T1.F_StaCode,
((select sum(F_Value) from t2 where t2.F_WeirCode=T1.F_PreWeirCode)-
(select sum(F_Value) from t2 where t2.F_WeirCode=T1.F_NextWeirCode))
as valueUse
from T1
 
忘了加 DATEPART(yy,L1.F_Time)='2002'
你自己补充一下。
 
谢谢各位!!!
 
顶部