SQL how to find the rows that have the highest value of a specific column

For example, the table has columns MYINDEX and NAME.

MYINDEX | NAME
=================
1       | BOB
2       | BOB
3       | CHARLES

Ho, will I find the row with the highest MYINDEX for a particular NAME? For instance. I want to find ROW-2 for the name "BOB".

+3
source share
6 answers

SELECT Max(MYINDEX) FROM table WHERE NAME = [insertNameHere]

EDIT: to get the whole line:

Select * //never do this really
From Table
Where MYINDEX = (Select Max(MYINDEX) From Table Where Name = [InsertNameHere]
+12
source
SELECT MAX(MYINDEX) FROM table
WHERE NAME = 'BOB'

For the entire line, do:

SELECT * FROM table
WHERE NAME = 'BOB'
AND MyIndex = (SELECT Max(MYINDEX) from table WHERE NAME = 'BOB')
+4
source

. , , , , MAX(my_index) ... GROUP BY name . :

SELECT
    MT.name,
    MT.my_index
FROM
(
    SELECT
        name,
        MAX(my_index) AS max_my_index
    FROM
        My_Table
    GROUP BY
        name
) SQ
INNER JOIN My_Table MT ON
    MT.name = SQ.name AND
    MT.my_index = SQ.max_my_index

:

SELECT
    MT1.name,
    MT1.my_index
FROM
    My_Table MT1
WHERE
    NOT EXISTS
    (
        SELECT *
        FROM
            My_Table MT2
        WHERE
            MT2.name = MT1.name AND
            MT2.my_index > MT1.my_index
    )
+3

name = 'Bob', :

SELECT MAX(MYINDEX) AS [MaxIndex]
FROM myTable
WHERE Name = 'Bob'
0
source

If you want to skip the inner join, you can do:

SELECT * FROM table WHERE NAME = 'BOB' ORDER BY MYINDEX DESC LIMIT 1;
0
source

Using

FROM TABLE SELECT MAX(MYINDEX), NAME GROUP BY NAME 
-1
source

Source: https://habr.com/ru/post/1756610/


All Articles