sql 用 where 条件求和

sql sum over with a where condition

我在 postgresql 数据库中有以下 table(它被分成两个 table 只是为了展示它是如何继续的):

| year | month | count |
|:-----|:-----:|------:|
| 2017 |  4    |   1   |
| 2017 |  5    |   4   |
| 2017 |  6    |   2   |
.
.
.
| year | month | count | 
|:-----|:-----:|------:|
| 2018 |  11   |   9   |

现在我需要一个输出,它汇总了从 10-2017 年到 9-2018 年,从 10-2018 年到 9-2019 年每个月的所有计数。

所以我们从 10-2018 开始,然后是 10-2018+11-2018,10-2018+11-2018+12-2018,...,10-2018+...9-2019。 然后我们再次从 10-2019 开始计数,例如 10-2019 10-2019+11-2019、10-2019+11-2019+12-2019、...、10-2019+...9-2020。

所以输出看起来像(它被分成两个 tables 只是为了展示它是如何继续的)::

| year | month | count | count_sum_ytd |
|:-----|:-----:|:-----:|--------------:|
| 2017 |  4    |   1   |       1       |
| 2017 |  5    |   4   |       5       |
| 2017 |  6    |   2   |       7       |
.
.
.
| year | month | count | count_sum_ytd |
|:-----|:-----:|:-----:|--------------:|
| 2017 |  9    |   2   |       22      |
| 2017 |  10   |   4   |       4       |
| 2017 |  11   |   3   |       7       |

因此,随着新的 10 月的到来,重新开始计数。 否则我们将从第 10 个月开始的每个月的所有值相加。 所以它就像 SUM(count) 中 PARTITION BY 中的 where 条件。

我不知道如何设置该条件。

感谢您的帮助。

嗯。 . .您可以通过计算月份列中“10”的个数来定义特殊组:

select t.*,
       sum(count) over (partition by grp order by year, month)
from (select t.*,
             count(*) filter (where month = 10) as grp
      from t
     ) t;

你也可以使用算术:

select t.*,
       sum(count) over (partition by floor( year * 100 - 10) / 100) order by year, month)
from t;

如果您将日期值作为适当的 date 存储在单个列中,这将是:

select t.*,
       sum(count) over (partition by date_trunc('year', datecol - interval '10 month') order by datecol)
from t;