This query sometimes randomly gives me null values in some rows and sometimes it doesn't. It all started happening when I changed the inner joins for left joins.
CREATE temporary TABLE IF NOT EXISTS surveys_temp AS
(SELECT SN.id_rep,
Coalesce(( Sum(CASE
WHEN SN.score < 7 THEN -100
WHEN SN.score >= 7
AND score < 9 THEN 0
WHEN SN.score >= 9 THEN 100
end) / Count(score) ), 0) AS NRS,
SW.wtr
FROM surveys SN
INNER JOIN (SELECT id_rep,
Coalesce(( Sum(CASE
WHEN score < 7 THEN -100
WHEN score >= 7
AND score < 9 THEN 0
WHEN score >= 9 THEN 100
end) / Count(score) ), 0) AS WTR
FROM surveys
WHERE survey_type = 'WTR'
GROUP BY id_rep) SW
ON SW.id_rep = SN.id_rep
WHERE SN.survey_type = 'NRS'
GROUP BY SN.id_rep);
CREATE temporary TABLE IF NOT EXISTS orders_temp AS
(SELECT id_rep,
Sum(Cast(ordernumber AS DECIMAL(2, 0))) AS Orders
FROM orders
GROUP BY id_rep);
CREATE temporary TABLE IF NOT EXISTS chats_temp AS
(SELECT id_rep,
Time_format(Sec_to_time(Cast(Cast(Sum(response_time * -1)/ Count(
id_session) AS
DECIMAL(5, 2
)) AS CHAR(6
))), '%H : %i : %s')AS response_time
FROM chats
WHERE chat_type = 1
GROUP BY id_rep
ORDER BY id_rep);
SELECT R.rep_name,
Count(DISTINCT R.id_session) AS Chats,
O.orders,
Concat(Cast((o.orders/Count(DISTINCT r.id_session)) * 100 AS DECIMAL(5, 2
)), '%'
) AS CONVERSION,
Coalesce(Cast(s.nrs AS DECIMAL(5, 2)), '0') AS NRS,
Coalesce(Cast(s.wtr AS DECIMAL(5, 2)), '0') AS WTR,
C.response_time
FROM reps R
LEFT JOIN surveys_temp AS S
ON S.id_rep = R.id_rep
LEFT JOIN orders_temp AS O
ON O.id_rep = R.id_rep
LEFT JOIN chats_temp AS C
ON c.id_rep = R.id_rep
WHERE R.rep_country IN( 'D.R', 'U.S' )
GROUP BY R.rep_name
ORDER BY R.rep_name;