SQL语句多层嵌套查询很慢,怎么优化,求方案 10
/******ScriptforSelectTopNRowscommandfromSSMS******/selectStationDetail.StationName,S...
/****** Script for SelectTopNRows command from SSMS ******/
select StationDetail.StationName,StationDetail.Longitude, StationDetail.Latitude, c.Rainfall
from [JD_Data].[dbo].StationDetail,
(select a.StationNum as StationNum,(a.Rainfall-b.Rainfall) as Rainfall
from
(SELECT AutoStationData.StationNum ,sum(cast(AutoStationData.Rainfall as float)) as Rainfall
FROM [JD_Data].[dbo].AutoStationData
where (AutoStationData.DateTime between '2015/8/24 7:09:00' and '2015/8/24 9:09:00' and datepart(MINUTE,DateTime)=0)
or (AutoStationData.DateTime = '2015/8/24 9:09:00')
and AutoStationData.Rainfall<>'NULL' group by AutoStationData.StationNum) as a ,
(SELECT AutoStationData.StationNum,sum(cast(AutoStationData.Rainfall as float)) as Rainfall
FROM [JD_Data].[dbo].AutoStationData where AutoStationData.DateTime = '2015/8/24 7:09:00' and AutoStationData.Rainfall<>'NULL'
group by AutoStationData.StationNum) as b
where a.StationNum=b.StationNum) as c
where c.StationNum=StationDetail.StationNum
这是语句,查询一下要一分多钟,时间太长了,里面的嵌套写的不是很好,求大神给优化 展开
select StationDetail.StationName,StationDetail.Longitude, StationDetail.Latitude, c.Rainfall
from [JD_Data].[dbo].StationDetail,
(select a.StationNum as StationNum,(a.Rainfall-b.Rainfall) as Rainfall
from
(SELECT AutoStationData.StationNum ,sum(cast(AutoStationData.Rainfall as float)) as Rainfall
FROM [JD_Data].[dbo].AutoStationData
where (AutoStationData.DateTime between '2015/8/24 7:09:00' and '2015/8/24 9:09:00' and datepart(MINUTE,DateTime)=0)
or (AutoStationData.DateTime = '2015/8/24 9:09:00')
and AutoStationData.Rainfall<>'NULL' group by AutoStationData.StationNum) as a ,
(SELECT AutoStationData.StationNum,sum(cast(AutoStationData.Rainfall as float)) as Rainfall
FROM [JD_Data].[dbo].AutoStationData where AutoStationData.DateTime = '2015/8/24 7:09:00' and AutoStationData.Rainfall<>'NULL'
group by AutoStationData.StationNum) as b
where a.StationNum=b.StationNum) as c
where c.StationNum=StationDetail.StationNum
这是语句,查询一下要一分多钟,时间太长了,里面的嵌套写的不是很好,求大神给优化 展开
1个回答
展开全部
大致的看了下,有点晕,内嵌的几个select只是对同一个表的部分不同条件进行分组计算,没必要写两个查询,其中还嵌套一个,我也是醉了,可以用case-when去解决这个问题。
更多追问追答
追问
casewhen怎么用呀,求示例
追答
比如 字段大于10的值加1,小于10的减一,
select
* ,
case when 字段值>10 then 字段值+1 else 字段值-1 end as 自定义列名
from tablename
你那边好像是同一个表不同条件,不同计算(有两列),可以这么写
select *,
case when 条件1 then sum(此处计算和) else 0 end as condition1,
case when 条件2 then sum(此处计算和) else 0 end as condition2
from tablename
大致就是这么写的,自己研究些,能学的更多,别人讲的太明白话学的反而少。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询