Mitch
Mitch

Reputation: 13

SQL Query for Comparing Customer Order Amounts

I'm looking to create a query that could compare a customer's latest order purchase amount to the previous order amount of the customer's last purchase. Please see example data screenshot below:

IMG1

Ideally I'd like the query to look for these things in the results:

Note: These conditions for the last bullet could be modified as needed (customer's account age is > 90 days, different in order amount is $500, etc)

Thank you for the assistance!

Upvotes: 0

Views: 203

Answers (1)

S3S
S3S

Reputation: 25112

For 2012 onward you can use LAG

declare @amount decimal(16,2) = 1000
declare @days int = 60

select 
   *
   ,TotalWithPrevious = [Order Amount] + lag([Order Amount]) over (partition by UserID order by [Order Date] desc)
   ,DifferenceofPrevious = [Order Amount] - lag([Order Amount]) over (partition by UserID order by [Order Date] desc)
   ,CheckCondition = case 
                      when [Order Amount] - lag([Order Amount]) over (partition by UserID order by [Order Date] desc) >= @amount
                           and datediff(day,[Order Date],lag([Order Date]) over (partition by UserID order by [Order Date] desc)) >= @days 
                           then 'True' 
                           else 'False' 
                      end
from YourTable

Upvotes: 1

Related Questions