In case you have your own slow SQL query, you can optimize it automatically here.
For the query above, the following recommendations will be helpful as part of the SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `A` ADD INDEX `a_idx_date` (`date`);
ALTER TABLE `B` ADD INDEX `b_idx_type_id` (`type`,`id`);
SELECT
num2.last_dates,
(SELECT
SUM(amount)
FROM
A
INNER JOIN
B
ON A.B_id = B.id
WHERE
B.type = 7
AND A.date <= num2.last_dates),
(SELECT
SUM(amount)
FROM
A
INNER JOIN
B
ON A.B_id = B.id
WHERE
B.type = 5
AND A.date <= num2.last_dates)
FROM
(SELECT
last_dates
FROM
(SELECT
LAST_DAY(CURDATE() - INTERVAL CUSTOM_MONTH MONTH) last_dates
FROM
(SELECT
1 CUSTOM_MONTH
UNION
SELECT
0
UNION
SELECT
2
UNION
SELECT
3
UNION
SELECT
4
UNION
SELECT
5
UNION
SELECT
6
UNION
SELECT
7
UNION
SELECT
8
UNION
SELECT
9
UNION
SELECT
10
UNION
SELECT
11
UNION
SELECT
12
) num
) num1
) num2
ORDER BY
num2.last_dates