mysql - 如何对mysql中已经求和的别名列进行求和

标签 mysql sum alias

我有 mysql 查询。

select d.department_id,d.department_name,sum(e.salary) AS amount
from department d inner join employee e on d.department_id=e.department_id
group by d.department_id,d.department_name

我通过使用此查询获得总计。

select d.department_id,d.department_name,sum(e.salary) AS amount
from department d inner join employee e on d.department_id=e.department_id
group by d.department_id,d.department_name WITH ROLLUP

但我想要这样的总金额列别名,如下

select d.department_id,d.department_name,sum(e.salary) AS amount, sum(SELECT(amount)) AS grand_total
from department d inner join employee e on d.department_id=e.department_id
group by d.department_id,d.department_name

我的数据库结构是。

enter image description here

我的 table 是

enter image description here

但我想要这样。

enter image description here

请帮助我任何人。

最佳答案

如果您想要附加列,请使用连接或子查询:

select d.department_id, d.department_name, sum(e.salary) AS amount,
       tot.salary
from department d inner join
     employee e
     on d.department_id = e.department_id inner join
     (select sum(e.salary) as salary from employee) tot
group by d.department_id, d.department_name, tot.salary;

注意:这假设员工表中的总计是您想要的总计。这似乎是一个合理的假设,但如果某些员工没有部门或某些员工在多个部门工作,则可能不准确。在这种情况下,您只需在子查询中重复 joindepartment 即可。

关于mysql - 如何对mysql中已经求和的别名列进行求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28516904/

相关文章:

mysql - 避免表中的列标题冲突加入 peewee

linux - 如何设置永久别名

algorithm - 绝对值之和的最小值

java - 检索触发器生成的主键 (Java)

php - 按值获取记录或获取最后一条记录

Mysql行间差异

具有相同引用编号的 PHP 求和

javascript - javascript中每一行的总和

Git 别名 - 多个命令和参数

mysql - linux env 上的 grails 部署中的 BeanCreationException