CREATE TABLE t(indiv INT, grp STRING, val INT) INSERT INTO t VALUES(1, 'A', 1) INSERT INTO t VALUES(1, 'A', 2) INSERT INTO t VALUES(1, 'A', 3) INSERT INTO t VALUES(1, 'A', 4) INSERT INTO t VALUES(2, 'A', 2) INSERT INTO t VALUES(2, 'A', 2) INSERT INTO t VALUES(2, 'A', 4) INSERT INTO t VALUES(2, 'A', 8) INSERT INTO t VALUES(3, 'B', 10) INSERT INTO t VALUES(3, 'B', 20) INSERT INTO t VALUES(3, 'B', 30) INSERT INTO t VALUES(3, 'B', 40) INSERT INTO t VALUES(4, 'B', 20) INSERT INTO t VALUES(4, 'B', 20) INSERT INTO t VALUES(4, 'B', 40) INSERT INTO t VALUES(4, 'B', 80) SELECT * FROM t FUNCTION myCov(x, y) { center_x := x - avg(x); center_y := y - avg(y); num := sum(center_x * center_y); denom := sqrt(sum(center_x * center_x)) * sqrt(sum(center_y * center_y)); num / denom } select myCov(1,2);