问题
Good Afternoon,
I am working on a database for someone that tracks the vehicles they use in their business. Due to vehicles having new license plates issued to them as they expire the business wants to track the current plate for each vehicle as well as all plates that were previously issued to each vehicle.
I have created a table for vehicles, tbl_vehicles.
I have also created a table for license plates, tbl_license_plates.
Being that each vehicle has multiple license plate records. I need on a form, frm_vehicles, (where certain data for each vehicle is updated) to show only the most recent license plate number to appear. This needs to happen even if the plate has expired...i.e...is no longer valid.
The problem that I am encountering is that I do not have sufficient SQL skills to construct a query that returns for each vehicle only the most recent plate. I wrote the below query and it returns the vehicle_master_id and the expiration date of the most recently issued plate.
However, when I try to add the license_plate_number to the query, it returns every plate that has every been issued for each vehicle. This is a problem because I need the query to return only the most recently issued plate, whether or not it is valid (unexpired).
So, the guidance that I am seeking is how to construct this query so that it returns the license_plate_number for only the most recently issued plate, regardless of validity.
Can someone point me in the right direction, please?
As suggested, here is the text of the query
SELECT tbl_license_plates.vehicle_master_id AS Vehicle, Max(tbl_license_plates.date_expires) AS Expiration_Date, tbl_license_plates.license_plate_number FROM tbl_license_plates GROUP BY tbl_license_plates.vehicle_master_id, tbl_license_plates.license_plate_number;
回答1:
Consider:
SELECT tbl_License_Plates.* FROM tbl_License_Plates WHERE license_plate_master_ID IN
(SELECT TOP 1 license_plate_master_ID FROM tbl_License_Plates AS Dupe WHERE
Dupe.vehicle_master_ID = tbl_License_Plates.vehicle_master_ID ORDER BY date_issued DESC);
More info on subqueries http://allenbrowne.com/subquery-01.html
Another approach is to take your GROUP BY query that has vehicle ID and issue date and INNER JOIN with tbl_License_Plates with compound link on both ID and date fields. This will be a non-updatable query.
回答2:
Consider using Max function to return max valid date, can find a lot on Google about that function. Something like:
SELECT tbl_License_Plates.vehicle_master_id, Max(tbl_License_Plates.date_expires) AS
MaxOfdate_expires
FROM tbl_License_Plates
GROUP BY tbl_License_Plates.vehicle_master_id;
来源:https://stackoverflow.com/questions/58467211/how-to-properly-create-a-sql-query