mysql - mysql分组排序

参考:https://www.cnblogs.com/john8169/p/9780471.html

说明:关键在于@pdept如何赋值。了解@pdept的赋值之后,立马就能明白rank(名次)的由来。

create table yida_sts.temp_hlq_user_sold_03 as  
select 
       User_Id
      ,Buyer_Fullname
      ,Buyer_Phone_Number
      ,Buyer_Email
      ,Sale_Date
      ,buy_times
      ,sum_price
      ,sku
      ,model
      ,rank 
from (  
       select b.*
            -- 行号
       	,@rownum:=@rownum+1     
            -- 处理排名,如果@pdept等于user_id,则表示@pdept被初始化,将@rank自增1
         ,if(@pdept=b.User_Id and @pdept2=b.Buyer_Fullname,@rank:=@rank+1,@rank:=1) as rank
         -- 初始化@pdept,@pdept为中间变量,在rank之后初始化,所以rank初始化时
         -- @pdept为null或者是上一user_id的值
           ,@pdept:=b.User_Id    
           ,@pdept2:=b.Buyer_Fullname
      from (  
          select a.*
          from temp_hlq_user_sold_02 a 
         order by user_id asc,Buyer_Fullname asc ,Buyer_Phone_Number asc,
         Buyer_Email asc,sale_date DESC  
          ) b 
       -- 初始化信息表
      ,(select @rownum :=0 , @pdept := null ,@pdept2 := null,@rank:=0) c 
     ) result  
;

猜你喜欢

转载自blog.csdn.net/helunqu2017/article/details/113816059