繁体   English   中英

MySQL选择总和,最大值,和最大值保持不变的同一行中的另一列值

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

样表:

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
...

我的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;

我要总结的traf小时,并找到最大traf相应time_stp在每个小时的部分。 我如何使用单个SQL语句来完成这些工作。

你试过了吗

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;

暂无
暂无

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

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