我是编码的新手,并不理解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会发生什么?
谢谢,
Shivam
你可能需要:
-- 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
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来编写动态查询,如果您不知道要转动的值或值更多,则需要该动态查询
我从命中和跟踪中解决了我的问题,下面是代码希望它能帮助别人。
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
谢谢,
Shivam