【问题标题】:Get the the last value of each month in Postgresql获取 Postgresql 中每个月的最后一个值
【发布时间】:2019-03-26 18:04:17
【问题描述】:

在我的工作中,我必须运行一个返回的查询(或者我应该说它会让我的生活轻松 100 倍) - 一年中每个月所有付款的总和 - 每个月底的最终余额。

要获得后者,我需要选择每个月最后一条记录的“ending_balance”列。我已经算出了总和,所以整个查询看起来像这样

select 
extract(month from request_date):: integer as mon,
extract(year from request_date)::integer as year,
<missing logic here> 
sum(total_amount),
from my_table group by 1,2 order by 2

我已经在 stackoverflow 和其他网站上寻找答案半天了,我已经弄清楚如何通过

获得单个月份和年份的值
select payer_id 
from my_table as last_payer 
where extract(month from request_date):: integer = '2' 
and extract(year from request_date)::integer= '2019' 
order by request_date desc limit 1

但这仅在我提供特定日期时才有效。我需要每个月和年都能做到这一点的东西。用 'mon' 和 'year' 替换硬编码值不起作用。

我还要补充一点,我正在开发 dbeaver,我认为它不支持函数,但如果函数是我能做到这一点的唯一方法,我想我会切换到只使用命令行。

【问题讨论】:

  • 您能否分享一些示例数据和您想要的结果。 “查找每个月最后一条记录的ending_balance 值” 的含义不是很清楚。我敢打赌,相关子查询或派生表会在这里解决问题,但我觉得我在做一些假设。
  • 我真的不想分享对我的工作数据库过于具体的信息,但“期末余额”只是数据库每个条目中的值。所以基本上我想从每个月的最后一个条目中选择一列。
  • 你不能简单地在两个日期之间使用运算符吗?这样你在上限和下限之间有更多的控制权,得到你想要的!
  • 我该怎么做才能将日期设置为每行的月份?我知道如何提供具体日期,或使用 now(),但我不知道一年中的每个月或所有时间我会如何做。

标签: postgresql postgresql-9.3


【解决方案1】:

此查询将对您有所帮助。

每年的特定月份。

select * from 
(select 
concat(extract(month from request_date):: integer,
extract(year from request_date)::integer) as dt
from table1) as a
group by dt

只需添加每个组的sum

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-19
    相关资源
    最近更新 更多