SQL 2表总和为一

问题描述 投票:1回答:2

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

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

Tabe l。 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

有没有办法可以得到它?

我已经做过小提琴:qazxsw poi

mysql sql function group-by sum
2个回答
1
投票

SQLFIDDLE

您可以像下面这样做:

SQL FIDDLE

0
投票

只需加入两个聚合查询:

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;

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

© www.soinside.com 2019 - 2024. All rights reserved.