栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

SQL | 多表连接/窗口函数 | 牛客SQL79/80/81 牛客的课程订单分析(三)/(四)/(五)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SQL | 多表连接/窗口函数 | 牛客SQL79/80/81 牛客的课程订单分析(三)/(四)/(五)

题目1

https://www.nowcoder.com/practice/4ae8cff2505f4d7cb68fb0ec7cf80c57?tpId=82&&tqId=37917&rp=1&ru=/activity/oj&qru=/ta/sql/question-ranking

思路

第一种,不使用窗口函数

select o1.*
from order_info o1 
inner join 
	(select user_id
	from order_info
	where date>'2025-10-15'  # 限定条件3个
	and status='completed'
	and product_name in ('C++','Java','Python')
	group by user_id
	having count(*)>=2) o2
on o1.user_id =o2.user_id 
where  o1.date>'2025-10-15'  # o1中同样要限定3个条件
and o1.status='completed'
and o1.product_name in ('C++','Java','Python')
order by id

第二种,使用窗口函数

select id,user_id,product_name,status,client_id,date
from (select *,count(*) over(partition by user_id) as co
     from order_info
     where date>'2025-10-15'  # 限定条件3个
     and status='completed'
     and product_name in ('C++','Java','Python')) o
where co>=2
order by id
题目2

https://www.nowcoder.com/practice/c93d2079282f4943a3771ca6fd081c23?tpId=82&tqId=37917&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fsql%2Fquestion-ranking

思路

在上一题基础上,使用窗口函数相对比较简单

select user_id,min(date) as first_buy_date,count(*) as cnt
from (select *,count(*) over(partition by user_id) as co
     from order_info
     where date>'2025-10-15'  # 限定条件3个
     and status='completed'
     and product_name in ('C++','Java','Python')) o
where co>=2
group by user_id
题目3

https://www.nowcoder.com/practice/348afda488554ceb922efd2f3effc427?tpId=82&tqId=37917&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fsql%2Fquestion-ranking

思路

第一种,使用窗口函数lead() over()

select  user_id,
        min(date) as first_buy_date,
        second_buy_date,
        cnt
from (select *,
          lead(date) over(partition by user_id order by date) as second_buy_date,
          count(*) over(partition by user_id) as cnt
     from order_info
     where date>'2025-10-15'  # 限定条件3个
     and status='completed'
     and product_name in ('C++','Java','Python')) o
where cnt>=2
group by user_id

第二种,对日期排序,取排名前2位的日期,最小的日期为first_buy_date,最大的日期为second_buy_date

select  user_id,
        min(date) as frist_buy_date,
        max(date) as second_buy_date,
        cnt
from (select *,
          row_number() over(partition by user_id order by date) as rn,
          count(*) over(partition by user_id) as cnt
     from order_info
     where date>'2025-10-15'  # 限定条件3个
     and status='completed'
     and product_name in ('C++','Java','Python')) o
where cnt>=2 and rn<=2
group by user_id
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/308057.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号