Search code examples
mysql

Ledger Table from two tables in mysql query


Please check tables below and help to solve. Table A

a_id name dept a_date amount
123 Clark Sales 2024-01-01 5000
124 Clark Sales 2024-01-02 6000
125 John Sales 2024-01-03 3500
126 John Sales 2024-01-04 5500

Table B

b_id name dept b_date amount status type
2001 Clark Sales 2024-02-05 1000 Paid Loan
2002 Clark Sales 2024-02-06 1000 Unpaid Loan
2003 Clark Sales 2024-02-08 5000 Paid Loan
2004 Clark Sales 2024-02-09 1000 Unpaid Adv
2005 John Sales 2024-02-11 1000 Unpaid Loan

With the help of this solution I tried below query.

SELECT
   a_date as `Date`,
   amount as `Paid Amount`,
   0 as `Received Amount`,
   amount - 0 as `Balance`
FROM `Table A`
WHERE name = 'Clark'
UNION
SELECT 
   b_date as `Date`,
   0 as `Paid Amount`,
   amount as `Received Amount`,
   0 - amount as `Balance`
FROM `Table B`
WHERE name = 'Clark' AND status = 'Paid' AND type = 'Loan'
ORDER BY `Date` ASC

Which gives table as below.

Date Paid Amount Received Amount Balance
2024-01-01 5000 0 5000
2024-01-02 6000 0 6000
2024-02-05 0 1000 -1000
2024-02-08 0 5000 -5000

but I am trying to achieve Result table like this

Date Paid Amount Received Amount Balance
2024-01-01 5000 0 5000
2024-01-02 6000 0 11000
2024-02-05 0 1000 10000
2024-02-08 0 5000 5000

In Column Balance every cell will be SUM with previous cell

First Row -> 5000

Second Row -> 5000 + 6000 = 11000

Thirst Row -> 6000 - 1000 = 10000

Fourth Row -> 10000 - 5000 = 5000

Any hint and solution is highly appreciated. Thanks Update: fourth row updated as suggested by @akina


Solution

  • this query works for me

    SELECT `Date`, `Paid Amount`, `Received Amount`, @balance:= @balance + (`Paid Amount` - `Received Amount`) AS `Balance` FROM (SELECT a_date AS `Date`, amount AS `Paid Amount`, 0 AS `Received Amount` FROM `Table A` WHERE `name` = 'Clark' UNION ALL
    SELECT b_date AS `Date`, 0 AS `Paid Amount`, amount AS `Received Amount` FROM `Table B` WHERE `name` = 'Clark' AND `status` = 'Paid' AND `type` = 'Loan') AS sub JOIN (SELECT @balance := 0) AS balance_init ORDER BY `Date` ASC;