SQL Query按月加入2个表

时间:2015-08-31 19:41:59

标签: mysql join

我有2个名为Despesas的表1和其他名为Receitas的表,两个都有字段 日期和价值。 我想总结按月和年分组的价值。 我试过这个

SELECT
    MONTHNAME(DATA) AS m,
    sum(valor) AS p

FROM
    despesas

GROUP BY 
MONTHNAME(DATA)

但我不知道如何在这样的表中加入

----------------------------------------
-  MONTH - SUM DESPESAS - SUM RECEITAS - 
- JANUARY - 10432.2     -  103.3       -
- MARCH    - 102.2      -   0          -
- APRIL    - 101.2      -    4         -
----------------------------------------

2 个答案:

答案 0 :(得分:1)

可能尝试如下;分别获取SUM()值,然后您可以在公共列JOINDATA两个表。查看您提供的小提琴http://sqlfiddle.com/#!9/cd9f9/6

SELECT
    MONTHNAME(d.DATA) AS Month_Name,
    sum(d.valor) AS Despesas_Sum_Valor,
    xx.Receitas_Sum_Valor
FROM
    despesas d JOIN (
SELECT DATA, 
sum(valor) AS Receitas_Sum_Valor
FROM Receitas

GROUP BY MONTHNAME(DATA) ) xx 
ON MONTHNAME(d.DATA) = MONTHNAME(xx.DATA)
GROUP BY 
MONTHNAME(DATA);

答案 1 :(得分:1)

drop table if exists t1;
create table t1 (date date, val int);
insert into t1 values ("2015-01-02", 1), ("2015-01-25", 2), ("2015-02-02", 3);
drop table if exists t2;
create table t2 (date date, val int);
insert into t2 values ("2015-01-15", 1), ("2015-02-10", 2), ("2015-03-01", 3);

select monthname(date), sum(val1) DESPESAS, sum(val2) RECEITAS 
   from (
     select date, val1, val2 
        from (select date, val val1, 0 val2 
                 from t1) s1  
              union 
              (select date m, 0 val1, val val2 
                 from t2 ) ) t 
   group by month(date) 
   order by date

结果

monthname(date) DESPESAS    RECEITAS
January         3           1
February        3           2
March           0           3