I'm trying to sum up 2 columns from 2 different tables, grouped and sorted by a formatted string.
The schema gist is this:
Table A:
* Created At
* Amount Charged
Table B:
* Created At
* Cash Amount
Note they share a column name called "created at", but have different column names for what I'm trying to sum up.
I want a result that says for the month of Jan, the sum of Table A Amount Charged + Table B Cash Amount is x, and for Feb, and so on and so forth.
Here's how I'm formatting the date:
str_to_date(concat(date_format(created_at
, '%Y-%m'), '-01')
You could use UNION ALL
:
SELECT str_to_date(concat(date_format(created_at, '%Y-%m'), '-01'), SUM(sub.c)
FROM (SELECT created_at, Amount AS c
FROM tabA
UNION ALL
SELECT created_at, Cash
FROM tabB) sub
GROUP BY str_to_date(concat(date_format(created_at, '%Y-%m'), '-01');
I would replace str_to_date(concat(date_format(created_at, '%Y-%m'), '-01')
with EXTRACT(YEAR_MONTH FROM created_at)