SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 select customer purchase less than 10 days apart
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

spinningtop
Starting Member

United Kingdom
29 Posts

Posted - 07/06/2012 :  07:34:33  Show Profile  Reply with Quote


Hi
I have a table with the columns 'StoreID', 'CustomerID' and 'DateOfPurchase'. I just want to select the StoreID and the CustomerID for each customer at the same store where their date of purchase is less than 10 days apart.

So from the table below I would select storeID 0001 and Customer A and both dates of purchase as they are less than 10 days apart.



StoreId CustomerID DateofPurchase
0001 A 01/01/2001
0001 A 02/01/2001
0001 B 01/01/2003
0002 A 01/01/2001
0002 A 20/01/2001
0002 B 01/01/2003

Should fairly simple but I can't figure it out. Should create a derived table with join on StoreID and CustomerID ?

sunitabeck
Flowing Fount of Yak Knowledge

5152 Posts

Posted - 07/06/2012 :  07:40:51  Show Profile  Reply with Quote
One way to do this is as follows:
SELECT
	a.StoreId,
	a.CustomerId,
	DATEDIFF( dd,b.DateofPurchase, a.DateofPurchase) AS Interval
FROM
	YourTable a
	CROSS APPLY
	(
		SELECT TOP (1) b.DateOfPurchase
		FROM YourTable b
		WHERE b.DateofPurchase < a.DateofPurchase
		AND a.CustomerId = b.CustomerId
		ORDER BY b.DateofPurchase DESC 
	) b
WHERE
	DATEDIFF( dd,b.DateofPurchase, a.DateofPurchase) < 10
Go to Top of Page

spinningtop
Starting Member

United Kingdom
29 Posts

Posted - 07/06/2012 :  07:52:44  Show Profile  Reply with Quote
This is great, works perfectly, thank you sunita.

I have never come across CROSS APPLY before but I will read up on it.

Go to Top of Page

sunitabeck
Flowing Fount of Yak Knowledge

5152 Posts

Posted - 07/06/2012 :  08:16:37  Show Profile  Reply with Quote
You are welcome!

CROSS APPLY and OUTER APPLY are sort of similar to INNER JOINS and LEFT JOINS, but different in that, logically the left table expression is evaluated first and then the right - which allows you to correlate the right expression with the left.
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000