2016-08-04 6 views
-1
 
funds_table 
--------------------------- 
source_id, amount, date, 
--------------------------- 
1, 1000, 2016-01-15 
2, 2000, 2016-02-28 
 
ca_table 
--------------------------- 
ca_id,source_id, amount 
--------------------------- 
c1 ,  1, 500 
c2 ,  1, 500 
c3 ,  2, 900 
c4 ,  2, 1100 
 
exp_table 
--------------------------- 
exp_id, ca_id, amount, 
--------------------------- 
e1,  c1, 0 
e2,  c1, 250 
e3,  c2, 500 
e4,  c3, 500 
e5,  c4, 600 
e6,  c4, 500 

私が選択MONTHNAME(日付)、合計(funds_table.amount **)、合計(ca_table.amount)を合計したいです合計(exp_table.amount) は(日)、月によって互いに 年(日付)= 2016グループに参加MySQLの合計欄の異なる3つのテーブル

期待出力に

 

----------------------------------------------------------------------- 
MonthName(date),sum(source_id.amount),sum(ca_id.amount),sum(exp_id.amount) 
----------------------------------------------------------------------- 
Jan   ,     1000,    1000,    750 
Feb   ,     2000,    2000,    1100 

3日間の結果の検索が、私は、正確な結果を得るカント。

+0

あなたの問題とは何ですか? – Jens

+0

私は最後のテーブルが結果になることを望みます –

答えて

0

私はあなたのテーブルを持っていないが、私はこれはそれが最初に思ったほど簡単ではありませんU

SELECT DATE_FORMAT(funds_table.date,"%M") AS month,SUM(ca_table.amount) AS ca_table_amount,SUM(exp_table.amount) AS exp_table_amount,month,SUM(funds_table.amount) AS funds_table_amount FROM `funds_table` INNER JOIN ca_table 
ON funds_table.source_id=ca_table.source_id 
INNER JOIN exp_table 
ON ca_table.ca_id=exp_table.ca_id 
GROUP BY month 
0

を助ける考える -

/* 
create table funds_table (source_id int, amount int, dte date) ; 
insert into funds_table values 
(1, 1000, '2016-01-15'), 
(2, 2000, '2016-02-28'); 

create table ca_table (ca_id varchar(2),source_id int, amount int); 
insert into ca_table values 
('c1' ,  1, 500), 
('c2' ,  1, 500), 
('c3' ,  2, 900), 
('c4' ,  2, 1100); 

create table exp_table(exp_id varchar(2), ca_id varchar(2), amount int); 
insert into exp_table values 
('e1',  'c1', 0), 
('e2',  'c1', 250), 
('e3',  'c2', 500), 
('e4',  'c3', 500), 
('e5',  'c4', 600), 
('e6',  'c4', 500); 
*/ 

select month,sum(ftamt) ftamt,sum(caamt) caamt,sum(eamt) eamt 
from 
(
select month(ft.dte) month,sum(ft.amount) as ftamt, ca.caamt, 0 as eamt 
from  funds_table ft 
join  (select ca.source_id ,sum(ca.amount) caamt from ca_table ca group by ca.source_id) ca on ca.source_id = ft.source_id 
group  by month(ft.dte) 
union 
select month(ft.dte), 0,0, sum(e.amount) 
from  funds_table ft 
join  ca_table ca on ca.source_id = ft.source_id 
join  exp_table e on e.ca_id = ca.ca_id 
group  by month(ft.dte) 
) s 
group by month 
をexp_tableするca_tableを通じて参加に対応するために労働組合の点に注意してください。

結果

+-------+-------+-------+------+ 
| month | ftamt | caamt | eamt | 
+-------+-------+-------+------+ 
|  1 | 1000 | 1000 | 750 | 
|  2 | 2000 | 2000 | 1600 | 
+-------+-------+-------+------+ 
+0

私は試してみて、それは感謝を実行すると思います!私はできるだけ早く返信します –

関連する問題