SQL81 牛客的课程订单分析(五)
代码
select
T.user_id,
min(T.date),
max(case when T.date_rank=2 then T.date end),
count(T.user_id) cnt
from (select rank() OVER (partition by user_id order by date) date_rank,
date,
user_id
from order_info
where order_info.status = 'completed' and order_info.date >= '2025-10-16'
and (order_info.product_name in ('C++','Python','Java'))) T
group by T.user_id
having count(T.user_id) >= 2
order by T.user_id;
知识点
代码中:
max(case when T.date_rank=2 then T.date end),
用聚合函数可以实现行转列 ( 这里min()或max()都可以)
SQL70 牛客每个人最近的登录日期(五)
代码
select
a.date,
round(count(b.user_id)*1.0/count(a.user_id),3) as p
from (select id,
user_id,
client_id,
date,
min(date)
from login
group by user_id) a
left join login b
on a.user_id = b.user_id and b.date = date(a.date, '+1 day')
group by a.date
UNION
SELECT date, 0.000 AS p
FROM login
WHERE date NOT IN (
SELECT MIN(date)
FROM login
GROUP BY user_id)
ORDER BY date;
知识点
UNION用于纵向合并table
SQL82 牛客的课程订单分析(六)
代码
select
T.id,
T.is_group_buy,
T.client_name
from (select
t1.id id,
t1.is_group_buy is_group_buy,
t2.name client_name,
count(t1.user_id) over (partition by t1.user_id) coun_ind
from order_info t1
left join client t2 on t1.client_id = t2.id
where t1.date > '2025-10-15' and t1.status = 'completed' and t1.product_name in ('C++','Java','Python')) T
where coun_ind >= 2
order by T.id;
知识点
group by配合聚合函数,用来筛选掉一些record
partition by放在聚合函数后面,并不会筛选掉一些record
学会判断什么时候用group by 什么时候用partition by
SQL86 实习广场投递简历分析(三)
代码
select x.job,
t1,
cnt1,
t2,
cnt2
from (select job,
substr(date,1,7) t1,
sum(num) cnt1
from resume_info
where date like '%2025%'
group by job,t1) x
join (select job,
substr(date,1,7) t2,
sum(num) cnt2
from resume_info
where date like '%2026%'
group by job,t2) y
on x.job=y.job and substr(x.t1,5,3)=substr(y.t2,5,3)
order by t1 desc,x.job desc;
知识点
-
substr()函数
- substr() 函数返回字符串的一部分。substr(string,start,length)
- string - 指定的要截取的字符串。
- start - 必需,规定在字符串的何处开始。
- 正数 - 在字符串的指定位置开始
- 负数 - 在从字符串结尾的指定位置开始
- 0 - 在字符串中的第一个字符处开始
- length - 指定要截取的字符串长度。
- substr() 函数返回字符串的一部分。substr(string,start,length)
-
使用like子句来进行匹配/模糊匹配
- ‘%a’ //以a结尾的数据
- ‘a%’ //以a开头的数据
- ‘%a%’ //含有a的数据
- ‘a’ //三位且中间字母是a的
- ‘_a’ //两位且结尾字母是a的
- ‘a_’ //两位且开头字母是a的