gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:00:27 25 4
gpt4 key购买 nike

我有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com