0

So I have this table and I am trying to get the latest analysis_id

+----+---------+-------------+
| id | repo_id | analysis_id |
+----+---------+-------------+
| 1  |   20    |      3      |
+----+---------+-------------+
| 2  |   20    |      4      |
+----+---------+-------------+
| 3  |   20    |      5      |
+----+---------+-------------+
| 4  |   21    |      6      |
+----+---------+-------------+
| 5  |   22    |      7      |
+----+---------+-------------+

So how do I get the largest number from analysis_id without the repeating repo_id

+----+---------+-------------+
| id | repo_id | analysis_id |
+----+---------+-------------+
| 3  |   20    |      5      |
+----+---------+-------------+
| 4  |   21    |      6      |
+----+---------+-------------+
| 5  |   22    |      7      |
+----+---------+-------------+
ropenrom24
  • 517
  • 8
  • 18

3 Answers3

4

A general MySQL 8+ friendly solution uses ROW_NUMBER:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY repo_id ORDER BY analysis_id DESC) rn
    FROM yourTable
)

SELECT id, repo_id, analysis_id
FROM cte
WHERE rn = 1;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
3

You are looking for group by

SELECT MAX(id) ,repo_id ,MAX(analysis_id)
FROM YOUR_TABLE
GROUP BY repo_id 
Arun Palanisamy
  • 5,281
  • 6
  • 28
  • 53
0

In MySQL 5+ you may use

SELECT *
FROM tablename t1
WHERE NOT EXISTS ( SELECT NULL
                   FROM tablename t2
                   WHERE t1.repo_id = t2.repo_id
                     AND t1.id < t2.id )
Akina
  • 39,301
  • 5
  • 14
  • 25