首页 > 解决方案 > 如何在 SQL 中旋转输出表的单列?

问题描述

我是编码新手,不了解 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 查询中进行更改吗?如果我有另一列的值我想 Pivot 会发生什么?

谢谢,

希瓦姆

标签: sqloracleoracle11gpivot

解决方案


你可能需要:

-- 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

推荐阅读