How to average/sum data in a day in SQL Server 2005

后端 未结 8 2334
执念已碎
执念已碎 2020-12-12 08:25

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         


        
8条回答
  •  佛祖请我去吃肉
    2020-12-12 08:57

    One possibility, if you need to do this often enough: add three computed columns for day, month, year to your table. Those columns are computed automatically based on the timestamp column, and they're just integer values, so they're easy to use in a GROUP BY.

    To do this, use these T-SQL statements:

    ALTER TABLE dbo.ROASTER_FEED ADD TSDay AS DAY(timestamp) PERSISTED
    ALTER TABLE dbo.ROASTER_FEED ADD TSMonth AS MONTH(timestamp) PERSISTED
    ALTER TABLE dbo.ROASTER_FEED ADD TSYear AS YEAR(timestamp) PERSISTED
    

    Now, you can easily select your data based on any day you wish:

    SELECT TSDay, TSMonth, TSYear, SUM(FEED)   -- use AVG(FEED) for average values
    FROM dbo.ROASTER_FEED
    WHERE TSYear = 2011 AND TSMonth = 8   -- or whatever you want to grab from the table!
    ORDER BY timestamp
    GROUP BY TSDay, TSMonth, TSYear
    

提交回复
热议问题