zoukankan      html  css  js  c++  java
  • mysql分组排序取最大值所在行,类似hive中row_number() over partition by

     如下图, 计划实现 :按照 parent_code 分组, 取组中code最大值所在的整条记录,如红色部分。(类似hive中: row_number() over(partition by))

    select c.* from
    (   select a.*, (@i := case when @key_i=parent_code then @i+1 else 1 end) as sort_num,(@key_i:=parent_code) as tmp 
            from my_test a, (SELECT  @i := 0,@key_i:='') b
            order by parent_code,code desc) c 
    where c.sort_num=1;

    个人理解, mysql 运行顺序:  from >>  where >> order by >> select .

    以下部门应该有助于理解mysql中变量的概念。

    1.=========================================================================================================

    仅按照code排序,加序号sort_num效果如下:  

    select (@i := @i + 1) as sort_num, a.*  
        from my_test a, (SELECT  @i := 0) b
        order by code;

    2.=========================================================================================================

    仅按parent_code分组,按照code排序,加序号.

    select a.*, (@i := case when @key_i=parent_code then @i + 1 else 1 end) as sort_num,(@key_i:=parent_code) as tmp 
        from my_test a, (SELECT  @i := 0,@key_i:='') b
        order by parent_code,code desc;

     

    参考链接 :https://blog.csdn.net/zzhhoubin/article/details/79839610

    https://www.cnblogs.com/CharlieLau/p/6737243.html

    https://blog.csdn.net/u011728683/article/details/78594070

  • 相关阅读:
    解决Xcode升级7.0后,部分.a静态库在iOS9.0的模拟器上,link失败的问题
    2014年工作总结
    工作还是事业
    海豚社区阶段性开发总结
    Xcode开发和调试总结
    iOS证书深究
    何为分类,UIImageView举例
    UIWebView的探索
    SugarSync网盘之NSDateFormatter
    ASP.NET程序从IIS6移植到IIS7时出现500.22错误(转)
  • 原文地址:https://www.cnblogs.com/andylhc/p/10216626.html
Copyright © 2011-2022 走看看