如何创建 sql table 以根据当前 date/month 动态更改列的顺序?

How to create sql table that changes dynamically the order of the columns based on current date/month?

我的目标是 table 具有以下结构:

公司名称 2021 年 12 月 2021 年 11 月 2021 年 10 月 ... 2021 年 1 月
Google 70 30 20 ... 80
亚马逊 30 45 34 ... 24
...

它包含每个公司在特定月份内所有客户的信用。

我只想跟踪最近 12 个月的情况(table 每月更新一次)。 在 2022 年 1 月,我希望列顺序更改如下:

公司名称 2022 年 1 月 2021 年 12 月 2021 年 11 月 ... 2021 年 2 月
Google 25 70 30 ... 14
亚马逊 80 30 45 ... 33
...

2022 年 2 月它将发生变化:

公司名称 2022 年 2 月 2022 年 1 月 2021 年 12 月 ... 2021 年 1 月
Google 37 25 70 ... 20
亚马逊 42 80 30 ... 21
...

假设我可以从具有以下结构的 table 中检索信用值:

公司名称 月份 价值
Google 2021 年 12 月 70
亚马逊 2021 年 12 月 30
Google 2021 年 11 月 30
亚马逊 2021 年 11 月 45
...

你知道如何在 SQL 中做到这一点吗?

假设您 table 存储了一个日期(即一个月中的某一天,例如该月的最后一天):

Company Month Value
Google 2021-06-30 70
Amazon 2021-06-30 30
Google 2021-05-31 30
Amazon 2021-05-31 45
... ... ...
Amazon 2020-01-31 123

并且您想要过去十二个月,您可以使用带有 PIVOT 子句或条件聚合的数据透视查询。我在下面的查询中使用后者:

    select 
        company,
        sum(case when trunc(month, 'mm') = trunc(sysdate, 'mm') - interval '12' month then value end) as "12 months ago",
        sum(case when trunc(month, 'mm') = trunc(sysdate, 'mm') - interval '11' month then value end) as "11 months ago",
        ...
        sum(case when trunc(month, 'mm') = trunc(sysdate, 'mm') - interval  '2' month then value end) as  "2 months ago",
        sum(case when trunc(month, 'mm') = trunc(sysdate, 'mm') - interval  '1' month then value end) as  "1 month ago"
    from mytable
    where month < trunc(sysdate, 'mm') and month >= trunc(sysdate, 'mm') - interval '12' month
    group by company
order by company;

在您的应用程序的网格中显示此结果时,您当然可以将列标题更改为相关月份。