打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
有幸去华为面试数据分析岗,看到SQL后我拒绝了

◆ ◆ ◆  ◆ 



面试真题

今年8月,有幸参加了华为的面试,虽然是外包身份,但是大家都知道,大公司对于外包的面试其实就是华为内部人员来进行。腾讯也是如此!岗位是数据分析,记忆最深刻的就是考察了SQL行转列。SQL,无疑是在数据分析面试过程中的重头戏。很多人说,SQL不重要,不能只做提数机器;还有人说,面试不需要准备SQL,只要你懂方法就足够了。呵呵一笑置之!如果你真的懂数据分析的方法与思路,还愁找不到工作吗?还会整天迷茫?所以沉下心来,好好练习SQL吧。即使做个提数机器,也要做到提数又快又准确,否则和咸鱼有什么区别?!

SQL提数,准确性是第一位的。准确性如何把握?关键在于你的理解需求能力、逻辑思维能力、执行原理掌握的程度。需求理解出错,从根上就是不可能提取到需要的数据。SQL执行原理中,我认为一定要把SQL子句的执行顺序搞清楚。

在日常工作中,或者面试过程中,常常会碰到要求用SQL语句实现行转列。形式如下:

select * from test ;

而面试官要求查询结果如下展示:

或者这样:



case when方法

其实很简单~我们可以使用case when语句进行行转列操作。代码如下:

case 1

select  name ,        max(case when subject='语文' then score else 0  end) as 语文 ,        max(case when subject='数学' then  score else 0 end) as 数学 ,         max(case when subject='英语' then score else 0  end) as 英语 from test group by name ;

case 2

select name , sum(case when subject='语文' then score else 0 end) as 语文 , sum(case when subject='数学' then score else 0 end) as 数学 , sum(case when subject='英语' then score else 0 end) as 英语 from test group by name ;

以上两种代码都可以实现行转列,细心的同学可能会发现其实只有max和sum的区别。其实,max、sum最主要的用途就是聚合作用——以name分组聚合。为了让大家更好的理解sum或max的作用,我们先展现一下不加聚合函数的效果。

select  name ,        case when subject='语文' then score else 0  end as 语文 ,        case when subject='数学' then  score else 0 end as 数学 ,         case when subject='英语' then score else 0  end as 英语 from test ;

很明显,我们需要以name进行分组聚合,这样才能得到满足条件格式的输出。而用max还是sum进行聚合,没有任何区别。

求总分

select name , max(case when subject='语文' then score else 0 end) as 语文 , max(case when subject='数学' then score else 0 end) as 数学 , max(case when subject='英语' then score else 0 end) as 英语 , sum(score) as 总分 from test group by name ;


窗口函数方法


同时,再给大家介绍一下以窗口函数进行聚合的案例。代码如下:

select name ,       max(case when subject='语文' then score else 0 endoverpartition by name ) 语文 ,       max(case when subject='数学' then score else 0 endover( partition by name ) 数学 ,       max(case when subject='英语' then score else 0 endover( partition by name ) 英语 from test ;

同理,上面的聚合函数max也可以用sum替换,不再赘述!

很明显,结果需要去重!但是,在实际的生产过程中可能不需要去重,而且不是重复的,这个谜题留给大家思考!

select distinct name ,       sum(case when subject='语文' then score else 0 endoverpartition by name ) 语文 ,       sum(case when subject='数学' then score else 0 endover( partition by name ) 数学 ,       sum(case when subject='英语' then score else 0 endover( partition by name ) 英语 from test ;

通过上面的比较发现,不同情况使用不同的语句为好。如果你想查询更多字段,那么窗口函数不失为一种选择;如果只需要查询一个字段,如name,那么建议大家还是使用groupby为好。在实际生产中,查询字段远远不止一个,一般不会重复,所以也就不需要去重了。

结束语

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
使用 case when进行行列转换
sql如何行转列,列转行
sql 交叉表
(转)行变列SQL语句(MSSQL) - jack - 博客园
SQL 行转列,列转行
SQL综合应用学习
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服