【问题标题】:Postgres Create function to copy data from one month to all months until end of quarterPostgres 创建函数将数据从一个月复制到所有月份,直到季度末
【发布时间】:2017-10-04 22:50:50
【问题描述】:

我在一个季度中定义了 1 个月的数据点,并且需要在该季度的所有月份中复制该数据点,以此类推所有月份。例如,我拥有的数据是:

month_start  C1   C2
2017-01-01   10   21
2017-01-01   17   42
2017-01-01   22    7
2017-04-01   13    6
2017-04-01    8   99 

现在我想更改它,以便根据 month_start 在季度内复制数据,如下所示:

month_start   C1      C2  
2017-01-01    10      21  
2017-01-01    17      42  
2017-01-01    22      7  
2017-02-01    10      21  
2017-02-01    17      42  
2017-02-01    22      7  
2017-03-01    10      21  
2017-03-01    17      42  
2017-03-01    22      7  
2017-04-01    13      6  
2017-04-01     8      99  
2017-05-01    13      6  
2017-05-01     8      99  
2017-06-01    13      6  
2017-06-01     8      99  

出于报告目的,我需要这样做,因为报告是月度报告。关于如何实现这一目标的任何想法。如果您有任何其他问题,请告诉我。

【问题讨论】:

  • SO 不是免费的编码服务。您尝试过什么(将其添加到问题中)并在不起作用时寻求具体帮助。顺便说一句,postgres 擅长创建系列,也许研究 postgres 系列。
  • 顺便说一下,我希望有更多的列可以帮助解释为什么有时每个日期有 3 行,而其他日期有 2 行

标签: sql postgresql reporting


【解决方案1】:

您可以使用函数generate_series(): 将行再复制两个月

with my_table(month_start, C1, C2) as (
values
    ('2017-01-01'::date, 10, 21),
    ('2017-01-01', 17, 42),
    ('2017-01-01', 22, 7),
    ('2017-04-01', 13, 6),
    ('2017-04-01', 8, 99)
)

select ms::date as month_start, c1, c2
from my_table
cross join generate_series(month_start, month_start+ interval '2 months', '1 month') ms
order by month_start, row_number() over (order by month_start);

 month_start | c1 | c2 
-------------+----+----
 2017-01-01  | 10 | 21
 2017-01-01  | 17 | 42
 2017-01-01  | 22 |  7
 2017-02-01  | 10 | 21
 2017-02-01  | 17 | 42
 2017-02-01  | 22 |  7
 2017-03-01  | 10 | 21
 2017-03-01  | 17 | 42
 2017-03-01  | 22 |  7
 2017-04-01  | 13 |  6
 2017-04-01  |  8 | 99
 2017-05-01  | 13 |  6
 2017-05-01  |  8 | 99
 2017-06-01  | 13 |  6
 2017-06-01  |  8 | 99
(15 rows)

请注意,row_number() 仅用于保留行的原始排序顺序。

【讨论】:

    猜你喜欢
    • 2023-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2018-06-18
    相关资源
    最近更新 更多