前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >HiveSql-微信运动在好友中的排名

HiveSql-微信运动在好友中的排名

作者头像
数据仓库晨曦
发布2024-01-08 15:43:03
1580
发布2024-01-08 15:43:03
举报
文章被收录于专栏:数据仓库技术数据仓库技术

一、题目

有两个表,朋友关系表user_friend,用户步数表user_steps。朋友关系表包含两个字段,用户id,用户好友的id;用户步数表包含两个字段,用户id,用户的步数

1.用户在好友中的排名

user_friend 数据

代码语言:javascript
复制
+----------+------------+
| user_id  | friend_id  |
+----------+------------+
| 1        | 2          |
| 1        | 3          |
| 2        | 1          |
| 2        | 3          |
| 2        | 4          |
| 3        | 1          |
| 3        | 4          |
| 4        | 2          |
| 4        | 3          |
| 5        | 2          |
| 5        | 3          |
| 5        | 4          |
+----------+------------+

user_friend数据

代码语言:javascript
复制
+---------------------+-------------------+
| user_steps.user_id  | user_steps.steps  |
+---------------------+-------------------+
| 1                   | 100               |
| 2                   | 95                |
| 3                   | 90                |
| 4                   | 80                |
| 5                   | 10                |
+---------------------+-------------------+

二、题目分析

维度

评分

题目难度

⭐️⭐️⭐️⭐️

题目清晰度

⭐️⭐️⭐️⭐️⭐️

业务契合度

⭐️⭐️⭐️⭐️⭐️

解法分析

1.要求解的是自己在好友中的排名,那么需要有自己和好友的步数,可是好友关系表中只有“好友”,需要加入自己的数据;

2.求排名,需要分组开窗;

3.需要筛选出自己名次的那一行数据;

三、SQL

1.列出好友步数,并将自己步数添加到结果中

代码语言:javascript
复制
--好友步数
select t1.user_id,t1.friend_id,t2.steps
from user_friend t1
join user_steps t2
on t1.friend_id = t2.user_id
union all
-- 自己步数
select user_id,user_id as friend_id,steps
from user_steps

查询结果如下:

2.按照用户分组,给每个用户的“好友”进行排名

代码语言:javascript
复制
select
  tt1.user_id,
  tt1.friend_id,
  tt1.steps,
  row_number()over(partition by tt1.user_id order by tt1.steps desc) as row_num
from
  (
  --好友步数
  select
    t1.user_id,
    t1.friend_id,
    t2.steps
  from user_friend t1 join user_steps t2
    on t1.friend_id = t2.user_id
  union all
  -- 自己步数
  select
    user_id,
    user_id as friend_id,
    steps
  from user_steps
  ) tt1

结果如下,我们最终需要的是红色框出来的行,所以再筛选出来,去掉非必要字段。

3求取最终结果

代码语言:javascript
复制
select
	user_id,
	row_num
from
	(
		select
			tt1.user_id,
			tt1.friend_id,
			tt1.steps,
			row_number()over(partition by tt1.user_id order by tt1.steps desc) as row_num
		from
		(
		--好友步数
		select
			t1.user_id,
			t1.friend_id,
			t2.steps
		from user_friend t1 join user_steps t2
		on t1.friend_id = t2.user_id
		union all
		-- 自己步数
		select
			user_id,
			user_id as friend_id,
			steps
		from user_steps
		) tt1
	)tt2
where user_id = friend_id

查询结果

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2023-06-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 数据仓库技术 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、题目
  • 二、题目分析
  • 三、SQL
    • 1.列出好友步数,并将自己步数添加到结果中
      • 2.按照用户分组,给每个用户的“好友”进行排名
        • 3求取最终结果
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档