简体   繁体   中英

How to get none matching columns and matching columns with two sql tables

I have two table incomes and expenses, I want to includes the none matching columns to the third table so I can be able to sum and group incomes and expenses with months and sum the Income column to get total and Expense Column total

             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

If you want to allow missing dates on both tables, you can emulate a full join with union all :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM