Re: regr_slope function with auto creation of X column

From: David G Johnston <david(dot)g(dot)johnston(at)gmail(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: regr_slope function with auto creation of X column
Date: 2014-11-30 03:01:27
Message-ID: 1417316487139-5828676.post@n5.nabble.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Jason Aleksi wrote
> --Storing 30 day regression slopes into table (DOES NOT WORK)
> INSERT INTO historical_data_regr_slope (department_id, date,
> regr_slope30sales) (
> SELECT historical_data.department_id, historical_data.date,
> regr_slope(row_number(), historical_data.salesDollarK) OVER
> (PARTITION BY historical_data.department_id ORDER BY historical_data.date
> DESC ROWS BETWEEN 1 PRECEDING AND 29 FOLLOWING) AS regr_slope30sales
> FROM historical_data
> GROUP BY historical_data.department_id, historical_data.date,
> historical_data.salesDollarK
> ORDER BY historical_data.department_id, historical_data.date DESC
> )
>
> Any suggestions on how to auto-create the regr_slope X column?

You shoud be able to use a subquery to first generate the relevant row
numbers and then in the outer query apply the regr_slope function.

You could also try (theory here - the documentation should be improved in
this area) two applications of the OVER clause.

regr_expr( row_number() over (...), sales ) over (...)

You should probably define the window in the main body and refer to it by
name if you attempt this. I honestly have no idea if it will work but the
syntax you used before is defined as invalid because nothing can come
between the function and the OVER part; which negates the possibility of
using a single OVER to cover two functions.

I would suggest you not intermix window and group by until you get the
window working. Then put that into a cte/with and run the group by
separately - you might need to put the group by in the cte and the window in
the main query. That said I haven't fully contemplated what it is you are
attempting to calculate. Typically moving averages are not going to require
a group by clause...you just need to add a where clause that can filter out
the first N records where the number of input rows is less than N.

David J.

--
View this message in context: http://postgresql.nabble.com/regr-slope-function-with-auto-creation-of-X-column-tp5828673p5828676.html
Sent from the PostgreSQL - sql mailing list archive at Nabble.com.

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Ron256 2014-12-03 14:42:16 Re: generating the average 6 months spend excluding first orders
Previous Message Jason Aleksi 2014-11-30 00:27:30 regr_slope function with auto creation of X column