I’ve an issue where I am trying to pull identify customer orders where
- The customer had an order in the same month one year ago and this
month. - The customer had an order one year ago this month but not this month
- The customer had an order this month but not one year ago.
My data looks like this.
CustomerID Month Year Value
1 2 2011 18
1 2 2012 16
2 1 2011 15
3 1 2012 13
From this I would expect to return (for each criteria above)
- Rows 1 & 2
- Row 3
- Row 4
I’m sure there must be an elegant solution to this but for the life of me I can’t see it today!
So far I’ve got to this but I get a lot of duplicates am I missing something obvious?
;with t (ID, Yr, Mo)
As
(
Select ID, TransactionYearFK, TransactionMonthFK
From dbo.MyData
)
Select *
From t tC
Full Outer Join t tL On tC.ID = tL.ID And tC.Mo = tL.Mo And tL.Yr = tC.Yr - 1
Where Coalesce(tC.ID, tL.ID) = 21110
Order By tC.Yr, tC.Mo
If you want all the results in one query, your conditions could be restated like this:
The year must be no earlier than the last one.
The month must be the same as the current month, whether this or the last year.
Assuming then you want to return order counts per month in each year for every customer, you could try something like this: