我必须在一个简单的查询中进行选择、联合...
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/