Mam dochody i wydatki na dwie table, chcę obejmować Brak pasujących kolumn do trzeciej tabeli, więc mogę być w stanie sumować i grupować dochody oraz wydatki z miesięcy i sumy kolumny dochodowej, aby uzyskać całkowitą i wydatkową kolumnę

             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
0
ven 27 marzec 2020, 11:56

1 odpowiedź

Najlepsza odpowiedź

Jeśli chcesz zezwolić na brakujące daty na obu tabelach, możesz naśladować full join za pomocą 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
2
GMB 27 marzec 2020, 09:43