【问题标题】:MySQL: Select rows with max column value and corresponded datetime grouped by another columnMySQL:选择具有最大列值的行以及由另一列分组的对应日期时间
【发布时间】:2016-09-12 15:29:42
【问题描述】:

我的桌子是

IP  HITS    DATETIME
ip1 90      2016-09-10 01:15:37
ip2 13      2016-09-10 04:16:41
ip3 14      2016-09-10 05:17:41
ip2 12      2016-09-10 07:18:42
ip3 45      2016-09-10 09:19:42
ip1 88      2016-09-10 13:20:43
ip2 15      2016-09-10 15:21:43
ip3 26      2016-09-10 18:22:44

结果是

IP  HITS    DATETIME
ip1 90      2016-09-10 01:15:37
ip2 15      2016-09-10 15:21:43
ip3 45      2016-09-10 09:19:42

任何建议将不胜感激。

【问题讨论】:

标签: mysql sql database group-by greatest-n-per-group


【解决方案1】:

这是使用Correlated sub-query的一种方式

select * from yourtable a
where hits = (select max(hits) from yourtable b where a.IP = b.IP)

使用JOIN的另一种方式

SELECT a.IP,a.HITS,a.DATETIME
FROM   yourtable a 
       JOIN (SELECT Max(hits) AS max_hits, 
                    ip 
             FROM   yourtable 
             GROUP  BY ip) b 
         ON a.ip = b.ip 
            AND b.max_hits = a.hits 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    相关资源
    最近更新 更多