mysql 列值与行值转换和统计

admin 阅读:34 2024-03-01

将 user_sample 表:

uid201608201609201610201611
张三iPhonemimiGoogle
李四mimiGoogleGoogle
王五GooglemiiPhoneiPhone

转为 phone_result 表:

uidiPhonemiGoogle
张三121
李四022
王五211

sql语句如下:

drop table if exists tmp;
drop table if exists phone_result;

create table tmp as select uid, `201608` as brand, `201608` as month from `user_sample`;
insert into tmp select uid, `201609` as brand, `201609` as month from `user_sample`;
insert into tmp select uid, `201610` as brand, `201610` as month from `user_sample`;
insert into tmp select uid, `201611` as brand, `201611` as month from `user_sample`;

create table phone_result as select distinct uid,
count(case brand when 'iPhone' then 1 end) as 'iPhone',
count(case brand when 'mi' then 1 end) as 'mi',
count(case brand when 'Google' then 1 end) as 'Google' from tmp group by uid;

drop table tmp;
声明

1、部分文章来源于网络,仅作为参考。
2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!