【问题标题】:Last value grouped by month for reporting monthly progress按月分组的最后一个值,用于报告月度进度
【发布时间】:2021-01-21 20:50:30
【问题描述】:

您好,我有一张如下所示的表格

grouping_coulmn value date_modified
1 5 2020-10-15
1 10 2020-10-20
2 3 2020-10-20
1 11 2020-11-30
1 11 2020-12-10
1 5 2020-12-15

如何进行返回以下结果的查询

grouping_column last_value_of_month month
1 10 OCT 2020
1 11 NOV 2020
1 5 DIC 2020
1 5 JAN 2021
2 3 OCT 2020
2 3 NOV 2020
2 3 DIC 2020
2 3 JAN 2021

换句话说,它应该每个月返回组的最后一个值,从第一个条目到当前月份。如果你不填补缺失的月份,我可以解决,但我不知道如何解决。

注意:这个问题是在 2021 年 1 月提出的,只是为了了解上下文。

【问题讨论】:

  • 你能修一下上面的桌子吗? :)
  • 是的,发布后注意到了
  • 当前月份是“2021 年 1 月”吗?
  • 是的,对不起,我的脑子还在 2020 模式,让我在问题中更正一下

标签: sql postgresql reporting


【解决方案1】:

首先,根据表中最早的日期生成所有月份:

with months as (
  select ddate + interval '1 month' as end_date,
         to_char(ddate, 'MON YYYY') as month
    from generate_series(
           date_trunc(
             'month', 
             (select min(date_modified) from table1)
           ), 
           now(),
           interval '1 month'
         ) as gs(ddate)
)

将其加入您的数据表,并使用distinct on 将结果限制为每个(grouping_column, month) 一条记录:

select distinct on (t.grouping_column, m.end_date)
       t.grouping_column, t.value as last_value_of_month, m.month
  from months m
       join table1 t
         on t.date_modified < m.end_date
 order by t.grouping_column, m.end_date, t.date_modified desc;

结果:

 grouping_column | last_value_of_month | month   
 --------------: | ------------------: | :-------
               1 |                  10 | OCT 2020
               1 |                  11 | NOV 2020
               1 |                   5 | DEC 2020
               1 |                   5 | JAN 2021
               2 |                   3 | OCT 2020
               2 |                   3 | NOV 2020
               2 |                   3 | DEC 2020
               2 |                   3 | JAN 2021

db小提琴here

【讨论】:

  • 非常感谢,我不习惯用其他 = 句子的东西来考虑连接,所以这真的很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-16
  • 1970-01-01
  • 2012-04-18
  • 2015-05-19
  • 2011-06-03
  • 1970-01-01
相关资源
最近更新 更多