2

In this scenario, I am trying to report on the operating_system_version for each distinct computer_id where the report_id for that computer_id is the greatest.

Currently, I am getting the below results:

operating_system_version | computer_id | report_id
10.8 | 1 | 10
10.9 | 1 | 20
10.9 | 2 | 11
10.8 | 2 | 21

The above is returned by this statement:

SELECT operating_systems.operating_system_version,
       reports.computer_id,
       reports.report_id
FROM operating_systems
INNER JOIN reports
    ON operating_systems.report_id = reports.computer_id

Instead, would like return the most recent (highest report_id) operating_system_version for each distinct computer_id, for example:

operating_system_version | computer_id | report_id
10.9 | 1 | 20
10.8 | 2 | 21

I am brand new to SQL .. Appreciate any help.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
user1890913
  • 107
  • 6
  • 1
    This question is very common. Follow the [tag:greatest-n-per-group] tag for many solutions. – Bill Karwin Oct 17 '13 at 03:11
  • Ok wow. Found an excellent post as suggested: http://stackoverflow.com/questions/7745609/sql-select-only-rows-with-max-value-on-a-column – user1890913 Oct 17 '13 at 03:47

4 Answers4

1

You would need to add a group by statement and a having statement.

The group by would look like

group by computer_id

The having would look like

having report_id= (select max(report_id) )
0
SELECT operating_systems.operating_system_version, 
        reports.computer_id, 
    reports.report_id
FROM operating_systems INNER JOIN reports ON operating_systems.report_id = reports.computer_id
WHERE NOT EXISTS (SELECT 1 
                    FROM  reports r2 
                    WHERE r2.computer_id = reports.computer_id 
                    AND r2.reports_id > reports.reports_id)
Dijkgraaf
  • 11,049
  • 17
  • 42
  • 54
0

A subquery would lead you to desired end result:

SELECT os.operating_system_version,
       r2.computer_id,
       MAX(r2.report_id)
FROM (
    SELECT DISTINCT computer_id
    FROM reports
) r
INNER JOIN operating_systems os
    ON os.report_id = r.computer_id
INNER JOIN reports r2
    ON r2.computer_id = r.computer_id
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • Unfortunately this returns only one record: operating_system_version | computer_id | MAX(r2.report_id) 10.8 | 2 | 21 Instead of the needed return of: 10.9 | 1 | 20 10.8 | 2 | 21 which is the highest report_id for each computer_id. – user1890913 Oct 17 '13 at 03:37
0

Need to do a better job looking through other posts. This question is answered in an excellent post at: SQL Select only rows with Max Value on a Column

Community
  • 1
  • 1
user1890913
  • 107
  • 6