2011-09-12 63 views
1

我有一个统计表在PostgreSQL表:获取每个第七记录

article_id | date  | read_count 
    1  | 2011-06-02 | 12 
    1  | 2011-06-03 | 54 
    1  | 2011-06-04 | 2 
    1  | 2011-06-05 | 432 

,正如我在图表中需要这个数据,我需要在每个星期得到的值。

我知道Postgres有一个row_number()函数,无论如何,我没有得到它的正常工作。

SELECT "date", "read_count" FROM "articles_stats" 
WHERE row_number() OVER (ORDER BY "date" ASC) % 7 = 0 
ORDER BY "date" ASC 

ERROR:窗口函数不允许在WHERE子句

+0

[Windows函数]( http://www.postgresql.org/docs/9.0/static/tutorial-window.html)应该exp说明错误的含义 - 希望能够洞察如何解决。 – 2011-09-12 18:54:23

+0

我真的知道错误的意思,我只是问如何解决这个问题。 ;-) –

+1

那么,重点是窗口函数*不能*在WHERE(该语句)中工作,因为既没有应用结果集也没有应用排序。 – 2011-09-12 18:58:15

回答

4

从@pst的链路,

"If there is a need to filter or group rows after the window calculations are performed, you can use a sub-select."

例如:

SELECT * 
    FROM (
      SELECT "date", "read_count", 
       row_number() OVER (ORDER BY "date" ASC) as n 
      FROM "articles_stats" 
     ) x 
    WHERE x.n % 7 = 0 
ORDER BY x."date" ASC 
+0

当,你打败了我49秒:)。那么给你一个upvote。 – Barend

+0

您可以使用'row_number()OVER()作为n',我认为这会使查询效率更高,因为排序的次数会减少。 – Barend

+0

@Barend:感谢你的赞扬和评论。 – bernie