如何在SQL中旋转输出表的单列?

时间:2018-09-10 08:07:21

标签: sql oracle oracle11g pivot

我是编码新手,不了解Pivot函数,只是想知道是否有人可以帮助我进行以下查询。

我在下面有一个SQL查询

select distinct hapf.position_code, pg.name
from
hr_all_positions_f hapf, PER_VALID_GRADES_F pvgf, per_grades pg
where
hapf.position_id = pvgf.position_id
and pvgf.grade_id = pg.grade_id
and hapf.position_code = 'ABCD'

这给出如下输出

POSITION_CODE    NAME
ABCD             Grade03
ABCD             Grade04
ABCD             Grade05

但是我想要输出如下

POSITION_CODE    Grade1    Grade2    Grade3
ABCD             Grade03   Grade04   Grade05

有人可以帮助我完成我在SQL查询中需要进行的更改吗?如果我还有另一个要更改其值的列会怎样?

谢谢

湿婆

3 个答案:

答案 0 :(得分:1)

您可能需要:

-- test case
with yourQuery (POSITION_CODE, NAME) as (
    select 'ABCD', 'Grade01' from dual union all
    select 'ABCD', 'Grade02' from dual union all
    select 'ABCD', 'Grade03' from dual
)
-- query
select *
from yourQuery
pivot ( max (Name) for name in
        (
            'Grade01' as Grade1,
            'Grade02' as Grade2,
            'Grade03' as Grade3
         )
       )

给出:

POSITION_CODE GRADE1  GRADE2  GRADE3 
------------- ------- ------- -------
ABCD          Grade01 Grade02 Grade03

如果您需要处理更多的列,则需要编辑代码,因为您需要事先知道结果集的列数和名称:

-- test case
with yourQuery (POSITION_CODE, NAME) as (
    select 'ABCD', 'Grade01' from dual union all
    select 'ABCD', 'Grade02' from dual union all
    select 'ABCD', 'Grade03' from dual union all
    select 'ABCD', 'Grade04' from dual
)
-- query
select *
from yourQuery
pivot ( max (Name) for name in
        (
            'Grade01' as Grade1,
            'Grade02' as Grade2,
            'Grade03' as Grade3,
            'Grade04' as Grade4
         )
       )

因此得到:

POSITION_CODE GRADE1  GRADE2  GRADE3  GRADE4 
------------- ------- ------- ------- -------
ABCD          Grade01 Grade02 Grade03 Grade04

答案 1 :(得分:0)

SELECT POSITION_CODE, Grade03,Grade04,Grade05 FROM   
(SELECT POSITION_CODE, NAME, Value_TO_PIVOT FROM mytable)Tab1  
PIVOT  
(  
SUM(Value_TO_PIVOT) FOR NAME IN (Grade03,Grade04,Grade05)) AS Tab2  
ORDER BY Tab2.POSITION_CODE

您可以参考此link编写动态查询,如果您不知道要透视的值或更多的值,则需要使用动态查询

答案 2 :(得分:0)

我从一开始就解决了我的问题,下面是希望它对其他人有帮助的代码。

    select position_code,
max(case when position_num = 1 and pg_num = 1 then grade_name end) as Grade1,
max(case when position_num = 1 and pg_num = 2 then grade_name end) as Grade2,
max(case when position_num = 1 and pg_num = 3 then grade_name end) as Grade3
from
(
select 
dense_rank() over (order by hapf.position_code) position_num,
dense_rank() over (partition by hapf.position_code order by pg.name) pg_num,
hapf.position_code, 
pg.name as grade_name
from
hr_all_positions_f hapf, PER_VALID_GRADES_F pvgf, per_grades pg
where
hapf.position_id = pvgf.position_id
and pvgf.grade_id = pg.grade_id
and hapf.position_code = 'ABCD'
) group by position_code

谢谢

湿婆