简体   繁体   中英

How to get max value and corresponding date in SQL Server

I have a table of locations, dates, and altitude values. The query below is easy, but I'm trying to get min/max dates that correspond to the min/max values of altitude.

SELECT location, 
max(datetime) as max_date
COUNT(Altitude) as COUNT, 
AVG(Altitude) as AVG,
MIN(Altitude) as MIN,
max(Altitude) as MAX
FROM mydatabase
GROUP BY location

For every location select max and min altitude and max min datetime for them.

    select location, Altitude, min([datetime]) dtmin, max([datetime]) dtmax
    from (
       SELECT location, Altitude, [datetime]
           , min(Altitude) over(partition by location) as aMIN
           , max(Altitude) over(partition by location) as aMAX
       FROM mydatabase
    ) t
    where Altitude in (aMIN, aMAX)
    group by location, Altitude
    order by location, Altitude;

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