MySQL:对两个 UNIONed 表求和(一个结果中 4x SUM)

标签 mysql

我必须在一个简单的查询中进行选择、联合...

SELECT description_x, a, b, c, d from table a WHERE person_id = 1
UNION
SELECT description_y, e ,f ,g ,h from table b WHERE person_id = 1

...a、b、c、d、e、f、g、h 均为整数。我怎样才能对它们求和,结果会像这样......

row 1: description_x |  a  |  b  |  c  |  d
row 2: description_y |  e  |  f  |  g  |  h
row 3: summary       | a+e | b+f | c+g | d+h 

...请吗?

非常感谢!

最佳答案

您可以向其中添加另一个union来执行聚合。

select description_x, a, b, c, d from table a where person_id = 1
union all
select description_y, e ,f ,g ,h from table b where person_id = 1
union all
select 'summary', sum(a), sum(b), sum(c), sum(d) from (
    select a, b, c, d from table a where person_id = 1
    union all
    select e ,f ,g ,h from table b where person_id = 1
) t

如果 MySQL 支持 CTE(正如评论中提到的,CTE 将在 MySQL 8 及以上版本中提供),我们就不需要再次重写相同的查询。

关于MySQL:对两个 UNIONed 表求和(一个结果中 4x SUM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42628345/

相关文章:

mysql - 日期_添加间隔

mysql - 如何删除sql中的行而不删除整个表

mysql - sqlite3可以优雅地处理30个并发更新请求吗?

Mysql 按多个列值连接和过滤

php - 每 30 秒获取一次表数据

php - 了解 url 缩短函数

php - 图片在mysql数据库中上传显示

php - PHP 中的 MySQL;比较前编辑列值

mysql - MongoDB 中与 SQL 中的减集操作等效的操作是什么?

mysql - 如何在 MS sql 中显示类似于 11111 或类似的数字