如何在oracle中将多列值转换为单行?

时间:2017-07-10 10:07:37

标签: database oracle

我的确切要求是,如果查询'select amount, quantity from temp_table where type = 5;'的输出是:

amount | quantity

10     |  5

20     |  7

12     |  10

然后,输出应显示为:

amount1 | amount2 | amount3 | quantity1 | quantity2 | quantity3

10      |  20     |  12     |  5        |  7        |   10

2 个答案:

答案 0 :(得分:0)

可能的解决方案可能是:

SELECT LISTAGG(amount, '|') WITHIN GROUP (order by amount) 
|| LISTAGG(quantity, '|')  WITHIN GROUP (order by amount) as result
FROM temp_table where type = 5;

*请记住,列数量和数量的值由空格分隔,因此listagg()表达式中的''。你可以把它改成'|'或者其他任何你喜欢的东西。

干杯

答案 1 :(得分:0)

使用PIVOT

SELECT "1_AMOUNT" AS Amount1,
       "2_AMOUNT" AS Amount2,
       "3_AMOUNT" AS Amount3,
       "4_AMOUNT" AS Amount4,
       "5_AMOUNT" AS Amount5,
       "1_QUANTITY" AS Quantity1,
       "2_QUANTITY" AS Quantity2,
       "3_QUANTITY" AS Quantity3,
       "4_QUANTITY" AS Quantity4,
       "5_QUANTITY" AS Quantity5
FROM   ( SELECT amount, quantity, ROWNUM rn FROM temp_table WHERE type = 5 )
PIVOT  ( MAX( amount ) AS amount,
         MAX( quantity ) AS quantity
         FOR rn IN ( 1, 2, 3, 4, 5 ) );