你好,我有一点问题。我正在尝试写下 SQL 查询。 我已经尝试了很多东西,但我找不到如何将几行添加在一起并从另一个表中添加一些数据,如果有更多的东西你必须分组。
这是我使用 select the basic one 和 order by 等时的数据。
标签 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 - spend
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
有什么办法可以得到吗?
我已经制作好了 fiddle : SQLFIDDLE
最佳答案
你可以像下面那样做:
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;
关于mysql - SQL 2表合二为一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47837785/