如何计算当前月份/六个月前的结果,并在Postgresql中显示为百分比变化?

42fyovps  于 2022-12-03  发布在  PostgreSQL
关注(0)|答案(1)|浏览(80)
create table your_table(type text,compdate date,amount numeric);
insert into your_table values
('A','2022-01-01',50),
('A','2022-02-01',76),
('A','2022-03-01',300),
('A','2022-04-01',234),
('A','2022-05-01',14),
('A','2022-06-01',9),
  
('B','2022-01-01',201),
('B','2022-02-01',33),
('B','2022-03-01',90),
('B','2022-04-01',41),
('B','2022-05-01',11),
('B','2022-06-01',5),
  
('C','2022-01-01',573),
('C','2022-02-01',77),
('C','2022-03-01',109),
('C','2022-04-01',137),
('C','2022-05-01',405),
('C','2022-06-01',621);

我尝试计算以显示每种类型从今天之前6个月的美元百分比变化。例如:

  • A型在6个月内下降了-82%。
  • B型下降-97.5%
  • C型增加+8.4%。

我如何在postgresql中混合其他语句来编写这个语句?

vuktfyat

vuktfyat1#

它看起来像是与5个月前相比,而不是6个月前,2022年6月1日不是今天的日期。
Join基于匹配类型和期望的时间差将该表与其自身进行比较。

select 
  b.type,
  b.compdate,
  a.compdate "6 months earlier",
  b.amount "amount 6 months back",
  round(-(100-b.amount/a.amount*100),2) "change"
from your_table a 
    inner join your_table b 
        on a.type=b.type 
        and a.compdate = b.compdate - '5 months'::interval;
    

-- type |  compdate  | 6 months earlier | amount 6 months back | change
--------+------------+------------------+----------------------+--------
-- A    | 2022-06-01 | 2022-01-01       |                    9 | -82.00
-- B    | 2022-06-01 | 2022-01-01       |                    5 | -97.51
-- C    | 2022-06-01 | 2022-01-01       |                  621 |   8.38

相关问题