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 `tam_results_14` ADD INDEX `tam_14_idx_result_custome_team_id_territo` (`result_id`,`customer_id`,`team_id`,`territory_name`);
ALTER TABLE `tam_results_14` ADD INDEX `tam_14_idx_resul_custo_team_team_terri_speci` (`result_id`,`customer_id`,`team_id`,`team_name`,`territory_name`,`specialty`);
WITH distinct_users_team_tbl AS (SELECT
tam_results_14.team_id,
count(DISTINCT tam_results_14.id) AS distinct_users_team,
count(DISTINCT tam_results_14.id) FILTER (WHERE targeted_users > 0) AS targeted_distinct_users_team
FROM
tam_results_14
WHERE
tam_results_14.result_id = 201
AND tam_results_14.customer_id = '1'
GROUP BY
tam_results_14.team_id
ORDER BY
NULL), distinct_users_territory_tbl AS (SELECT
tam_results_14.team_id,
tam_results_14.territory_name,
count(DISTINCT tam_results_14.id) AS distinct_users_territory,
count(DISTINCT tam_results_14.id) FILTER (WHERE targeted_users > 0) AS targeted_distinct_users_territory
FROM
tam_results_14
WHERE
tam_results_14.result_id = 201
AND tam_results_14.customer_id = '1'
GROUP BY
tam_results_14.team_id,
tam_results_14.territory_name
ORDER BY
NULL), distinct_users_specialty_tbl AS (SELECT
tam_results_14.team_id,
tam_results_14.team_name,
tam_results_14.territory_name,
tam_results_14.specialty,
sum(tam) AS tam,
sum(sam) AS sam,
count(DISTINCT tam_results_14.id) AS distinct_users_specialty,
count(DISTINCT tam_results_14.id) FILTER (WHERE targeted_users > 0) AS targeted_distinct_users_specialty
FROM
tam_results_14
WHERE
tam_results_14.result_id = 201
AND tam_results_14.customer_id = '1'
GROUP BY
tam_results_14.team_id,
tam_results_14.team_name,
tam_results_14.territory_name,
tam_results_14.specialty
ORDER BY
NULL) SELECT
*
FROM
distinct_users_specialty_tbl
JOIN
distinct_users_team_tbl
ON distinct_users_specialty_tbl.team_id = distinct_users_team_tbl.team_id
JOIN
distinct_users_territory_tbl
ON distinct_users_specialty_tbl.team_id = distinct_users_territory_tbl.team_id
AND distinct_users_specialty_tbl.territory_name = distinct_users_territory_tbl.territory_name