簡體   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