从Rows到Column的SQL结果

时间:2018-05-16 02:58:00

标签: sql oracle sqlplus

如何在shell脚本中使用sqlplus以下面的列形式获取sql结果。请注意第1列是标题,第2列是行值(只有1行需要显示为无其他匹配。)

STAT_DATE       20180515

SERVER_NAME   abcd3363

Hits1         112389

Hits2         659405

而选择命令简单,我得到如下。

STAT_DATE   SERVER_NAME     Hits1     Hits2

----------- --------------  -------- --------

20180515    abcd3363        112389   659405  

1 个答案:

答案 0 :(得分:0)

这应该有帮助 -

CREATE TABLE tabl1
    (STAT_DATE varchar2(11), SERVER_NAME varchar2(14), Hits1 varchar2(8), Hits2 varchar2(8))
;

INSERT ALL 
    INTO tabl1 (STAT_DATE, SERVER_NAME, Hits1, Hits2)
         VALUES ('20180515', 'abcd3363', '112389', '659405')
SELECT * FROM dual
;

查询 -

select * from tabl1
unpivot (vals for cols in (STAT_DATE as 'STAT_DATE', SERVER_NAME AS 'SERVER_NAME', Hits1 AS 'Hits1', Hits2 AS 'Hits2'));
;

输出 -

COLS        VALS
STAT_DATE   20180515
SERVER_NAME abcd3363
Hits1       112389
Hits2       659405