Mysql sum列不同3个表

时间:2016-08-04 07:02:16

标签: php mysql sql database sqlite

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(日期),sum(funds_table.amount **), sum(ca_table.amount) sum(exp_table)相加.amount) 互相加入 其中年(日期)= 2016 按月分组(日期)

预期产出


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

3天搜索结果但我无法得到确切的结果。

2 个答案:

答案 0 :(得分:0)

我没有你的桌子,但我认为这将有助于你

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

答案 1 :(得分:0)

并不像第一次看起来那么容易 - 注意联盟通过ca_table来连接到exp_table

/*
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

结果

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