简体   繁体   中英

mysql select sum, max, and another column value at the same row which the max value stays

Sample table:

uid time_stp                traf
1   2016-01-13 00:00:00     6
1   2016-01-13 05:00:00     8
1   2016-01-13 10:00:00     14
1   2016-01-13 15:00:00     26
1   2016-01-13 20:00:00     42
...

My SQL:

select
    uid,
    from_unixtime(floor(unix_timestamp(time_stp)/3600) * 3600) as tm,
    sum(traf),
    max(traf),
    -- xxx as max_traf_time
from
    group_by_time_range
group by
    uid, tm;

I want to sum the traf hourly, and find the max traf with corresponding time_stp in each hour section. How could I use a single SQL statement to finish this stuff.

Have you tryed

select
    T1.uid,
    from_unixtime(floor(unix_timestamp(time_stp)/3600) * 3600) as tm,
    sum(traf),
    (
     SELECT max(traf)
     FROM group_by_time_range T2
     WHERE T2.uid = T1.uid
    ) as Max_Traf,
    (
     SELECT time_stp
     FROM group_by_time_range T3
     WHERE traf = Max_Traf
    ) as max_traf_time
from
    group_by_time_range T1
group by
    uid, tm;

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