为月环比变化创建一个数据透视表 table

Create a pivot table for Month over Month variation

我从查询中返回了这些记录

+---------+--------------+-----------+----------+
| Country | other fields |   sales   |   date   |
+---------+--------------+-----------+----------+
| US      | 1            |  0.00  | 01/01/21 |
| CA      | 1            |  0.00  | 01/01/21 |
| UK      | 1            |  0.00  | 01/01/21 |
| FR      | 1            |  0.00  | 01/01/21 |
| US      | 1            |  0.00  | 01/02/21 |
| CA      | 1            |  0.00  | 01/02/21 |
| UK      | 1            |  0.00  | 01/02/21 |
| FR      | 1            |  0.00  | 01/02/21 |

我想显示一个月与上一个月的销售额变化,如下所示:

| Country | 01/02/21     | 01/01/21  | Var%     |
| US      |  0.00     |  0.00  | 100%     |
| CA      |  0.00     |  0.00  | 100%     |
| FR      |  0.00     |  0.00  | 100%     |
+---------+--------------+-----------+----------+

如何使用 Postgres 查询完成?

如果你总是只比较两个月:

select country
    , sum(sales) filter (where date ='01/01/21')  month1
    , sum(sales) filter (where date ='01/02/21')  month2
    , ((sum(sales) filter (where date ='01/02/21') /sum(sales) filter (where date ='01/01/21')) - 1) * 100 var
from tablename
where date in ('01/01/21' , '01/02/21')
group by country

您还可以从 tablefunc 扩展中查看 crosstab,它基本上与上述查询相同。

CREATE EXTENSION IF NOT EXISTS tablefunc;

select * ,("01/02/21" /"01/01/21") - 1) * 100 var 
from(
select * from crosstab ('select Country,date , sales from tablename')
as ct(country varchar(2),"01/01/21" money , "01/02/21" money)
) t

有关交叉表的详细信息,请参阅tablefunc

但是如果您想在行而不是列中显示日期,您可以轻松地将其概括为所有日期:

select * 
   , ((sales / LAG(sales,1,1) over (partition by country order by date)) -1)* 100  var
from 
country