Note that there are some explanatory texts on larger screens.

plurals
  1. POMoving average in postgresql
    primarykey
    data
    text
    <p>I have the following table in my Postgresql 9.1 database:</p> <pre><code>select * from ro; date | shop_id | amount -----------+----------+-------- 2013-02-07 | 1001 | 3 2013-01-31 | 1001 | 2 2013-01-24 | 1001 | 1 2013-01-17 | 1001 | 5 2013-02-10 | 1001 | 10 2013-02-03 | 1001 | 4 2012-12-27 | 1001 | 6 2012-12-20 | 1001 | 8 2012-12-13 | 1001 | 4 2012-12-06 | 1001 | 3 2012-10-29 | 1001 | 3 </code></pre> <p>I am trying to get a moving average comparing data against last 3 Thursdays without including the current Thursday. Here's my query:</p> <pre><code>select date, shop_id, amount, extract(dow from date), avg(amount) OVER (PARTITION BY extract(dow from date) ORDER BY date DESC ROWS BETWEEN 0 PRECEDING AND 2 FOLLOWING) from ro where extract(dow from date) = 4 </code></pre> <p>This is the result given</p> <pre><code>date | shop_id | amount | date_part | avg -----------+----------+--------+-----------+-------------------- 2013-02-07 | 1001 | 3 | 4 | 2.0000000000000000 2013-01-31 | 1001 | 2 | 4 | 2.6666666666666667 2013-01-24 | 1001 | 1 | 4 | 4.0000000000000000 2013-01-17 | 1001 | 5 | 4 | 6.3333333333333333 2012-12-27 | 1001 | 6 | 4 | 6.0000000000000000 2012-12-20 | 1001 | 8 | 4 | 5.0000000000000000 2012-12-13 | 1001 | 4 | 4 | 3.5000000000000000 2012-12-06 | 1001 | 3 | 4 | 3.0000000000000000 </code></pre> <p>I expect</p> <pre><code>date | shop_id | amount | date_part | avg -----------+----------+--------+-----------+-------------------- 2013-02-07 | 1001 | 3 | 4 | 2.6666666666666667 2013-01-31 | 1001 | 2 | 4 | 4.0000000000000000 2013-01-24 | 1001 | 1 | 4 | 6.3333333333333333 2013-01-17 | 1001 | 5 | 4 | 6.0000000000000000 2012-12-27 | 1001 | 6 | 4 | 5.0000000000000000 2012-12-20 | 1001 | 8 | 4 | 2012-12-13 | 1001 | 4 | 4 | 2012-12-06 | 1001 | 3 | 4 | </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload