Precompute the averages, then get to work on the main formula:
select grp, sum((x - avgx) * (y - avgy)) numerator
FROM ( SELECT grp,
avg(x) AS avgx,
avg(y) AS avgy
FROM tbl
) AS z
JOIN tbl USING(grp)
group by grp;
Assuming that works OK, enhance it to do the whole formula:
SELECT grp, ( sum((..)*(..)) ) /
( SQRT( ... ) ) as Correlation
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…