tags:

views:

50

answers:

1

Ok here's the deal I got one table with a bunch of client information. Each client makes up to one purchase a year which is represented by an individual row. there's a column for the year and there's a column the contains a unique identifier for each client. What I need to do is to construct a query that takes last year and this year and shows me which clients were here made a purchase last year but not make a purchase this year.

I also need to build a query that shows me which clients did not make a purchase last year and the year before last but did make a purchase this year.

+4  A: 

Given this table:

Purchase
========
PurchaseID (autoincrement int PK)
ClientID (int FK)
Year (int)
Amount (float)

Sample data:

insert into Purchase (ClientID, Year, Amount) values (1, 2009, 123)
insert into Purchase (ClientID, Year, Amount) values (2, 2009, 123)
insert into Purchase (ClientID, Year, Amount) values (2, 2010, 123)
insert into Purchase (ClientID, Year, Amount) values (3, 2010, 123)
insert into Purchase (ClientID, Year, Amount) values (3, 2007, 123)
insert into Purchase (ClientID, Year, Amount) values (4, 2010, 123)
insert into Purchase (ClientID, Year, Amount) values (4, 2008, 123)

Made a purchase in 2009 but not the following year (2010):

select p1.*
from Purchase p1
left outer join Purchase p2 on p1.ClientID = p2.ClientID and p1.Year = p2.Year - 1
where p2.ClientID is null
    and p1.Year = 2009

Results:

PurchaseID  Year        ClientID    Amount
----------- ----------- ----------- ---------------------
1           2009        1           123.00

Made a purchase in 2010, but not the two previous years (2008 or 2009):

select p3.*
from 
Purchase p3
left outer join Purchase p2 on p3.ClientID = p2.ClientID and p3.Year = p2.Year + 1
left outer join Purchase p1 on p3.ClientID = p1.ClientID and p3.Year = p1.Year + 2
where p2.ClientID is null
    and p1.ClientID is null
    and p3.Year = 2010

Results:

PurchaseID  Year        ClientID    Amount
----------- ----------- ----------- ---------------------
4           2010        3           123.00
RedFilter
@Orbman, Great work, but I think I'd use constants on the right side of your ON clauses for the year.
Marcus Adams
@Marcus: I did without constants so that you only need to change the `Year` in one place to use it for different years. They can more easily be turned into views this way.
RedFilter
@Orbman, That's a good reason. Is the query able to use an index on Year with the expression on the right side of the ON clause?
Marcus Adams
@Marcus: I would guess no...
RedFilter
Sorry I took so long to get back but thanks a lot guys. That filled in the other portions of the other 2 complex queries I needed to run.
Adam McMahon