MySQL 转置结果集以利于跨行计算

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

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

一.需求

对来自多个行的数据进行计算。
为便于计算,可以把这些行转置到列中,这样所有需要的值都包含于1行中。

deptno 20 是总工资最高的部门,执行下列查询可以确认这一列:

mysql> select deptno, sum(sal) as sal
-> from emp
-> group by deptno;
±-------±---------+
| deptno | sal |
±-------±---------+
| 10 | 8750.00 |
| 20 | 10875.00 |
| 30 | 9400.00 |
±-------±---------+
3 rows in set (0.00 sec)

现在要计算deptno 20 和deptno 10之间以及deptno 20 和deptno 30 之间的总工资之差。

二.解决方案

使用聚集函数sum及case表达式转换总和,然后,在select列表中编写表达式:

select  d20_sal - d10_sal as d20_10_diff,
        d20_sal - d30_sal as d20_30_diff
  from  (
select  sum(case when deptno = 10 then sal end) as d10_sal,
        sum(case when deptno = 20 then sal end) as d20_sal,
        sum(case when deptno = 30 then sal end) as d30_sal
  from  emp
        ) totals_by_dept;

测试记录:

mysql> select  d20_sal - d10_sal as d20_10_diff,
    ->         d20_sal - d30_sal as d20_30_diff
    ->   from  (
    -> select  sum(case when deptno = 10 then sal end) as d10_sal,
    ->         sum(case when deptno = 20 then sal end) as d20_sal,
    ->         sum(case when deptno = 30 then sal end) as d30_sal
    ->   from  emp
    ->         ) totals_by_dept;
+-------------+-------------+
| d20_10_diff | d20_30_diff |
+-------------+-------------+
|     2125.00 |     1475.00 |
+-------------+-------------+
1 row in set (0.00 sec)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值