Reputation: 485
I have a database with Hours
as integer
field and PK
like record ID
/Autonumber
in a table to identify records. How can I with an SQL Query get the value max value and the record ID or field value where the max value is located? I am using a .mdb MS Access
database.
Code I am currently using:
with dmpat.ADOQuery1 do
begin
sql.Clear; //Hours is integer field
//Here I would like to get the ID (integer) field value of each of these values:
sql.Add('SELECT MAX(Hours) AS [Max], MIN(Hours) AS [Min], AVG(Hours) AS [AVE]');
sql.Add('FROM Professions');
open;
Max := fields[0];
Min := fields[1];
Ave := fields[2];
end;
Is such a thing possible? New to SQL, thanks anyway!
Upvotes: 0
Views: 3199
Reputation: 485
So I found this solution. This would give the Primary Key
or the record ID
. It also allows for the possibility that there is more than one record with the MAX()
or MIN()
value.
SELECT ID, Name, Hours AS [Max] FROM Professions
WHERE Hours = (SELECT MAX(Hours) FROM Professions)
ORDER BY ID ASC
Here is proof using another database, though the same concept applies.
I actually wrote this code while working on a completely different problem.
Upvotes: -2
Reputation: 164064
You can use 2 subqueries:
SELECT MAX(Hours) AS [Max],
(SELECT TOP 1 ID FROM Professions ORDER BY Hours DESC) AS Max_ID,
MIN(Hours) AS [Min],
(SELECT TOP 1 ID FROM Professions ORDER BY Hours) AS Min_ID,
AVG(Hours) AS [AVE]
FROM Professions
Each of the subqueries sorts the table either descending or ascending and picks the top row.
Upvotes: 3