Oracle列行分为多列

时间:2016-12-21 02:12:00

标签: sql oracle

从表中选择年份,代码,基准;

结果:年份,代码,基准

    2017, MKPI00719, 1
    2017, MKPI00719, benchmark0001
    2017, MKPI00719, 2016
    2017, MKPI00719, 90
    2017, MKPI00743, 1
    2017, MKPI00743, benchmark34455
    2017, MKPI00743, 2013
    2017, MKPI00743, 900

我想在此下面显示

 Year, code,        ben_value, desc,          b_year, kpi 
 2017, MKPI00719,   1,      benchmark0001,  2016,   90 
 2017, MKPI00743,  1,       benchmark87899, 2013,   900 

这个senario ben_value总是一个。这是独特的,分组的  年,代码。

请帮我看看如何用oracle编写我的sql

1 个答案:

答案 0 :(得分:0)

如果您有序列号,那么我认为以下内容可以解决您的问题:

select year, code,
       max(case when seqnum = 1 then benchmark end) as ben_value,
       max(case when seqnum = 2 then benchmark end) as description,
       max(case when seqnum = 3 then benchmark end) as b_year,
       max(case when seqnum = 4 then benchmark end) as kpi
from (select t.*,
             row_number() over (partition by year, code order by sequence_no) as seqnum
      from t
     ) t
group by year, code