Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I find missed years

Status
Not open for further replies.

3587ch

Technical User
Jun 19, 2009
30
US
I have a tblpayments with a clientid and payment date, payments are made yearly (sometimes). I need a way to findout for each client which years they missed. How can I do this?

So I might say between 2005 and 2009 which clients missed a payment and then I need to know their clientID and the year(s) they missed?

Thank you,
 
One way is to make a table of year values.

tblYears
numYears (numeric value)

Code:
numYear
2004
2005
2006
2007
2008
2009
2010
2011
2012

Populate the table with the minimum year your data will hold, and go out as far as you think necessary.

Now build a query that returns the range you want from tblYears
qryYearRange
Code:
SELECT tblYears.numYear
FROM tblYears
WHERE tblYears.numYear >=[Enter Start Year] And  tblYears.numYear<=[Enter End Year]

Now build a cartesian product of the all the clients and the years in question
qryCart_YearsAndClients
Code:
SELECT tblClients.clientID, qryYearRange.numYear
FROM qryYearRange, tblClients;

Now build a query that changes the date in the payment table into a numeric year
qryYearPayment
Code:
SELECT tblPayments.clientID, CLng(Year([dtmPaymentDate])) 
AS YearPayment
FROM tblPayments
ORDER BY tblPayments.clientID, CLng(Year([dtmPaymentDate]));

Now build a query that returns all missing years
Code:
SELECT 
 clientID, 
 numYear
FROM qryCart_YearsAndClients 
LEFT JOIN qryYearPayments ON   
 (qryCart_YearsAndClients.clientID =
  qryYearPayments.clientID) AND
 (qryCart_YearsAndClients.numYear =  
 qryYearPayments.YearPayment)
WHERE 
 qryYearPayments.clientID Is Null
ORDER BY 
 qryCart_YearsAndClients.clientID,
 qryCart_YearsAndClients.numYear;

Given this
Code:
clientID	dtmPaymentDate
1	1/1/2005
1	1/1/2006
1	1/1/2008
1	1/1/2009
2	1/1/2006
2	1/1/2007
2	1/1/2009

the query produces this if I enter 2005 and 2009
Code:
clientID	numYear
1	2007
2	2005
2	2008

This could all be done in a single query, but it would be hard to explain so I used a bunch of small queries.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top