SQL 按时间段分组计算 SPT_VALUES 使用

通过网上查资料,今天有学习了一招。

按时间段分组计算

 

功能要求:

检测数据要求统计出整点数据例如:

2011-12-07 01

2011-12-07 02

2011-12-07 03

...

2011-12-07 24

 检测数据的和或者平均值

 

写的存储过程如下:

CREATE PROCEDURE [dbo].[Test]
@stationCode NVARCHAR(24),
@ObservationDate DATETIME
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.


SET NOCOUNT ON;
--检测数据量很大,将结果集保存到临时表#temp
SELECT ObservationDatetime,RainfallPerMinute, Temperature, BatteryVoltage
INTO #temp FROM View_rainfall WHERE StationCode=@stationCode and DATEDIFF(day,ObservationDatetime,@ObservationDate) = 0

SELECT b.EndDate AS ObservationDate,
ISNULL(SUM(a.RainfallPerMinute),0) AS Rainfall,

ISNULL(AVG(a.Temperature),0) AS Temperature,
ISNULL(MIN(a.BatteryVoltage),'0') AS BatteryVoltage
FROM #temp a RIGHT JOIN
(

--日期列表,此招为以前不知道的最新学会的。
SELECT
DATEADD(HOUR,NUMBER,@ObservationDate) AS BeginDate,
DATEADD(HOUR,NUMBER+1,@ObservationDate) AS EndDate
FROM MASTER..SPT_VALUES WHERE TYPE='P'AND NUMBER between 0 and 23
) b
 ON a.ObservationDateTime between b.BeginDate and b.EndDate --此招为以前不知道的最新学会的以前只知道通过主键外联真是DBA也不是白给的,改变自己无知的思想任何人都有长处 
GROUP BY b.BeginDate, b.EndDate

END

你可能感兴趣的:(数据库)