首页 > 解决方案 > sql sum over with where 条件

问题描述

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

| 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。

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

| 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 条件。

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

感谢帮助。

标签: sqlpostgresqlsumwhere-clausecumulative-sum

解决方案


嗯。. . 您可以通过计算月份列中的“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;

推荐阅读