如何计算每月的总运行?

发布于 2025-01-23 15:40:41 字数 858 浏览 5 评论 0原文

表:

日期
'2020-06-02'150'2020-06-03'7891'2020-07-07-02'392运行
中有一个我在PostgreSQL
总数
......

我需要在表中的每个日期的列。 value在运行总计中的总和必须在行的第一个月份和行中的日期之间的第一个月日期之间计算。

示例:

  • 对于日期'2020-06-02'在第一行中value列的总和必须在'2020-06--之间的范围内计算01'和当前日期('2020-06-02'),包括当前日期的数字。
  • 对于第二行的日期,必须在value列中的数字之和在'2020-06-01'和当前日期之间计算。 >'2020-06-03'),包括'2020-06-03'的数字。
  • 对于第三行,value列中的数字总和必须在'2020-07-01''2020-07-之间计算。 02'
  • 等等...

如何实现这一目标?使用窗口功能?

I have a table in PostgreSQL:

datevalue
'2020-06-02'150
'2020-06-03'7891
'2020-07-02'392
......

I need to get running total of numbers in value column for each date in table. The sum of value in running total has to be calculated over the date range between the first date of month of the date in row and date in the row.

Examples:

  • For date '2020-06-02' in the first row the sum of value column has to be calculated over the range between '2020-06-01' and current date ('2020-06-02'), including number for current date.
  • For the date in the second row the sum of numbers in value column has to be calculated over the date range between '2020-06-01' and current date ('2020-06-03'), including number for '2020-06-03'.
  • For the third row the sum of numbers in value column has to be calculated over the date range between '2020-07-01' and '2020-07-02'.
  • and so on...

How to achieve this? With window functions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

荒路情人 2025-01-30 15:40:41

实际:

SELECT date
     , sum(value) OVER (PARTITION BY date_trunc('month', date) ORDER BY date)
FROM   tbl;

请注意,对等行(根据您的分区和排序订单)获得相同的结果。含义,重复的天数每个都具有相同的运行总和,包括其所有值。

Actually:

SELECT date
     , sum(value) OVER (PARTITION BY date_trunc('month', date) ORDER BY date)
FROM   tbl;

Note that peer rows (according to your partition and sort order) get the same result. Meaning, duplicate days each get the same running sum including all of their values.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文