开发者

PostgreSQL - WHERE clause within OVER clause?

I need to use a where clause within an over clause. How?

SELECT SUM(amount) OVER(WHERE dateval > 12)

Or something like that.

--EDIT--

More details

My table is formatted with a year, month, and amount column.

I want to select all the year, month, and amount rows AND creat开发者_如何转开发e a fourth 'virtual column' that has the sum of the past 12 months of amount column.

For example:

YEAR | MONTH | AMOUNT

2001 | 03 | 10

2001 | 05 | 25

2001 | 07 | 10

Should create:

YEAR | MONTH | AMOUNT | ROLLING 12 MONTHS

2001 | 03 | 10 | 10

2001 | 05 | 25 | 35

2001 | 07 | 10 | 45


Given a query against your three-column resultset, does the below work for you?

SELECT
    SUM(amount) OVER(ORDER BY YEAR ASC, MONTH ASC
                     ROWS BETWEEN 11 PRECEDING AND CURRENT ROW)
...


select a,(select sum(a) from foo fa where fa.a > fb.a) from foo fb;

Doesn't use over, is pretty inefficient since it is running new sub-query for each query, but it works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜