I\'m trying to average data in SQL Server 2005 in a day. Here is what my database look like this if I use simple query as
SELECT timestamp, FEED
FROM ROASTE
@marc_s hit upon the preferred solution of using a computed columns to handle this but to do it on-the-fly, cast your timestamp data to shear off the time component. In my example, I cast it to a 10 character field that contains the 0 padded date.
;
WITH ROASTER_FEED ([timestamp],[Feed]) AS
(
SELECT CAST('02/07/2011 12:00:01' AS datetime),1246
UNION ALL SELECT '02/07/2011 12:00:01',1234
UNION ALL SELECT '02/07/2011 12:00:01',1387
UNION ALL SELECT '02/07/2011 12:00:02',1425
UNION ALL SELECT '02/07/2011 12:00:03',1263
UNION ALL SELECT '02/07/2011 11:00:01',1153
UNION ALL SELECT '02/07/2011 11:00:01',1348
UNION ALL SELECT '02/07/2011 11:00:01',1387
UNION ALL SELECT '02/07/2011 11:00:02',1425
UNION ALL SELECT '02/07/2011 11:00:03',1223
UNION ALL SELECT '03/07/2011 12:00:01',1226
UNION ALL SELECT '03/07/2011 12:00:01',1245
UNION ALL SELECT '03/07/2011 12:00:01',1384
UNION ALL SELECT '03/07/2011 12:00:02',1225
UNION ALL SELECT '03/07/2011 12:00:03',1363
)
SELECT
-- Shear off the time value by forcing the date into date values
-- If this was SQL Server 2008+, we'd just cast to date type and
-- be done with it
-- Chart for convert options
-- http://msdn.microsoft.com/en-us/library/ms187928.aspx
CONVERT(char(10), RF.[timestamp], 121) AS [timestamp]
, COUNT(1) AS row_counts
, SUM(RF.Feed) as ValuesSum
, AVG(RF.Feed) as Average
FROM
ROASTER_FEED RF
GROUP BY
CONVERT(char(10), RF.[timestamp], 121)
Results in
timestamp row_counts ValuesSum Average
2011-02-07 10 13091 1309
2011-03-07 5 6443 1288