表转换为Oracle的另一种方式

时间:2016-11-23 10:18:34

标签: sql oracle unpivot

ID UserId G_NEWS L_NEWS R_NEWS

 1  210   90     160     99
 2  111   89     120     76

我想像这样转移表格(每次我只想要一个用户的记录。),

 Column_names Values

 G_NEWS       90  
 L_NEWS       160  
 R_NEWS       99

通过使用以下查询,我可以检索列名,但我如何获得特定用户的值。

 SELECT COLUMN_NAME 
 FROM ALL_TAB_COLUMNS 
 WHERE TABLE_NAME='TBL_NEWS';

2 个答案:

答案 0 :(得分:1)

听起来像unpivot 请参阅示例文档:unpivot sample 如果列可以动态更改 - 它可以是动态sql,提供列的列表

 with matrix as(
 select
   1 as ID
  ,210 as UserId
  ,90 as G_NEWS
  ,160 as L_NEWS
  ,99 as R_NEWS
 from dual
 union all
 select
   2 as ID
  ,111 as UserId
  ,89 as G_NEWS
  ,120 as L_NEWS
  ,76 as R_NEWS
  from dual)   
select column_name, val from matrix
unpivot
(
  val
    for column_name in ("G_NEWS","L_NEWS","R_NEWS")
)
 where userId = 111
order by userId, column_name

result of test query for user 111:
1   G_NEWS  89
2   L_NEWS  120
3   R_NEWS  76

答案 1 :(得分:0)

简单的方法是按照上面的评论;

create table test_table
(id number,userid number,g_news number, l_news number, r_news number)
/
insert into test_table
VALUES(1,210,90,160,99)
/
insert into test_table
VALUES(2,211,89,120,76)
/
commit
/

SELECT 'G_NEWS' AS column_name ,g_news AS col_values FROM test_table WHERE id = 1
union all
SELECT 'L_NEWS',l_news FROM test_table WHERE id = 1
union all
SELECT 'R_NEWS',r_news FROM test_table WHERE id = 1

结果;

COLUMN COL_VALUES
------ ----------
G_NEWS         90
L_NEWS        160
R_NEWS         99