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

时间:2017-07-18 03:30:43

标签: sql json oracle distinct

表A包含3列作为年份,商店和销售。

表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 ......是Shop Shop的不同值。

1 个答案:

答案 0 :(得分:0)

你想要的是一个“枢轴”,如下所述:https://www.techonthenet.com/oracle/pivot.php

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

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;

我在SQL Fiddle中设置了上面的例子,它返回了预期的内容。

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