简体   繁体   中英

How to get highest values from two columns in a table (SQL)

So I have a table that has n rows like this:

.ID.|.Cycle.|.Week.|..Date...|.Type. 

.1..|...1...|..1...|.12-12-12|.a.

.2..|...1...|..2...|.12-12-12|.a. 

.3..|...1...|..3...|.12-12-12|.a.

.4..|...1...|..4...|.12-12-12|.a.

.5..|...2...|..1...|.12-12-12|.a.

.6..|...2...|..2...|.12-12-12|.a.

.7..|...2...|..2...|.12-12-12|.some_value.

So here I'd want to get back cycle 2, week 2 of type "some_value" because cycle 2 is the largest cycle number in the table, and week 2 is the largest week number in cycle 2.

Right now I use query

SELECT cycle=MAX(cycle),week=MAX(week)
FROM table 
WHERE TYPE=some_value

But I have a feeling this isn't right because I don't seem to get correct values. Any help is appreciated.

Are you trying to do this?

select cycle, week
from table
where type = somevalue
order by cycle desc
limit 1;

Your query is returning the maximum of the cycle and of the week independently.

I Guess this is what you are trying to achieve.

SELECT week,
       cycle
FROM   table
WHERE  cycle = (SELECT Max(cycle)
                FROM   table
                WHERE  TYPE = some_value)
       AND TYPE = some_value
ORDER  BY week DESC 
limit 1

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