just check out if below gives some guidelines :
The tables :
tblRawData
Country
InvoiceDate
tblLookUpData
Country
CountryMonth
CountryDays
The sub-queries :
qrytblRawData
Code:
SELECT
tblRawData.Country,
tblRawData.InvoiceDate,
Day([InvoiceDate]) AS DayInvoiceDate,
Month([InvoiceDate]) AS MonthInvoiceDate
FROM
tblRawData;
qryPayDayInter
Code:
SELECT
qrytblRawData.Country,
qrytblRawData.InvoiceDate,
qrytblRawData.MonthInvoiceDate,
qrytblRawData.DayInvoiceDate,
tblLookUpData.CountryMonth,
tblLookUpData.CountryDays,
Min(IIf([CountryDays]>=[DayInvoiceDate],[CountryDays],0)) AS DayGreaterThanEqualToInvoiceDay
FROM
qrytblRawData
INNER JOIN
tblLookUpData
ON
(qrytblRawData.MonthInvoiceDate = tblLookUpData.CountryMonth)
AND
(qrytblRawData.Country = tblLookUpData.Country)
GROUP BY
qrytblRawData.Country,
qrytblRawData.InvoiceDate,
qrytblRawData.MonthInvoiceDate,
qrytblRawData.DayInvoiceDate,
tblLookUpData.CountryMonth,
tblLookUpData.CountryDays
HAVING
(((Min(IIf([CountryDays]>=[DayInvoiceDate],[CountryDays],0)))>0));
qryPayDayFinal
Code:
SELECT
qryPayDayInter.Country,
qryPayDayInter.InvoiceDate,
Min(qryPayDayInter.DayGreaterThanEqualToInvoiceDay) AS MinOfDayGreaterThanEqualToInvoiceDay
FROM
qryPayDayInter
GROUP BY
qryPayDayInter.Country,
qryPayDayInter.InvoiceDate;
The final query :
qryPayDateFinal
Code:
SELECT
qryPayDayFinal.Country,
qryPayDayFinal.InvoiceDate,
qryPayDayFinal.MinOfDayGreaterThanEqualToInvoiceDay, DateSerial(Year([InvoiceDate]),Month([InvoiceDate]),[MinOfDayGreaterThanEqualToInvoiceDay]) AS PayDate
FROM
qryPayDayFinal;
Edit :
Was wondering if we had tables like below :
tblRawData
Country
InvoiceDate
tblLookUpDataCopy
Country
CountryMonth
CountryDaysStart
CountryDaysEnd
with data like say :
Code:
Country CountryMonth CountryDaysStart CountryDaysEnd
US 1 1 7
US 1 7 22
US 1 22 31
perhaps things could be simpler, something like below or even simpler :
pseudo-code
the sub-query :
qry1
Code:
SELECT
tblRawData.Country,
tblRawData.InvoiceDate,
Month([InvoiceDate]) AS MonthInvoiceDate,
Day([InvoiceDate]) AS DayInvoiceDate
FROM tblRawData;
the final query :
Code:
SELECT
qry1.Country,
qry1.InvoiceDate,
qry1.MonthInvoiceDate,
qry1.DayInvoiceDate,
tblLookUpDataCopy.CountryDaysStart,
tblLookUpDataCopy.CountryDaysEnd,
IIf(([DayInvoiceDate]>=[CountryDaysStart]) And ([DayInvoiceDate]<[CountryDaysEnd]),[CountryDaysEnd],0) AS PaymentDay,
DateSerial(Year([InvoiceDate]),Month([InvoiceDate]),[PaymentDay]) AS PaymentDate
FROM
qry1
INNER JOIN
tblLookUpDataCopy
ON
(qry1.Country = tblLookUpDataCopy.Country)
AND
(qry1.MonthInvoiceDate = tblLookUpDataCopy.CountryMonth)
WHERE
(((IIf(([DayInvoiceDate]>=[CountryDaysStart]) And ([DayInvoiceDate]<[CountryDaysEnd]),[CountryDaysEnd],0))>0));
Thanks