编写 Hive 的 HQL 语句来实现以下结果:表中的 1 表示选修,表中的 0 表示 未选修

编写 Hive 的 HQL 语句来实现以下结果:表中的 1 表示选修,表中的 0 表示 未选修,第1张

编写 Hive 的 HQL 语句来实现以下结果:表中的 1 表示选修,表中的 0 表示 未选修 二、求学生选课情况 1 、数据说明 ( 1 )数据格式 id course 1,a 1,b 1,c 第 3 页 共 5 页 1,e 2,a 2,c 2,d 2,f 3,a 3,b 3,c 3,e ( 2 )字段含义 表示有 id 为 1,2,3 的学生选修了课程 a,b,c,d,e,f 中其中几门。 2 、需求 编写 Hive 的 HQL 语句来实现以下结果:表中的 1 表示选修,表中的 0 表示 未选修 id  a  b  c  d  e  f 1  1  1  1  0  1  0 2  1  0  1  1  0 1 3  1   1  1  0 1  1 解题思路,主要用到case when这个知识点,其余建表、导入数据都是寻常 *** 作 第一步,建表,主要按照导入数据的逗号分割
create table if not exists  t_course(
   id  int,
   course  string
)
row format delimited fields terminated by ',';

第二步,载入数据,注意文件目录,不要照搬
load data local inpath  '/opt/tmp/test/course.txt' into table  t_course;

第三步,创建一个新表,对原有表的数据进行处理
create  table  id_courses as select t1.id as id,t1.course as id_course,t2.course course
from(select id as id,collect_set(course) as course from t_course group by id) t1
join ( select  collect_set(course) as course from t_course )t2;

第4步,用case when 解决
select id,
       case when array_contains(id_course,course[0]) then 1 else  0 end as a,
       case when array_contains(id_course,course[1]) then 1 else 0 end as b,
       case when array_contains(id_course,course[2]) then 1 else  0 end as c,
       case when array_contains(id_course,course[3]) then 1 else 0 end as d,
       case when array_contains(id_course,course[4]) then 1 else  0 end as e,
       case when array_contains(id_course,course[5]) then 1 else 0 end as f
       from id_courses;

最后,得到答案,如图所示

 乐于奉献共享,帮助你我他!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5575244.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存