【问题标题】:How to calculate current month / six months ago and result as a percent change in Postgresql?How to calculate current month / six months ago and result as a percent change in Postgresql?
【发布时间】:2022-12-02 05:54:09
【问题描述】:
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);

I am trying to calculate to show the percentage change in $ from 6 months prior to today's date for each type. In example:

  • Type A decreased -82% over six months.
  • Type B decreased -97.5%
  • Type C increased +8.4%.

How do I write this in postgresql mixed in with other statements?

【问题讨论】:

  • Please use plain text for a complete question. Not some image elsewhere

标签: postgresql


【解决方案1】:

It looks like comparing against 5, not 6 months prior, and 2022-06-01 isn't today's date.

Join the table with itself based on the matching type and desired time difference. Demo

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

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 2022-08-17
    • 2022-12-28
    • 2022-12-02
    • 2022-12-16
    • 2022-12-27
    • 2022-12-01
    • 2022-12-27
    • 2022-12-27
    相关资源
    最近更新 更多