暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

SQL解决实际问题(3)

牛谈琴 2021-08-13
521

主要记录实际应用SQL中出现的问题并加以记录。

1.行列转换

行列转化不仅在面试中经常被考到,同时在一些其他场景中也会经常应用。行列转换是一个重要的知识点。

通常来说,我们既要用到 行转化成列,同时也要掌握 列转化成行

首先介绍一下纵表转横表

数据的处理和分析,金融的报表

  • 纵表转横坐标

首先介绍数据结构,数据结构如下:

我们要转成长截面的面板数据

我们可以记住基本的步骤:

1.根据名称进行分组:

2.decode函数进行选取

1.先根据名称进行分组

select username from 行列 group by username

复制

2.decode 函数

decode
函数的基本用法可以参照如下:

case 字段
  when 值1 then 结果2
  when 值2 then 结果2
  ....
  else 结果n
end

复制

所以在命令中可以记录如下:

select username,
   sum(case course when 'mysql' then score else 0 end) mysql,
   sum(case course when 'hive' then score else 0 end) hive,
   sum(case course when 'python' then then score 0 end) python
from 行列
group by username;

复制

另外有一种比较野蛮的用法使用 group_concat()
用法:

3.group_concat():字段值合并

select username,group_concat(course),group_concat(score) 
from 行列
group by username;

复制

输出结果为:

  • 横表转纵表

首先做成一个视图

create view vstu as select username,
sum(case course when 'mysql' then score else 0 end) mysql,
sum(case course when 'hive' then score else 0 end) hive,
sum(case course when 'python' then score else 0 end) python
from 行列
group by username;


select * from vstu;

复制

第一步:

select username,mysql score from vstu;

复制

第二步:进行下一步的修改

select username,'mysql' course,mysql score from vstu;

复制

course
做为字段进行说明,mysql
是需要的统计课程分数。

第三步:把结果合并在一起:

select username,'mysql' course,mysql score from vstu
union all
select username,'hive' course,hive score from vstu
union all
select username,'python' course,python score from vstu;

复制

3 合并表进行总结

前段时间需要帮同事一个忙,进行数据的比对,后来发现其实是一个很简单的问题。问题描述如下:

需要从表A中将表B中出现的问题清除掉

<<< 左右滑动见更多 >>>

思路如下:

1.先找出多余表和主表共有的数据

2.从主表中排除这些数据即可

第一步:找出两张表共有的号码:

select 主表.手机号 from 主表 inner join 
多余表
on 主表.`手机号` = 多余表.`手机号`;

复制

输出结果为(保密需要清除后面两位):

159274287
187711227
183270448
189723912
150726977

复制

第二步:从主表主排除这些共同数据即可:

select * from 主表 where 主表.`手机号` not in (
select 主表.手机号 from 主表 inner join 
多余表
on 主表.`手机号` = 多余表.`手机号`);

复制

输出结果为:

总结:

目需要用到一个子查询,其二是一个自连接问题。然后再解决问题。

文章转载自牛谈琴,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论