MySQL 反向转置结果集

本文介绍了如何在MySQL8.0中将具有多列存储的非规范化数据转换为行存储。通过使用笛卡尔积和CASE函数,可以实现从列deptno_10, deptno_20, deptno_30到行deptno和counts_by_dept的转换。示例SQL脚本展示了具体的转换过程,并给出了测试结果,成功地将数据转换为期望的格式。
摘要由CSDN通过智能技术生成

备注:测试数据库版本为MySQL 8.0

如需要scott用户下建表及录入数据语句,可参考:
scott建表及录入数据sql脚本

一.需求

把列转换为行。
±----------±----------±----------+
| deptno_10 | deptno_20 | deptno_30 |
±----------±----------±----------+
| 3 | 5 | 6 |
±----------±----------±----------+

要把它转换为:
±-------±---------------+
| deptno | counts_by_dept |
±-------±---------------+
| 10 | 3 |
| 20 | 5 |
| 30 | 6 |
±-------±---------------+

二.解决方案

检验想要的结果集,很容易明白,对表EMP执行简单的count和group by,就能产生想要的结果。
尽管如此,这里的目的是假设数据按行存储,也许数据是以多列存储、非规范化和聚集过的值。

用笛卡尔积加上case函数即可

select dept.deptno,
       case dept.deptno
            when 10 then emp_cnts.deptno_10
            when 20 then emp_cnts.deptno_20
            when 30 then emp_cnts.deptno_30
       end as counts_by_dept
  from (
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
       ) emp_cnts,
       ( select deptno from dept where deptno <= 30) dept
;

测试记录:

mysql> select dept.deptno,
    ->        case dept.deptno
    ->             when 10 then emp_cnts.deptno_10
    ->             when 20 then emp_cnts.deptno_20
    ->             when 30 then emp_cnts.deptno_30
    ->        end as counts_by_dept
    ->   from (
    -> 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
    ->        ) emp_cnts,
    ->        ( select deptno from dept where deptno <= 30) dept;
+--------+----------------+
| deptno | counts_by_dept |
+--------+----------------+
|     10 |              3 |
|     20 |              5 |
|     30 |              6 |
+--------+----------------+
3 rows in set (0.00 sec)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值