行转列 && 字段拆分

Posted on 2021-07-06 15:39  打杂滴  阅读(208)  评论(0编辑  收藏  举报

explode称之为Hive爆炸函数,意思就是将一行数据炸开。
Usage:explode(array/map) explode函数传递的参数必须是一个array或者是map

 

hive
scala> spark.sql("select explode(split('41,52,62,35&98','[,&]')) numlist").show
+-------+
|numlist|
+-------+
| 41|
| 52|
| 62|
| 35|
| 98|
+-------+

MySQL

substring_index(str,delim,count) 说明:substring_index(被截取字段,关键字,关键字出现的次数) 

表help_topic的字段help_topic_id为一个0起始的自增列,'aaa,bbb,dddd,yyy,uuu,eee'中的,被替换后,减少了5个分隔符,substring_index按,号出现的位置,截取了6次,得到的结果如下,然后使用substring_index,获取,最后一次出现的位置截取最后一个字符串分割

mysql> select help_topic_id,substring_index('aaa,bbb,dddd,yyy,uuu,eee',',',help_topic_id+1) from mysql.help_topic where help_topic_id<length('aaa,bbb,dddd,yyy,uuu,eee')+1-length(replace('aaa,bbb,dddd,yyy,uuu,eee',',','')) ;
+---------------+-----------------------------------------------------------------+
| help_topic_id | substring_index('aaa,bbb,dddd,yyy,uuu,eee',',',help_topic_id+1) |
+---------------+-----------------------------------------------------------------+
| 0 | aaa |
| 1 | aaa,bbb |
| 2 | aaa,bbb,dddd |
| 3 | aaa,bbb,dddd,yyy |
| 4 | aaa,bbb,dddd,yyy,uuu |
| 5 | aaa,bbb,dddd,yyy,uuu,eee |
+---------------+-----------------------------------------------------------------+
6 rows in set (0.00 sec)

mysql> select help_topic_id,substring_index(substring_index('aaa,bbb,dddd,yyy,uuu,eee',',',help_topic_id+1),',',-1) from mysql.help_topic where help_topic_id<length('aaa,bbb,dddd,
+---------------+-----------------------------------------------------------------------------------------+
| help_topic_id | substring_index(substring_index('aaa,bbb,dddd,yyy,uuu,eee',',',help_topic_id+1),',',-1) |
+---------------+-----------------------------------------------------------------------------------------+
| 0 | aaa |
| 1 | bbb |
| 2 | dddd |
| 3 | yyy |
| 4 | uuu |
| 5 | eee |
+---------------+-----------------------------------------------------------------------------------------+
6 rows in set (0.00 sec)

 

sqlserver 行转列 列转行

create table stu_score
(
name varchar(100),
math_score int,
ch_score int,
en_sore int
)

insert into stu_score
select 'tian',80,90,86
union
select 'liu',98,78,67
union
select 'wang',75,79,65

--列转行

select name,'math_score' cource,math_score
from stu_score
union
select name,'ch_score' cource,ch_score
from stu_score
union
select name,'en_sore' cource,en_sore
from stu_score

 

 

--行转列

select name,max(case cource when 'math_score' then math_score else 0 end) math_score
,max(case cource when 'ch_score' then math_score else 0 end) ch_score
,max(case cource when 'en_sore' then math_score else 0 end) en_sore from (
select name,'math_score' cource,math_score
from stu_score
union
select name,'ch_score' cource,ch_score
from stu_score
union
select name,'en_sore' cource,en_sore
from stu_score)a
group by name

 

Copyright © 2024 打杂滴
Powered by .NET 8.0 on Kubernetes