简体   繁体   English

对多列求和并在mysql中求和它们的别名

[英]Sum multiple columns and sum their alias in mysql

Is it possible to sum the columns and sum again?是否可以sum列,再次总结?

select 
id,
sum(t2.col) as cola,
sum(t3.col) as colb,
sum(t4.col) as colc,
sum(cola + colb + colc) as total
from t1
left join t2 on t2.id = t1.t2fk
left join t3 on t3.id = t1.t3fk
left join t4 on t4.id = t1.t4fk
group by t1.id

something like this像这样的东西

sum(cola + colb + colc) as total

You can't do it with aliases, but you can do it by re-writing the SELECT clauses, like this:你不能用别名来做到这一点,但你可以通过重写 SELECT 子句来做到,像这样:

select 
id,
sum(t2.col) as cola,
sum(t3.col) as colb,
sum(t4.col) as colc,
sum(t2.col) + sum(t3.col) + sum(t4.col) as total
from t1
left join t2 on t2.id = t1.t2fk
left join t3 on t3.id = t1.t3fk
left join t4 on t4.id = t1.t4fk
group by t1.id

There will be no performance penalty (ie MySQL will not "re-summarize" the three columns to produce the total)不会有性能损失(即 MySQL 不会“重新汇总”三列以产生总数)

Yes, this is possible by using a nested query.是的,这可以通过使用嵌套查询来实现。

SELECT id, cola, colb, colc, SUM(cola + colb + colc)
  FROM  (
      SELECT id, SUM(a) cola, SUM(b) colb, SUM(c) colc
        FROM whatever ...
       GROUP BY id
        ) subquery_alias
 GROUP BY id

Most servers' query planning modules do a good job optimizing these sorts of queries built from sub queries.大多数服务器的查询计划模块在优化从子查询构建的这些类型的查询方面做得很好。

Pro tip Format these nested queries carefully in your source code so you, or somebody else, can read them easily years from now.专业提示在您的源代码中仔细格式化这些嵌套查询,以便您或其他人可以在几年后轻松阅读它们。

For MySql 8.0+ you can use a CTE:对于 MySql 8.0+,您可以使用 CTE:

with cte as (
  select id, sum(t2.col) as cola, sum(t3.col) as colb, sum(t4.col) as colc
  from t1
  left join t2 on t2.id = t1.t2fk
  left join t3 on t3.id = t1.t3fk
  left join t4 on t4.id = t1.t4fk
  group by t1.id
)
select c.*, null as total
from cte as c
union all
select null, null, null, null, sum(cola + colb + colc)
from cte

For earlier versions:对于早期版本:

select id, sum(t2.col) as cola, sum(t3.col) as colb, sum(t4.col) as colc, null as total
from t1
left join t2 on t2.id = t1.t2fk
left join t3 on t3.id = t1.t3fk
left join t4 on t4.id = t1.t4fk
group by t1.id
union all
select null, null, null, null, sum(t2.col + t2.col + t2.col)
from t1
left join t2 on t2.id = t1.t2fk
left join t3 on t3.id = t1.t3fk
left join t4 on t4.id = t1.t4fk

In case there are null s in the columns t2.col , t3.col and t4.col , instead of如果t2.colt3.colt4.col列中有null ,而不是

sum(t2.col + t2.col + t2.col)

use:用:

sum(t2.col) + sum(t2.col) + sum(t2.col)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM