Sql 在要归档的列名称中选择唯一值

Sql 在要归档的列名称中选择唯一值,sql,json,oracle,distinct,Sql,Json,Oracle,Distinct,表A包含年、商店和销售额三列 表A Year Shop Sales 2015 Shop-A 100 2015 Shop-B 200 2015 Shop-C 300 2016 Shop-A 100 2016 Shop-A 100 2016 Shop-A 100 2017 Shop-A 100 ... 是否可以将格式转换为此格式 Year Shop-A Shop-B Shop-C ... 2015 100 200 300 2016 100 100 100 哪个商店A、

表A包含年、商店和销售额三列

表A

Year Shop   Sales
2015 Shop-A 100
2015 Shop-B 200
2015 Shop-C 300
2016 Shop-A 100
2016 Shop-A 100
2016 Shop-A 100
2017 Shop-A 100
...
是否可以将格式转换为此格式

Year Shop-A Shop-B Shop-C ...
2015 100     200   300
2016 100     100   100
哪个商店A、B、C。。。是column Shop的不同值。

您需要的是一个“枢轴”,如下所述:

下面是一个可能适用于您的示例的查询:

create table TableA(
    Year int,
    Shop varchar2(100),
    Sales int
    );

delete from TableA;
insert into TableA(Year,Shop,Sales) values(2015,'Shop-A',100);
insert into TableA(Year,Shop,Sales) values(2015,'Shop-B',200);
insert into TableA(Year,Shop,Sales) values(2015,'Shop-C',300);
insert into TableA(Year,Shop,Sales) values(2016,'Shop-A',100);
insert into TableA(Year,Shop,Sales) values(2016,'Shop-B',100);
insert into TableA(Year,Shop,Sales) values(2016,'Shop-C',100);
insert into TableA(Year,Shop,Sales) values(2017,'Shop-A',100);  

/* Show the table as is before pivot*/
select * 
from TableA;

/* The pivoted data. Note that liberties were taken to correct the 2016 - ShopA sales data. */
select *
from
(
    select 
        year,
        sales,
            shop
    from TableA
)
pivot
(
    max(sales)
    for shop in('Shop-A','Shop-B','Shop-C')
)
order by year;
我在a中设置了上面的示例,它返回了预期的结果


请注意,PIVOT子句有一个缺点,即FOR子句中列出的值在查询中是静态的。解决此问题的唯一方法是使用动态SQL构建PIVOT查询,以便将列动态添加到查询中,并相应地执行构造的查询字符串。

您尝试过什么吗?谷歌“PivotQuerySQL”来看看如何做到这一点。检查这个。这就是你要找的。