在oracle中使用asc顺序将行转换为列

时间:2018-01-31 10:53:45

标签: sql oracle

 SELECT * FROM 
  ( 
    SELECT TEST_NAME, SBNO, VAL
    FROM TABLE1

  ) 
  PIVOT ( 
    MAX(VAL) 
  FOR SBNO in (1 value1, 2 value2, 3 value3 ));

输出:

enter image description here

我想按升序显示数据,如下所示:

2.3,2.4,2.5

但结果是

2.3,2.5,2.4

2 个答案:

答案 0 :(得分:0)

这样就可以了。我创建了一个新的SBNO列,按test_namevalue排序,然后PIVOT运算符将完成剩下的工作。

;with cte as (
    select
        test_name
        ,val
        ,'Value' + cast(ROW_NUMBER() over (partition by test_name order by test_name, val) as varchar(5)) as new_SBNO
    from TABLE1
)
select *
from cte
pivot (
    max(val)
    for new_SBNO in (value1, value2, value3)
) pvt

答案 1 :(得分:0)

我会使用条件聚合来做到这一点:

select test_name,
       max(case when seqnum = 1 then val end) as value_1,
       max(case when seqnum = 2 then val end) as value_2,
       max(case when seqnum = 3 then val end) as value_3
from (select t1.*,
             row_number() over (partition by test_name order by val asc) as seqnum
      from table1 t1
     ) t1
group by test_name;

您可以使用pivot表达此信息。在Oracle中,pivot甚至可以更快一些。我发现条件聚合更灵活,更易于实现。