简体   繁体   English

SQL获取行等于某值的最大列数

[英]SQL get max of columns where a row equals something

If I have Table with 3-columns: 如果我有带有3列的表格:

Date | Name  | Num
oct1 | Bob   | 2
oct2 | Zayne | 1   
oct1 | Test  | 5    
oct2 | Apple | 7

I want to retrieve the rows where Num is MAX , 我想检索NumMAX的行。

WHERE Date = oct1 or Date = oct2

So I want result to be: 所以我希望结果是:

oct1 Test 5
oct2 Apple 7

MYSQL is preferred. 首选MYSQL。 But SQL answer be given also. 但是也给出SQL答案。 Thanks. 谢谢。

You can try below using correlated subquery 您可以在下面尝试使用相关子查询

select * from tablename a 
 where num in (select max(num) from tablename b where a.date=b.date)
 and date in ('oct1', 'oct2')

You can try to use correctly subquery 您可以尝试正确使用子查询

Schema (MySQL v5.7) 模式(MySQL v5.7)

CREATE TABLE T(
   Date VARCHAR(50),
   Name  VARCHAR(50), 
  Num INT
);



INSERT INTO T VALUES ('oct1','Bob',2);
INSERT INTO T VALUES ('oct2','Zayne',1);
INSERT INTO T VALUES ('oct1','Test',5);
INSERT INTO T VALUES ('oct2','Apple',7);

Query #1 查询#1

SELECT *
FROM T t1
WHERE Num = (SELECT MAX(Num) FROM T tt WHERE t1.Date = tt.Date)
AND 
     t1.Date in ('oct1','oct2')


| Date | Name  | Num |
| ---- | ----- | --- |
| oct1 | Test  | 5   |
| oct2 | Apple | 7   |

View on DB Fiddle 在数据库小提琴上查看

It sounds like you want this query: 听起来您想要此查询:

SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT Date, MAX(Num) AS max_num
    FROM yourTable
    WHERE Date IN ('oct1', 'oct2')
    GROUP BY Date
) t2
    ON t1.Date = t2.Date AND t1.Num = t2.max_num
WHERE t1.Date IN ('oct1', 'oct2');

By the way, you should seriously consider storing proper date data in an actual date or datetime column in MySQL. 顺便说一句,您应该认真考虑在MySQL的实际date或datetime列中存储适当的日期数据。 It appears you are just storing text right now, which would be hard to work with. 看来您现在只是在存储文本,很难使用。

You can use corelated subquery just like below 您可以如下使用关联子查询

 SELECT *
 FROM T t1
 WHERE Num = (SELECT MAX(Num) FROM T t2 WHERE t2.Date = t1.Date)

Fiddle link 小提琴链接

Date    Name    Num
oct1    Test    5
oct2    Apple   7

As you where asking for a standard way to do this: All the answers given so far comply with the SQL standard. 当您需要一种标准的方法来执行此操作时:到目前为止给出的所有答案都符合SQL标准。 One more possible approach in standard SQL is to use a window function. 标准SQL中的另一种可能方法是使用窗口函数。 This is only featured in MySQL as of version 8, however. 但是,仅MySQL从版本8开始才提供。

select date, name, num
from
(
  select date, name, num, max(num) over (partition by date) as max_num
  from mytable
) analyzed
where num = maxnum
order by date;

This only reads the table once, which can (but not necessarily does) speed up the query. 这只会读取一次表,这可以(但不一定可以)加快查询速度。

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

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