如何将PSQL表增加一年

时间:2019-04-01 01:21:28

标签: sql postgresql

我有一个table,其中:

Company|Date | Value
Best Buy| 2018-06 | 100
Best Buy|2018-07 | 105
Best Buy|2017-06 | 90
Best Buy|2017-07 | 92

我想计算出逐年增长的数字,例如:

Date | YoY growth
2018-06 | 0.11111
2018-07 | 0.1413

当我像这样连接两个表时:

SELECT y1.company, y2.Date, (y2.value/y1.value -1) as YoY_growth
FROM table as y1
LEFT JOIN table as y2
ON y1.company = y2.company AND (y2.date = y1.date + interval '1 year');

在PSQL中,将y1.date增加1年以获得逐年增长的正确方法是什么?该表当前已填充了空值

2 个答案:

答案 0 :(得分:0)

您可以这样做:

SELECT y1.company, y2.Date, (y2.value/y1.value -1) as YoY_growth
FROM table y1 LEFT JOIN
     table y2
     ON y1.company = y2.company AND
          (y2.date || '-01')::date = (y1.date || '-01')::date + interval '1 year');

答案 1 :(得分:0)

假设您确实将日期字段存储为日期类型。这个答案就足够了。否则,我放弃,大声笑:D

DISTINCT ON (company, date_part('month', y1.date))仅选择每个公司的月份。因此,最多每个公司只有12行。

实时测试:http://sqlfiddle.com/#!17/751ad/4

CREATE TABLE progress
    ("company" varchar(7), "date" date, "value" numeric(18,4))
;


INSERT INTO progress
    ("company", "date", "value")
VALUES
    ('BestBuy', '2017-06-01', 90),
    ('BestBuy', '2017-07-01', 92),
    ('BestBuy', '2018-06-01', 100),    
    ('BestBuy', '2018-07-01', 105)
;

SELECT 
     distinct on (y1.company, date_part('month', y1.date))    

     y1.company, 

     to_char(
         first_value(y1.date) 
         over (partition by y1.company, date_part('month', y1.date) 
               order by y1.date desc),
         'YYYY-MM'
     ) as date,     

     (y1.value/y2.value - 1) as YoY_growth

FROM progress as y1
LEFT JOIN progress as y2
ON y1.company = y2.company AND (y2.date = y1.date - interval '1 year');

输出:

| company |    date |         yoy_growth |
|---------|---------|--------------------|
| BestBuy | 2018-06 | 0.1111111111111111 |
| BestBuy | 2018-07 |  0.141304347826087 |