数据库行转列、列转行方法以及代码实现

MySql

行转列
将图1做成图2的效果
图1:
数据库行转列、列转行方法以及代码实现_第1张图片
图2:
数据库行转列、列转行方法以及代码实现_第2张图片
创建数据表:

CREATE TABLE `TEST_TB_GRADE` (
  `ID` int(10) NOT NULL AUTO_INCREMENT,
  `USER_NAME` varchar(20) DEFAULT NULL,
  `COURSE` varchar(20) DEFAULT NULL,
  `SCORE` float DEFAULT '0',
  PRIMARY KEY (`ID`)
) ;

导入数据:

insert into TEST_TB_GRADE(USER_NAME, COURSE, SCORE)  values
("张三", "数学", 34),
("张三", "语文", 58),
("张三", "英语", 58),
("李四", "数学", 45),
("李四", "语文", 87),
("李四", "英语", 45),
("王五", "数学", 76),
("王五", "语文", 34),
("王五", "英语", 89);

行转列代码实现:

select username,
	max(case course when '数学' then score else 0 end) 数学,
	max(case course when '语文' then score else 0 end) 语文,
	max(case course when '英语' then score else 0 end) 英语
from test_tb_grade
group by username;

hive

原效果:
数据库行转列、列转行方法以及代码实现_第3张图片
代码实现:

select country,gender,count(*) from customer_details group by country,gender;

行转列效果:
方法一、
数据库行转列、列转行方法以及代码实现_第4张图片
代码实现:

select country,
	sum (case gender when 'Male' then 1 else 0 end) as male,
	sum (case gender when 'Female' then 1 else 0 end) as female
from customer_details group by country;

方法二、
数据库行转列、列转行方法以及代码实现_第5张图片
代码实现:

with
t1 as (select country,size(collect_list(gender)) as male from customer_details where gender='Male' group by country),
t2 as (select country,size(collect_list(gender)) as Female from customer_details where gender='Female' group by country)
select t1.country,t1.male,t2.Female from t1 inner join t2 on t1.country=t2.country;

你可能感兴趣的:(HIVE,mysql)