Search code examples
google-cloud-spanner

Is there a STDDEV equivalent in Cloud Spanner functions?


I don't see it in the documentation; is it perhaps part of an existing function I didn't notice, or available in some other way?


Solution

  • As Andrei Tigau mentioned, STDDEV is not supported yet. That said, you need to calculate it in two pass. Assuming you are interested in column x of YourTable,

    SELECT SQRT(SUM(POW(x - avg, 2)/(n-1)))
    FROM (SELECT AVG(x) AS avg, COUNT(*) AS n FROM YourTable)
      CROSS JOIN YourTable;
    

    You may try following one pass solution as well.

    SELECT SQRT(s2/(n-1) - POW(s/n, 2))
    FROM (
      SELECT COUNT(*) AS n, SUM(x) AS s, SUM(x*x) AS s2
      FROM YourTable
    );
    

    Depending on type, you may have to cast it to double (especially for s2) to avoid overflow. Both will suffer from floating point errors.