SQL how to find rows which have highest value of s

2019-02-25 08:31发布

For example, the table has columns MYINDEX and NAME.

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

Ho do I find row with highest MYINDEX for specific NAME? E.g. I want to find ROW-2 for name "BOB".

6条回答
趁早两清
2楼-- · 2019-02-25 08:43

If you wanted to see the highest index for name = 'Bob', use:

SELECT MAX(MYINDEX) AS [MaxIndex]
FROM myTable
WHERE Name = 'Bob'
查看更多
趁早两清
3楼-- · 2019-02-25 08:44

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

SELECT * FROM table WHERE NAME = 'BOB' ORDER BY MYINDEX DESC LIMIT 1;
查看更多
太酷不给撩
4楼-- · 2019-02-25 08:54

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

EDIT: to get the whole row:

Select * //never do this really
From Table
Where MYINDEX = (Select Max(MYINDEX) From Table Where Name = [InsertNameHere]
查看更多
仙女界的扛把子
5楼-- · 2019-02-25 08:57

There are several ways to tackle this one. I'm assuming that there may be other columns that you want from the row, otherwise as others have said, simply name, MAX(my_index) ... GROUP BY name will work. Here are a couple of examples:

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

Another possible solution:

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
    )
查看更多
叼着烟拽天下
6楼-- · 2019-02-25 09:03
SELECT MAX(MYINDEX) FROM table
WHERE NAME = 'BOB'

For the whole row, do:

SELECT * FROM table
WHERE NAME = 'BOB'
AND MyIndex = (SELECT Max(MYINDEX) from table WHERE NAME = 'BOB')
查看更多
Lonely孤独者°
7楼-- · 2019-02-25 09:05

Use

FROM TABLE SELECT MAX(MYINDEX), NAME GROUP BY NAME 
查看更多
登录 后发表回答