日期:2014-05-18  浏览次数:20451 次

求存储过程循环语句,查询几个月内每天的最大值和他的出现时间
小弟我写了个存储过程,查询给定时间段内的最大值和出现时间。但现在要查询几个月内每天的最大值,想用连接,把查询结果,按每天一个字段来显示。
请问高手们,怎么做?

我的查询最大值和出现时间的存储过程
CREATE PROCEDURE GetMaxEx
@Beginning_Date datetime,
@EndDate datetime 
AS
begin

select d.StationName,d.xian,d.height,d.Longitude,d.Latitude, c.* from
(
select
  StationID,
  max_val=max(Temperature),
  time_at_max=min(RsTime)
from 
(select StationID,RsTime,Temperature from zdzRecord where RsTime>= @Beginning_Date and RsTime<@EndDate and Temperature>-9999) a

where a.Temperature=(select max(Temperature) from zdzRecord where RsTime>=@Beginning_Date and RsTime<@EndDate and StationID=a.StationID )

group by StationID 
) c,
StationInfo d 
where c.StationID = d.StationID order by d.xian

end
GO


------解决方案--------------------
SQL code

每天的最大值--convert(varhcar(10),RsTime,120)--显示天作为组
group   by   StationID ,convert(varhcar(10),RsTime,120)

CREATE   PROCEDURE   GetMaxEx 
@Beginning_Date   datetime, 
@EndDate   datetime   
AS 
begin 

select   
d.StationName,d.xian,d.height,d.Longitude,d.Latitude,   
c.*  
 from 
( 
select 
      StationID,
        convert(varhcar(10),RsTime,120) as 天 
        max_val=max(Temperature), 
        time_at_max=min(RsTime) 
from   
(select  
     StationID,
    RsTime,Temperature   
from   zdzRecord     
where   
    RsTime> =   @Beginning_Date     and   RsTime <@EndDate   and   Temperature> -9999)     a 

where   
    a.Temperature=(select   max(Temperature)  
         from   zdzRecord   where  DATEDIFF(RsTime,aRsTime)=0        --条件
     RsTime> =@Beginning_Date     and   RsTime <@EndDate   and   StationID=a.StationID     ) 

group   by   StationID  ,convert(varhcar(10),RsTime,120) --加上
)   c, 
StationInfo   d   
where   c.StationID   =   d.StationID  order   by   d.xian 

end 
GO

------解决方案--------------------
SQL code
SELECT a.* FROM tb a
INNER JOIN
    (SELECT CONVERT(VARCHAR(10),RsTime,120) dd,MAX(Temperature) mp
        FROM tb
            WHERE RsTime >= @Beginning_Date AND RsTime <@EndDate AND Temperature> -9999
            GROUP BY CONVERT(VARCHAR(10),RsTime,120)
    )b
    ON CONVERT(VARCHAR(10),RsTime,120)=dd AND Temperature=mp