[英]How to get none matching columns and matching columns with two sql tables
我有两个表的收入和支出,我想将不匹配的列包括到第三个表中,这样我就可以对收入和支出进行汇总和分组,并将收入列相加以获得总计和支出列总计
incomes table expenses table
----------------------------------- ------------------------------------
| incomeId | date | amount | | expenseId | date | amount |
+---------------------------------+ +----------------------------------+
| 1 | 2/4/2020 | 3000 | | 1 | 8/4/2020 | 3000 |
| 2 | 9/4/2020 | 9000 | | 2 | 23/4/2020 | 3500 |
| 3 | 15/9/2020 | 15000 | | 1 | 9/3/2020 | 2000 |
| 4 | 7/3/2020 | 7000 | ------------------------------------
------------------------------------
Expected table Results
------------------------------------
| Month | Income | Expense |
+----------------------------------+
| March | 7000 | 2000 |
| April | 12000 | 6500 |
| September | 15000 | |
+==================================+
| Total | 34000 | 8500 |
====================================
SQL
SELECT
Income.Month,
Income.Income,
Expense.Expense
FROM(
SELECT
DATE_FORMAT(date,'%M') AS Month,
SUM(amount) AS Income
FROM income
GROUP BY DATE_FORMAT(date, '%M')
) AS Incomes
JOIN
(
SELECT
DATE_FORMAT(date,'%M') AS Month,
SUM(amount) AS Expense
FROM expenses
GROUP BY DATE_FORMAT(date, '%M')
) AS Expense
ON Expense.Month = Income.Month
如果您想在两个表上都允许缺少日期,您可以使用union all
模拟full join
:
select year(date) yr, month(date) mn, sum(income) income, sum(expense) expense
from (
select date, amount income, null expense from incomes
union all
select date, null, amount from expenses
) t
group by year(date), month(date)
with rollup
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.