Question

I am trying to build an access query with multiple criteria. The table to be queried is "tblVendor" which has information about vendor shipment data as shown below:

enter image description here

The second table is "tblSchedule" which has the schedule for each Vendor cutoff date. This table has cutoff dates for data analysis.

enter image description here

For each vendor, I need to select records which have the ShipDate >= CutoffDate. Although not shown in the data here, it may be possible that multiple vendors have same CutoffDate. For small number of records in "tblCutoffdate", I can write a query which looks like:

SELECT tblVendors.ShipmentId, tblVendors.VendorNumber, tblVendors.VendorName, 
tblVendors.Units, tblVendors.ShipDate
FROM tblVendors INNER JOIN tblCutoffDate ON tblVendors.VendorNumber =
tblCutoffDate.VendorNumber
WHERE (((tblVendors.VendorNumber) In (SELECT VendorNumber FROM [tblCutoffDate] WHERE 
[tblCutoffDate].[CutoffDate] = #2/1/2014#)) AND ((tblVendors.ShipDate)>=#2/1/2014#)) OR
(((tblVendors.VendorNumber) In (SELECT VendorNumber FROM [tblCutoffDate] WHERE
[tblCutoffDate].[CutoffDate] = #4/1/2014#)) AND ((tblVendors.ShipDate)>=#4/1/2014#));

As desired, the query gives me a result which looks like:

enter image description here

What concerns me now is that I have a lot of records being added to the "tblCutoffDate" which makes it difficult for me to hardcode the dates in the query. Is there a better way to write the above SQL statement without any hardcoding?

Was it helpful?

Solution 2

A simpler WHERE clause should give you what you want.

SELECT
    v.ShipmentId,
    v.VendorNumber,
    v.VendorName,
    v.Units,
    v.ShipDate
FROM
    tblVendors AS v
    INNER JOIN tblCutoffDate AS cd
    ON v.VendorNumber = cd.VendorNumber
WHERE v.ShipDate >= cd.CutoffDate;

OTHER TIPS

You might try something like -- this should handle vendors having no past cutoff, or those having no future cutoff

"today" needs a suitable conversion to just date w/o time

comparison "=" may go on both, or one, or none Max/Min

"null" may be replaced by 1/1/1900 and 12/31/3999 in Max/Min

SELECT tblvendors.shipmentid,
   tblvendors.vendornumber,
   tblvendors.vendorname,
   tblvendors.units,
   tblvendors.shipdate

FROM   tblvendors
LEFT JOIN 
   ( SELECT vendornum,
        Max( iif cutoffdate <  today, cutoffdate, null) as PriorCutoff,
        Min( iif cutoffdate >= today, cutoffdate, null) as NextCutoff
     FROM tblcutoffdate
     GROUP BY vendornum
   ) as VDates
ON  vendornumber = vendornum
WHERE tblvendors.shipdate BETWEEN  PriorCutoff and NextCutoff

ORDER BY  vendornumber, shipdate, shipmentid
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top