Standard Deviation for SQLite

后端 未结 10 717
生来不讨喜
生来不讨喜 2020-12-14 08:05

I\'ve searched the SQLite docs and couldn\'t find anything, but I\'ve also searched on Google and a few results appeared.

Does SQLite have any built-in Standard Devi

10条回答
  •  猫巷女王i
    2020-12-14 08:37

    I implemented the Welford's method (the same as extension-functions.c) as a SQLite UDF:

    $db->sqliteCreateAggregate('stdev',
        function (&$context, $row, $data) // step callback
        {
            if (isset($context) !== true) // $context is null at first
            {
                $context = array
                (
                    'k' => 0,
                    'm' => 0,
                    's' => 0,
                );
            }
    
            if (isset($data) === true) // the standard is non-NULL values only
            {
                $context['s'] += ($data - $context['m']) * ($data - ($context['m'] += ($data - $context['m']) / ++$context['k']));
            }
    
            return $context;
        },
        function (&$context, $row) // fini callback
        {
            if ($context['k'] > 0) // return NULL if no non-NULL values exist
            {
                return sqrt($context['s'] / $context['k']);
            }
    
            return null;
        },
    1);
    

    That's in PHP ($db is the PDO object) but it should be trivial to port to another language.

    SQLite is soooo cool. <3

提交回复
热议问题