获取具有不同类型的 id 值的员工列表作为输出中的列名
Posted
技术标签:
【中文标题】获取具有不同类型的 id 值的员工列表作为输出中的列名【英文标题】:To get list of employees with an id value different type as column name in output 【发布时间】:2020-11-24 12:52:30 【问题描述】:我有一张表empl
,其值如下:
empid id_val id_type
----------------------------
123456 ABCD1234XY SSN
123456 U9876512 PASSPORT
123456 9090876543 UID
123456 V2345677 VOTERID
123457 ABCD1235YZ SSN
123457 V8765120 PASSPORT
123457 8090876541 UID
123457 A2342627 VOTERID
123458 ABCD1236ZZ SSN
123458 X9876510 PASSPORT
123458 9090876599 UID
123459 ABCD1238YY SSN
123459 8080876549 UID
123459 Z2345678 VOTERID
我想要像 ID 类型列表这样的输出作为列的意思:
empid SSN PASSPORT UID VOTERID
--------------------------------------------------
123456 ABCD1234XY U9876512 9090876543 V2345677
123457 ABCD1235YZ V8765120 8090876541 A2342627
123458 ABCD1236ZZ X9876510 9090876599 NULL
123459 ABCD1238YY NULL 8080876549 Z2345678
能否请您帮我获得类似上述格式的输出,其中价值提及为顶部。
【问题讨论】:
【参考方案1】:您可以使用条件聚合:
select empid,
max(case when id_val = 'SSN' then id_type end) as SSN,
max(case when id_val = 'PASSPORT' then id_type end) as PASSPORT,
max(case when id_val = 'UID' then id_type end) as UID,
max(case when id_val = 'VOTERID' then id_type end) as VOTERID
from t
group by empid;
【讨论】:
【参考方案2】:你可以使用PIVOT
:
SELECT *
FROM table_name
PIVOT (
MAX( id_val )
FOR id_type IN (
'SSN' AS ssn,
'PASSPORT' AS passport,
'UID' AS "UID",
'VOTERID' AS voterid
)
)
ORDER BY empid;
其中,对于样本数据:
CREATE TABLE table_name ( empid, id_val, id_type ) AS
SELECT 123456, 'ABCD1234XY', 'SSN' FROM DUAL UNION ALL
SELECT 123456, 'U9876512', 'PASSPORT' FROM DUAL UNION ALL
SELECT 123456, '9090876543', 'UID' FROM DUAL UNION ALL
SELECT 123456, 'V2345677', 'VOTERID' FROM DUAL UNION ALL
SELECT 123457, 'ABCD1235YZ', 'SSN' FROM DUAL UNION ALL
SELECT 123457, 'V8765120', 'PASSPORT' FROM DUAL UNION ALL
SELECT 123457, '8090876541', 'UID' FROM DUAL UNION ALL
SELECT 123457, 'A2342627', 'VOTERID' FROM DUAL UNION ALL
SELECT 123458, 'ABCD1236ZZ', 'SSN' FROM DUAL UNION ALL
SELECT 123458, 'X9876510', 'PASSPORT' FROM DUAL UNION ALL
SELECT 123458, '9090876599', 'UID' FROM DUAL UNION ALL
SELECT 123459, 'ABCD1238YY', 'SSN' FROM DUAL UNION ALL
SELECT 123459, '8080876549', 'UID' FROM DUAL UNION ALL
SELECT 123459, 'Z2345678', 'VOTERID' FROM DUAL;
输出:
EMPID |社保号 |护照 |用户名 |投票人 -----: | :--------- | :------- | :--------- | :-------- 123456 | ABCD1234XY | U9876512 | 9090876543 | V2345677 123457 | ABCD1235YZ | V8765120 | 8090876541 | A2342627 123458 | ABCD1236ZZ | X9876510 | 9090876599 | 空 123459 | ABCD1238YY | 空 | 8080876549 | Z2345678
db小提琴here
【讨论】:
以上是关于获取具有不同类型的 id 值的员工列表作为输出中的列名的主要内容,如果未能解决你的问题,请参考以下文章