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;
select country,gender,count(*) from customer_details group by country,gender;
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;
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;