CREATE OR REPLACE FUNCTION median(vals numeric[]) RETURNS float AS '
median(vals)
' LANGUAGE 'plr' STRICT;
CREATE AGGREGATE median (numeric)
(
sfunc = array_append,
stype = numeric[],
initcond = '{}',
finalfunc = median
);
--And usage
select sn, median(dtwm), count(dtwm), date_trunc('day', timestamp) as day from
gwdata where timestamp < '2003-01-01' group by sn, day limit 5;
-- sn | median | count | day -----+--------+-------+------------------------
-- 5526 | 1.59 | 24 | 2002-12-26 00:00:00-07
-- 5539 | 1.7605 | 24 | 2002-02-27 00:00:00-07
-- 5522 | 0.737 | 24 | 2001-10-03 00:00:00-07
-- 5517 | 0.96 | 24 | 2001-11-05 00:00:00-07
-- 5513 | 1.3855 | 24 | 2001-09-07 00:00:00-07
-- Time: 247.126 ms
-- Here's the PL/Perl median() function.
-- Much less straightforwards, included for historical interest BEGIN { strict->import(); }
my ($tname,$cname) = @_;
my $SQL = "SELECT count($cname) AS t FROM $tname";
my $rc = spi_exec_query($SQL);
my $total = $rc->{rows}[0]{'t'};
$total < offset =" ($total-1)/2;" sql = "SELECT $cname AS median FROM $tname ORDER BY $cname OFFSET $offset LIMIT 1" sql = "SELECT avg($cname) AS median FROM (SELECT $cname FROM $tname ORDER BY $cname OFFSET $offset LIMIT 2 ) AS foo" rc =" spi_exec_query($SQL);">{rows}[0]{median};
Elevate Your Data Skills with Jumping Rivers Training
-
In today’s data-driven world, strong analytical and programming skills are
essential for success.
Whether you’re just starting your data journey or looki...
1 day ago

No comments:
Post a Comment