sql - 如何在 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 会发生什么?
谢谢,
希瓦姆
解决方案
你可能需要:
-- 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
推荐阅读
- c++ - 雅虎财经的股息历史
- node.js - 具有两个项目的 Firebase Functions 服务帐户
- python - 如何使用 BeautifulSoup 获取最新帖子的文本,select()
- azure - Azure 媒体服务价格计算
- python - 加速 pandas groupby 聚合
- windows - 如何使用 FFMPEG 流式传输桌面,并将输出设置为 http://127.0.0.1:8080
- python - 如何使用 python 将 BEP2 BUSD 令牌所有余额转移到另一个安全钱包?
- python - 当 __getattribute__ 和 __getattr__ 存在时,为什么 Python 类实例中会出现“流氓”形状属性?
- flutter - 带有 jsondecode var 输出的 Flutter 条件语句
- azure - azure web 应用程序中插槽的自定义域