简体   繁体   English

如何选择某列上具有最大值的行

[英]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. B / c如果需要一个复杂的查询来获取tab1,那么写两次是很麻烦的。 By the way, I am using Sqlite. 顺便说一下,我正在使用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. 这个表单是否比作者提到的嵌套SELECT更有效是值得怀疑的,但如果tab1是select本身则可能更好。

From what I understood, the problem is not the query itself but "cumbersome" writing table tab1. 根据我的理解,问题不是查询本身,而是“繁琐”的写表tab1。 I would suggest then you create view tab1 , and then use it. 我建议你create view tab1 ,然后使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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