hvie函数求转换行列

mysql 查询结果转置_MySQL 将结果集转置为一行

一.需求

希望将几个行组中的数据转换成几行中的列,每个原来的行组转换成一行。

例如,下面的结果集显示了每个部门中员工的数目:

deptno cnt

10 3

20 5

30 6

希望重新设置输出格式,使其结果集看起来如下:

deptno_10 deptno_20 deptno_30

3 5 6
————————————————
版权声明:本文为CSDN博主「weixin_39526238」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_39526238/article/details/113711123

使用sum汇总、case进行判断

select sum(case when deptno = 10 then 1 else 0 end) as deptno_10,

sum(case when deptno = 20 then 1 else 0 end) as deptno_20,

sum(case when deptno = 30 then 1 else 0 end) as deptno_30

from emp

order by 1;
————————————————
版权声明:本文为CSDN博主「weixin_39526238」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_39526238/article/details/113711123

 

解决方案2

使用max及case函数

select max(case when deptno = 10 then empcount else null end) as deptno_10,

max(case when deptno = 20 then empcount else null end) as deptno_20,

max(case when deptno = 30 then empcount else null end) as deptno_30

from (

select deptno, count(*) as empcount

from emp

group by deptno

) x;
————————————————
版权声明:本文为CSDN博主「weixin_39526238」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_39526238/article/details/113711123

posted @ 2021-11-09 18:00  faithtwo  阅读(48)  评论(0)    收藏  举报