简体   繁体   中英

MYSQL finding maximum value and date corresponds to the value in same select statement

I have aa select statement

SELECT MAX(windspeed) as maxwind, count(if (avgspeed<0.8, avgspeed,0)) as no_cases 
from towerdata 
where datetime between '2013-01-01 00:00:00' and '2013-01-01 23:00:00'

I would like to get the 'datetime' value on which the the windspeed was equal to maxwind. How to frame the sql?

My purpose is to get value of maximum wind speed and ot what time the wind blew at this speed. Also no of times when wind was less than 0.8 m/s. I can use two separate select statement, but want to reduce the lines

Order by the windspeed and take the first record only

SELECT datetime
from towerdata 
where datetime between '2013-01-01 00:00:00' and '2013-01-01 23:00:00'
order by windspeed desc
limit 1

Here is one approach, using a subquery in the where clause:

select max(windspeed) as max_windspeed, count(*)
from towerdata td
where datetime between '2013-01-01 00:00:00' and '2013-01-01 23:00:00' and
      windspeed = (select max(windspeed) as maxws
                   from towerdata
                   where datetime between '2013-01-01 00:00:00' and '2013-01-01 23:00:00'
                  )

EDIT:

I realize that you want a separate count, so use a join:

select max(td.maxws) as max_windspeed,
       max(case when td.windspeed = td.maxws then td.datetime end) as maxws_datetime,
       sum(case when td.avgspeed < 0.8 then td.avgspeed else 0 end)
from towerdata td left outer join
     (select max(windspeed) as maxws
      from towerdata
      where datetime between '2013-01-01 00:00:00' and '2013-01-01 23:00:00'
     ) tdmax
     on td.windspeed = tdmax.windspeed
where datetime between '2013-01-01 00:00:00' and '2013-01-01 23:00:00';

By the way, the expression:

count(if (avgspeed<0.8, avgspeed,0))

probably isn't doing what you want. It counts up the number of rows, the same as count(*) . count() returns the number of non-NULL values. That is why I replaced it with a case .

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