Labels

Saturday, December 31, 2011

Calculate a measure for every 30 mins

-- SQL GROUP BY half an hour - sql server order by half an hour ------------
-- Set GROUP BY interval half hour or other value like quarter hour (15 minutes)
USE tempdb;DECLARE  @IntervalMinutes INT = 30
SELECT PurchaseOrderID,
       TotalDue,
       OrderDate = DATEADD(MINUTE,CHECKSUM(PurchaseOrderID),OrderDate)
INTO   POH   -- Generate test data with SELECT INTO table create
FROM   AdventureWorks2008.Purchasing.PurchaseOrderHeader
-- MSSQL group by half an hour time only without date
SELECT   Period = Convert(VARCHAR,DATEADD(MINUTE,(DATEDIFF(MINUTE,'19000101', OrderDate) / @IntervalMinutes) * @IntervalMinutes,
                                          '19000101'),108),
         TotalPurchase = SUM(TotalDue) -- SUM aggregate function
FROM     POH
GROUP BY Convert(VARCHAR,DATEADD(MINUTE,(DATEDIFF(MINUTE,'19000101',OrderDate) / @IntervalMinutes) * @IntervalMinutes,
                                 '19000101'),108)
ORDER BY Period;
/* Partial results:
Period      TotalPurchase
21:00:00    991821.1719
21:30:00    1047153.5762
22:00:00    969689.2412
22:30:00    1072308.1789
23:00:00    1145267.5879
23:30:00    890941.4027
*/
-- T-SQL group by half an hour for each order date
SELECT   Period = DATEADD(MINUTE,(DATEDIFF(MINUTE,'19000101',OrderDate) / @IntervalMinutes) * @IntervalMinutes,'19000101'),
         TotalPurchase = SUM(TotalDue) -- SQL SUM aggregate function
FROM     POH
GROUP BY DATEADD(MINUTE,(DATEDIFF(MINUTE,'19000101',OrderDate) / @IntervalMinutes) * @IntervalMinutes,'19000101')
ORDER BY Period;
GO
/* Partial results
Period                        TotalPurchase
2004-03-15 08:00:00.000       133756.1379
2004-03-15 08:30:00.000       186778.3909
2004-03-16 08:30:00.000       162812.8586
2004-03-16 18:30:00.000       5036.1465
*/
DROP TABLE tempdb.dbo.POH

No comments:

Post a Comment