简体   繁体   中英

How to select rows with max values on a certain column

For example, I have

tab1:
att1|att2
A|3
B|4
C|3
D|4
E|1
F|2

And I want

B|4
D|4

I know I can use

SELECT att1 att2
FROM tab1 as T
WHERE T.att2 =
(
   SELECT MAX(att2) FROM tab1;
}

I wondering if there is a more clever way to do it. B/c if it takes a complicated query to get tab1, it is cumbersome to write it twice. By the way, I am using Sqlite.

My original answer was:

SELECT att1, att2
FROM tab1
ORDER BY att2 DESC LIMIT 0,1;

I apologize, that won't work if there is more than one record with the max value. Here is another answer:

SELECT t1.att1, t1.att2
FROM tab1 AS t1
LEFT JOIN tab1 AS t2
ON t1.att2 < t2.att2
WHERE t2.att1 IS NULL;

It's questionable whether this form is more efficient than nested SELECT the author mentioned, but might be better in case if tab1 is a select itself.

From what I understood, the problem is not the query itself but "cumbersome" writing table tab1. I would suggest then you create view tab1 , and then use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM