June 13, 2010

Calculate Average Time Interval in SQL Server




I was recently working on a query where a Hotel has a bunch of Privileged Customers. To determine what discount to give to these customers, the query should be able to tell what is the average interval after which each privileged guest visits the hotel. The Guest who visits the hotel frequently, gets big discounts.

Here’s the query (I used Peso's code for this query which I found on the net):

DECLARE @TT TABLE (CID int, CheckIn DATETIME)

INSERT INTO @TT VALUES (2, 'April 02, 2010 11:25am')
INSERT INTO @TT VALUES (4, 'April 03, 2010 9:55am')
INSERT INTO @TT VALUES (5, 'April 07, 2010 11:24am')
INSERT INTO @TT VALUES (2, 'April 10, 2010 11:22am')
INSERT INTO @TT VALUES (3, 'April 15, 2010 5:27am')
INSERT INTO @TT VALUES (6, 'April 16, 2010 8:21am')
INSERT INTO @TT VALUES (7, 'April 17, 2010 11:55am')
INSERT INTO @TT VALUES (3, 'April 22, 2010 10:16am')
INSERT INTO @TT VALUES (4, 'April 24, 2010 11:35am')
INSERT INTO @TT VALUES (7, 'April 30, 2010 9:49pm')
INSERT INTO @TT VALUES (2, 'May 01, 2010 9:49am')
INSERT INTO @TT VALUES (5, 'May 02, 2010 10:43am')
INSERT INTO @TT VALUES (6, 'April 21, 2010 9:23am')
INSERT INTO @TT VALUES (3, 'May 03, 2010 11:29am')

SELECT CID,
DATEDIFF(HOUR, MIN(CheckIn), MAX(CheckIn))
/ (
COALESCE(NULLIF(COUNT(*), 1), 2) - 1) AS AvgIntervalInHour
FROM @TT
GROUP BY CID
ORDER BY AvgIntervalinHour

OUTPUT

image


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

0 Responses to "Calculate Average Time Interval in SQL Server"
 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions