2017-03-06 3 views
2

私はSELECT文を持って、1つの単純なクエリでUNION句...のMySQL:SUM 2つのUNION句のテーブル(1つの結果で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 

...、B、C、D、E、F 、g、hはすべて整数です。どのようにしてSUMを計算すると、結果は次のようになりますか?

 
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がgと何らかの関係を持つのは奇妙に思えます。 – 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以降に来ている)CTEをサポートしている場合、再び同じクエリを書き直す必要はありません。

+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

関連する問題