SQL 2表总和为一

时间:2017-12-15 18:15:23

标签: mysql sql function group-by sum

您好我有点问题。我试图写下SQL查询。 我已经尝试了很多东西,但是我无法找到如何将几行添加到一起并从另一个表中添加一些数据,如果有更多的东西需要分组。

以下是我使用我的选择基本订单时的数据等。

Tabel No.1

 Got      User_ID    Month
 100      1          1
 200      1          1
 500      1          2
 400      1          2
 50       1          3
 50       2          1
 150      2          1
 200      2          1
 100      2          2
 20       2          3

表2

 Spend    User_ID    Month
 50       1          1
 20       1          1
 50       1          2
 100      2          1
 50       2          2
 50       2          2
 50       2          3

使用SQL查询我希望得到此表Total = Got - 花费

 User_ID    Month   GOT    Spend    Total
 1          1       300    70       230
 1          2       900    50       850
 1          3       50     0        50
 2          1       400    100      300
 2          2       100    100      0
 2          3       20     50       -30

有没有办法可以得到它?

我有小提琴: SQLFIDDLE

2 个答案:

答案 0 :(得分:1)

SQL FIDDLE

你可以这样做:

select NO1.User_Id, NO1.Month, sum(NO1.Got) as Got, 
coalesce(Spend, 0) Spend, (sum(NO1.Got) - coalesce(Spend, 0)) Total
from NO1
left join (select User_Id, Month, sum(Spend) as Spend from NO2
          group by User_Id, Month) NO2 on NO1.User_Id=NO2.User_Id and NO1.Month=NO2.Month
group by NO1.User_Id, NO1.Month, Spend
order by NO1.User_Id, NO1.Month;

答案 1 :(得分:0)

只需加入两个汇总查询:

select t1.User_Id, t1.Month, 
       IFNULL(t1.Got_Total, 0) As Got, 
       IFNULL(t2.Spend_Total, 0) As Spend, 
       IFNULL(t1.Got_Total, 0) - IFNULL(t2.Spend_TOTAL, 0) As Total
from
  (select User_Id, Month, sum(Got) as Got_TOTAL
   from NO1
   group by User_Id, Month) t1
left join 
  (select User_Id, Month, sum(Spend) as Spend_TOTAL
   from NO2
   group by User_Id, Month) t2
on t1.User_Id = t2.User_Id and t1.Month = t2.Month
order by t1.User_Id, t1.Month

SQL Fiddle Demo