sql使用中的一些固定语法

时间:2022-01-08 02:38:46

#sql求分组后 组内排名前几--每个uid在9月份登录的前七天,与后7天(分别计算,不足7天的取全部)

SELECT * from ( SELECT  
 uid,
 day,
 @ROW := case when @cid=uid then @ROW 1 else 1 END rn, 
 @cid := uid
from 
(
  SELECT uid,day  from 
  ods_app_action_login_h 
  where day>="2019-09-01" and day <="2019-09-30" and uid <>‘‘  
      GROUP BY day,uid ORDER BY uid,day desc
) l1,(SELECT @ROW := 0,@cid :=0) l2) l5
where rn <=7

--第二种
SELECT uid,day 
from ods_app_action_login_h as o1 
where day>="2019-09-27" and day<="2019-09-30" and 
 (
    SELECT count(*) from 
    (
       SELECT uid,day from ods_app_action_login_h where 
      day>="2019-09-27" and day<="2019-09-30" GROUP BY uid,day
      ) as o 
    where  o1.uid= o.uid and o.day <=o1.day   --分组排序
 ) <= 7