Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access query to select rows that are the MAX of one column but unique on another

Tags:

ms-access

Lets say I want a table that gives me the 4 columns of data below, but I only want a single row for each unique "ID" using the "Date" column to select only the most recent date for each unique "ID":

|--ID--|-Type-|-Code-|--Date--|
|   1  |   A  |  11  |11/07/13|
|   2  |   A  |  11  |11/07/13|
|   2  |   B  |  12  |10/07/13|   <-- don't want this record from ID=2 as
|   3  |   A  |  11  |11/07/13|       there is a more recent date for it
|   4  |   A  |  10  |11/07/13|       than 10/07/2013
|   5  |   A  |  11  |11/07/13|

I've tried adapting this answer that seemed to be for a similar question, but I'm getting the following error:

Your query does not include the specified expression 'ID' as part of an part of an aggregate function

Here's my adapted version of that SQL I was trying to run in Access:

SELECT ESM.ID, ESM.Type, ESM.Code, ESM.Date
FROM Emp_Stat_Mon As ESM
INNER JOIN
    (
    SELECT ID, MAX(Date) AS MaxDate
    FROM Emp_Stat_Mon
    GROUP BY ID
    ) groupedESM ON ESM.ID = groupedESM.ID AND ESM.Date = groupedESM.MaxDate;
like image 964
Matt Hall Avatar asked Jul 11 '13 11:07

Matt Hall


People also ask

How do you select a maximum value in an Access query?

Max() and Min() function in MS Accessmax() function return the maximum value of given set. In the function a query is passed and in the eligible records which value will be maximum that will return as result. A expression will be pass as parameter and it will return the maximum value in the expression.

Can we use MAX function in where clause?

The MAX() function is used with the WHERE clause to gain further insights from our data. In SQL, the MAX() function computes the highest or maximum value of numeric values in a column.

Which query can be used to extract the maximum?

To find the maximum value of a column, use the MAX() aggregate function; it takes a column name or an expression to find the maximum value. In our example, the subquery returns the highest number in the column grade (subquery: SELECT MAX(grade) FROM student ).

How do I select a maximum value in a column in SQL?

To find the max value of a column, use the MAX() aggregate function; it takes as its argument the name of the column for which you want to find the maximum value. If you have not specified any other columns in the SELECT clause, the maximum will be calculated for all records in the table.


1 Answers

This does it:

SELECT  ID, Type, Code, Date
FROM Emp_Stat_Mon t1
WHERE t1.Date = 
    (SELECT Max(t2.Date) 
     FROM Emp_Stat_Mon t2 
     WHERE t2.ID=t1.ID 
     GROUP BY t2.ID)

An SQLFiddle with your sample data : SQLFiddle

like image 117
Ron.B.I Avatar answered Oct 13 '22 21:10

Ron.B.I