Leetcode SQL精选题(六)

257 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

30.not in

select

distinct buyer_id

from sales

where product_id=1 and 
buyer_id    #这里一定要写buyer_id!

not in (

    select buyer_id from sales where product_id=3

)

如果不写的话,就会因为筛选出每一行都不为空,最后会导致not in就没有用

30.日期加减

如果是做日期差的话直接做datediff(day1,day2)就可以

now()       //now函数为获取当前时间

select date_add(now(), interval 1 day); - 加1天

select date_add(now(), interval 1 hour); -加1小时

select date_add(now(), interval 1 minute); - 加1分钟

select date_add(now(), interval 1 second); -加1秒

select date_add(now(), interval 1 microsecond);-加1毫秒

select date_add(now(), interval 1 week);-加1周

select date_add(now(), interval 1 month);-加1月

select date_add(now(), interval 1 quarter);-加1季

select date_add(now(), interval 1 year);-加1年

MySQL adddate(), addtime()函数,可以用date_add() 来替代。

MySQL date_sub() 日期时间函数 和date_add() 用法一致。

MySQL 中subdate(),subtime()函数,建议,用date_sub()来替代。

31.group by 和通过窗口函数做额区别qu'b:

select

player_id,

min(event_date) over(partition by player_id) event_date1

from activity

select

player_id,

min(event_date)  event_date1

from activity

group by player_id

不同之处就在于窗口函数是不支持distinct的,做出了有问题

32.计算人数比例的做法,可以参考一下力扣的这道题:leetcode.cn/problems/ga…

Image.png 两种解法都很精妙:

select a1.install_dt,

       count(*) installs,

       round(count(a2.event_date)/count(*),2) Day1_retention

from(

    select player_id,min(event_date) install_dt

    from Activity

    group by player_id

) a1

left join Activity a2        #join不行,必须配合上面的count一起使用--->如果是null就count不进去

    on a1.player_id = a2.player_id and datediff(a2.event_date,a1.install_dt)=1group by a1.install_dt

select first_date as install_dt,

count(distinct player_id) as installs,

round(sum(if(datediff(event_date,first_date)=1,1,0))/count(distinct player_id),2)      
#老规矩,sum妙用

as Day1_retention

from

(

    select player_id,event_date,min(event_date) over(partition by player_id) as first_date

    from activity

)tmp

group by first_date