Hi all, I'm hoping someone can suggest the best approach to my issue.
I'm trying to write a query to analyse the retention of customer purchases for each given month. So given a simple purchase order table (Sales), which contains each purchase a customer has made I want to derive a status for a customer against each month, the derived status has to show whether the customer has made a purchase in the previous month and in the current month, or if they have made a purchase in the previous month but not in the current month etc... the stauses can be arbitrary e.g., retained, returning or similar...
The query will run on a table with millions of rows so has to be effiicient and I can't use any temp tables, pivot or partition functions and will probably have a left join with a calendar dimenion table.
Initial thoughts are obviously a self join with a (month -1) condition but can't think of how to determine previous month and past activity to relate the each current month.
Many thanks in advance!!!
Here is a very simple sample table,
CREATE TABLE [dbo].[SALES]( [SALE_DATE] [date] NULL, [USERID] [int] NULL, [INVOICE_AMOUNT] float NULL, [SALE_YEAR_MONTH] [int] NULL, ) ON [PRIMARY] GO INSERT [dbo].[SALES] ([SALE_DATE], [USERID], [INVOICE_AMOUNT], [SALE_YEAR_MONTH]) VALUES ('2012-01-02', 8, 33, 201201) INSERT [dbo].[SALES] ([SALE_DATE], [USERID], [INVOICE_AMOUNT], [SALE_YEAR_MONTH]) VALUES ('2013-01-01', 8, 232, 201301) INSERT [dbo].[SALES] ([SALE_DATE], [USERID], [INVOICE_AMOUNT], [SALE_YEAR_MONTH]) VALUES ('2013-01-02', 8, 54, 201301) INSERT [dbo].[SALES] ([SALE_DATE], [USERID], [INVOICE_AMOUNT], [SALE_YEAR_MONTH]) VALUES ('2013-02-02', 8, 122, 201302) INSERT [dbo].[SALES] ([SALE_DATE], [USERID], [INVOICE_AMOUNT], [SALE_YEAR_MONTH]) VALUES ('2014-01-01', 8, 75, 201401) INSERT [dbo].[SALES] ([SALE_DATE], [USERID], [INVOICE_AMOUNT], [SALE_YEAR_MONTH]) VALUES ('2014-01-02', 8, 333, 201401) INSERT [dbo].[SALES] ([SALE_DATE], [USERID], [INVOICE_AMOUNT], [SALE_YEAR_MONTH]) VALUES ('2014-01-03', 8, 3325, 201401)