Part of the secret is
SELECT (...)/total, ...
JOIN ( SELECT SUM(...) AS total FROM ... ) x
That is, compute the total separately and make it available in the expressions.
SELECT @total := SUM(...) FROM ...
SELECT (...)/@total, ...
Your query plan shows two table scans on leads, which is not surprising given the search predicates with OR: FROM leads WHERE to_id = lead_id OR from_id = lead_id.
It also shows a spilled sort, suggesting that the sort buffer is too small.
Consider rewriting your query with joins instead of subselects, something like:
As the error says, that is limitation. However, you probably want try as follows:
COUNT (DISTINCT CASE WHEN O.REFDOCNUM is not null and D.REFDOCNUM is not null and D.REFDOCNUM is not null
THEN S.DOCNUM END
) AS HasInvoice,
COUNT (DISTINCT CASE WHEN O.REFDOCNUM is not null and D.REFDOCNUM ...