代码之家  ›  专栏  ›  技术社区  ›  developer

使用group by获取max value数据的SQL查询

  •  0
  • developer  · 技术社区  · 7 年前

    我有下表:

    Date         Id    Count
    2018-09-01   100   50   
    2018-09-01   101   60
    2018-09-01   102   55
    2018-09-02   103   40
    2018-09-02   104   30
    2018-09-02   105   20
    2018-09-02   106   10
    2018-09-03   107   30
    2018-09-03   108   70
    

    我想获取每个日期的最大ID行及其最大ID的计数列。

    结果表:

    Date         Id    Count
    2018-09-01   102   55   
    2018-09-02   106   10
    2018-09-03   108   70
    

    要得到这个结果,SQL查询应该是什么?

    谢谢。

    3 回复  |  直到 7 年前
        1
  •  8
  •   Yogesh Sharma    7 年前

    使用 row_number() :

    select top (1) with ties t.*
    from table t
    order by row_number() over (partition by date order by cnt desc);
    
        2
  •  1
  •   Gordon Linoff    7 年前

    你不需要聚合,你需要过滤。

    select t.*
    from t
    where t.count = (select max(t2.count) form t t2 where t2.date = t.date);
    
        3
  •  1
  •   Eray Balkanli    7 年前

    我认为使用self-join是另一种选择:

    select t.*
    from table t
    inner join (select Date, max(t.ID) as DID from table t group by Date) t2
    on t.Date = t2.Date and t.ID = t2.DID