Mysql 行转列

select username,count(1) from T_CheckData group by username;

/*=====确定列 第一种=====*/
select sum(case username when '郭二' then 1 else 0 END) as 郭二,
sum(case username when '张三' then 1 else 0 END) as 张三,
sum(case username when '李四' then 1 else 0 END) as 李四,
sum(case username when '王五' then 1 else 0 END) as 王五
 from T_CheckData ;

/*=====确定列 第二种=====*/
select sum(if(username='郭二',1,0)) as 郭二,
sum(if(username='张三',1,0)) as 张三,
sum(if(username='李四',1,0)) as 李四,
sum(if(username='王五',1,0)) as 王五
 from T_CheckData ;


/*=====不确定列=====*/
/*=====【username】替换为你想要的动态列值=====*/
/*=====【state】替换为用于合计的数值=====*/
/*=====【weight】替换为你的分类值(一般为日期)=====*/
/*=====【T_CheckData】替换为表名=====*/
SET @EE='';
set @str_tmp='';
SELECT @EE:=CONCAT(@EE,'SUM(IF(username=\'',username,'\'',',state,0)) AS ',username,',') as aa into @str_tmp FROM (SELECT DISTINCT username FROM T_CheckData) A order by length(aa) desc limit 1; 
SET @QQ=CONCAT('SELECT ifnull(T_CheckData.weight,\'total\') as 分类,',LEFT(@str_tmp,char_length(@str_tmp)-1),'  ,SUM(state) AS TOTAL FROM T_CheckData GROUP BY weight WITH ROLLUP');
PREPARE stmt  FROM @QQ; 
EXECUTE stmt ;
deallocate prepare stmt;

 

转载于:https://www.cnblogs.com/shengwei/p/5706919.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值