sql - 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 条件。
我不知道如何设置该条件。
感谢帮助。
解决方案
嗯。. . 您可以通过计算月份列中的“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;
推荐阅读
- c# - 枚举模型绑定 [FromRoute] 的行为与 .net 核心中的 [FromBody] 不同
- javascript - 使用 node_modules 实现 Typed.js 时遇到问题
- php - session_start(); 警告?
- java - 运行测试时出现 InaccessibleObjectException
- laravel - 403 Forbidden on Storage Directory
- django - Vue 代码未在我的 Django/Vue 项目中更新
- pyspark - 遍历 pyspark 数据帧以查找分层血统
- django - 如何在考试服务器上的 Apache 服务器上运行我的 Django 项目?
- angular - 有没有办法在使用 observables 时将复杂的 json 数据映射到 typescript 中的接口?
- html - 需要 CSS 帮助 - 通过媒体查询阻止布局变化 - flex?