I wanted to create a query based on the date, I want to sum the credit and debit based on the year of the transaction_line and display it as total_previous (date within 2021) and total_current (date within 2022). Below is what I do and what is the expected result.
transaction_lines table:
account_id | date | debit | credit |
---|---|---|---|
1021 | 2021-11-08 | 100 | 0 |
1021 | 2022-01-02 | 107 | 0 |
1021 | 2022-04-22 | 0 | 50 |
1021 | 2022-04-22 | 12 | 0 |
What I got currently:
account_id | total_previous | total_current |
---|---|---|
1021 | 0 | -169 |
Expected result:
account_id | total_previous | total_current |
---|---|---|
1021 | -100 | -69 |
The query that I executed:
SELECT
account_id,
date,
debit,
credit,
IF(date >= '2021-01-01'
AND date <= '2021-12-31',
- COALESCE(SUM(debit), 0) + COALESCE(SUM(credit), 0),
0) AS total_previous,
IF(date >= '2022-01-01'
AND date <= '2022-12-31',
- COALESCE(SUM(debit), 0) + COALESCE(SUM(credit), 0),
0) AS total_current
FROM
transaction_lines
WHERE
account_id = '1021'
AND date >= '2021-01-01'
AND date <= '2022-12-31';
I already work on this for a full day, thus I need help to justify if it is actually achievable. If it is possible, please advise me on what is wrong with my query.
2
Answers
Try this:
Instead of hard coding the year in the query, you can make the query dynamic so that it you can see the current_total and prev_total for multiple years.
Then when you want for a certain year you can just add a where clause
e.g where current.current_year = 2021