日期:2014-05-16 浏览次数:20770 次
IF EXISTS(SELECT name FROM sys.objects WHERE name = 'test')
DROP TABLE test
go
CREATE TABLE test
(
dt DATETIME ,
num DECIMAL(6,4)
)
GO
INSERT INTO test (dt , num)
SELECT '2001-08-21 00:00:00.000' , 1.529 UNION ALL
SELECT '2001-08-21 01:00:00.000' , 1.524 UNION ALL
SELECT '2001-08-21 02:00:00.000' , 1.522 UNION ALL
SELECT '2001-08-21 03:00:00.000' , 1.52 UNION ALL
SELECT '2001-08-21 04:00:00.000' , 1.522 UNION ALL
SELECT '2001-08-21 05:00:00.000' , 1.526 UNION ALL
SELECT '2001-08-21 06:00:00.000' , 1.532 UNION ALL
SELECT '2001-08-21 07:00:00.000' , 1.536 UNION ALL
SELECT '2001-08-21 08:00:00.000' , 1.539 UNION ALL
SELECT '2001-08-21 09:00:00.000' , 1.541 UNION ALL
SELECT '2001-08-21 10:00:00.000' , 1.539 UNION ALL
SELECT '2001-08-21 11:00:00.000' , 1.536 UNION ALL
SELECT '2001-08-21 12:00:00.000' , 1.533 UNION ALL
SELECT '2001-08-21 13:00:00.000' , 1.529 UNION ALL
SELECT '2001-08-21 14:00:00.000' , 1.526
---------------------------------執行查詢----------------------
;WITH a AS(
SELECT CONVERT(DATE , dt) AS yyyymmdd , DATEPART(HOUR , dt)/6 AS t ,num
FROM test)
SELECT yyyymmdd , t , AVG(num) AS avg_num
FROM a
GROUP BY yyyymmdd , t
/*
yyyymmdd t avg_num
---------- ----------- ---------------------------------------
2001-08-21 0 1.523833
2001-08-21 1 1.537166
2001-08-21 2 1.529333
(3 row(s) affected)
*/