2017-03-06 101 views
2

我必須進行選擇,被聯合在一個簡單的查詢...MySQL的:SUM 2頁聯合在一起的表(4×SUM在一個結果)

 
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 

...好嗎?

非常感謝!

+1

c似乎與c有任何關係似乎很奇怪。 – Strawberry

回答

2

您可以添加另一個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支持的熱膨脹係數(正如在評論中提到的,是在MySQL 8日起推出)。

+0

這正是我正在尋找的東西。非常感謝你! – dusty

0
select sum(a) as a,sum(b) as b,sum(c) as c,sum(d) as d from (
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 
)T 
+0

非常好,謝謝。 – dusty