postgresql 获取一个月的最大值以及与前一个月的差值

flmtquvp  于 2023-04-20  发布在  PostgreSQL
关注(0)|答案(1)|浏览(200)

我用的是PostgreSQL 9.6。
我有一个包含电表数据的表,例如每个小时有一行,这只是一个例子,所以每个月有很多行:
| 米特里德|时间|价值|
| --------------|--------------|--------------|
| 1|2022-07-01 00:00:00|五四八|
| 1|2022-07-01 01:00:00|五四九|
| 1|2022-07-02 12:00:00|五五五|
| 1|2022-08-01 04:00:00|六百五十|
| 1|2022-08-14 03:00:00|七百|
| 1|2022-09-02 14:00:00|八二一|
我想显示每个月的最大计量器值(即月底的值),我想显示每个月的值与上个月相比变化了多少。
所以我想要一个这样的结果(这个例子是基于一些其他的数据)
| 日期|最大|差异|
| --------------|--------------|--------------|
| 2023-01-01 2023-01-01|1|零|
| 2023-02-01 2023-02-01 2023-02-01|九十六|九十五|
| 2023-03-01 2023-03-01 2023-03-01|二百八十九|一百九十三|
我想出了这个查询,但它包含4个选择,有没有更简单/更好的方法来做到这一点?它使用row_number为每个月的最大值分配“1”,然后使用lag获得前几个月的值。

select date, max, max - lag "diff" from (
select date, max, lag(max) over (order by max) from (
select * from (
select  date(date_trunc('month', time)), max(value), row_number() over (partition by date(date_trunc('month', time)) order by value desc) rn
    
    from public.electricitymetering where "meterid" = '1'

group by date_trunc('month', time), value 
order by date(date_trunc('month', time)) desc ) as result
where rn = 1
    ) as temp ) as final
vmdwslir

vmdwslir1#

是的,有一个更简单的方法,基于this example of the lag function

with monthly_maxes as (
   select date(date_trunc('month', time)) as date, max(value) as max,
   from public.electricitymetering where "meterid" = '1'
   group by date(date_trunc('month', time))
)
select date, max, max - lag(max, 1) OVER (ORDER BY date) diff
from monthly_maxes;

相关问题