问题描述
我在 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 条件。
我不知道如何设置该条件。
感谢您的帮助。
解决方法
嗯。 . .您可以通过计算月份列中“10”的数量来定义特殊组:
Question.objects.all().first().get_children()
你也可以使用算术:
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