Skip to main content

You have four tables to track revenue and expenses—bankaccount, cash, accountitem, accountcategory.

-- Monthly expenses
--
-- http://www.artfulsoftware.com/infotree/qrytip.php?id=1088
-- You have four tables to track revenue and expenses—bankaccount,
-- cash, accountitem, accountcategory:

DROP TABLE
IF EXISTS accountitem,
 accountcategory,
 bankaccount,
 cash;

CREATE TABLE accountitem (
  itemid INT PRIMARY KEY auto_increment,
  itemname CHAR (32),
  itemcatid INT
);

CREATE TABLE accountcategory (
  categoryid INT PRIMARY KEY auto_increment,
  categoryname CHAR (32),
  isexpense bool
);

CREATE TABLE bankaccount (
  id INT auto_increment PRIMARY KEY,
  amount DECIMAL (12, 2),
  itemid INT,
  entrydate date
);

CREATE TABLE cash (
  id INT auto_increment PRIMARY KEY,
  amount DECIMAL (12, 2),
  itemid INT,
  date date
);

SELECT
  -- pivot by month
IF (MONTH = 1, m.Amt + n.Amt, 0) AS `Jan`,
IF (MONTH = 2, m.Amt + n.Amt, 0) AS `Feb`,
IF (MONTH = 3, m.Amt + n.Amt, 0) AS `Mar`,
IF (MONTH = 4, m.Amt + n.Amt, 0) AS `Apr`,
IF (MONTH = 5, m.Amt + n.Amt, 0) AS `May`,
IF (MONTH = 6, m.Amt + n.Amt, 0) AS `Jun`,
IF (MONTH = 7, m.Amt + n.Amt, 0) AS `Jul`,
IF (MONTH = 8, m.Amt + n.Amt, 0) AS `Aug`,
IF (MONTH = 9, m.Amt + n.Amt, 0) AS `Sep`,
IF (MONTH = 10, m.Amt + n.Amt, 0) AS `Oct`,
IF (MONTH = 11, m.Amt + n.Amt, 0) AS `Nov`,
IF (MONTH = 12, m.Amt + n.Amt, 0) AS `Dec`

FROM
  (
    SELECT
      MONTH (a.Date) AS MONTH,
      sum(a.Amount) AS Amt
    FROM
      cash a
    JOIN accountitem b ON a.itemid = b.itemid
    JOIN accountcategory c ON b.ItemCatID = c.CategoryID
    WHERE
      c.IsExpense = 1
    GROUP BY
      MONTH
  ) AS m
JOIN (
  -- join cash & bank data
  SELECT
    MONTH (a.EntryDate) AS MONTH,
    sum(a.Amount) AS Amt
  FROM
    BankAccount a
  JOIN accountitem b ON a.itemid = b.itemid
  JOIN accountcategory c ON b.ItemCatID = c.CategoryID
  WHERE
    c.IsExpense = 1
  GROUP BY
    MONTH
) AS n USING (MONTH);