sql总和与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条件。

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

感谢帮助。

戈登·利诺夫(Gordon Linoff)

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章