【问题标题】:select the unique values in a column to be filed name选择要归档的列中的唯一值 name
【发布时间】:2017-07-18 03:30:42
【问题描述】:

表 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

Shop A,B,C...是 Shop 列的不同值。

【问题讨论】:

标签: sql json oracle distinct


【解决方案1】:

您想要的是此处所述的“枢轴”: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 查询,以便将列动态添加到查询中并相应地执行构造的查询字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-24
    • 2012-03-28
    • 1970-01-01
    • 2013-06-09
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多