Tuesday, March 27, 2012

Getting the average results based on time.

Hello~,
The table has columns like this.
__
time smalldatetime
value1 int
value2 int
-

for example,
....
'2006-11-16 12:00:00',100,200
'2006-11-16 13:00:00',110,210
'2006-11-16 14:00:00',120,220
....

The record is inserted at every hour.

I want get daily,monthly,yearly average and display the result ordered by time.


SELECT CONVERT(CHAR(8),time,112) as [Day],
AVG(value1) AS value1,
AVG(value2) AS value2
FROM MyTable
GROUP BY CONVERT(CHAR(8),time,112)
ORDER BY 1

SELECT CONVERT(CHAR(6),time,112) as [Month],
AVG(value1) AS value1,
AVG(value2) AS value2
FROM MyTable
GROUP BY CONVERT(CHAR(6),time,112)
ORDER BY 1

SELECT CONVERT(CHAR(4),time,112) as [Year],
AVG(value1) AS value1,
AVG(value2) AS value2
FROM MyTable
GROUP BY CONVERT(CHAR(4),time,112)
ORDER BY 1

sql

No comments:

Post a Comment