我有一个这种形式的表(这只是局部视图,表包含100多列)。
LOAN NUMBER DOCUMENT_TYPE DOCUMENT_ID
992452533663 Voters ID XPD0355636
992452533663 Pan card CHXPS5522D
992452533663 Drivers licence DL-0420110141769
对于单个贷款号码,我有三种文件作为证据。我希望将这些细节转换为列并采用以下形状:
LOAN NUMBER VOTERS_ID PAN_CARD DRIVERS LICENCE
992452533663 XPD0355636 CHXPS5522D DL-0420110141769
如何解决这个问题?
答案 0 :(得分:11)
您可以使用pivot
query执行此操作,如下所示:
select * from (
select LOAN_NUMBER, DOCUMENT_TYPE, DOCUMENT_ID
from my_table t
)
pivot
(
MIN(DOCUMENT_ID)
for DOCUMENT_TYPE in ('Voters ID','Pan card','Drivers licence')
)
答案 1 :(得分:8)
如果您使用的是Oracle 10g,则可以使用DECODE
函数将行转移到列中:
CREATE TABLE doc_tab (
loan_number VARCHAR2(20),
document_type VARCHAR2(20),
document_id VARCHAR2(20)
);
INSERT INTO doc_tab VALUES('992452533663', 'Voters ID', 'XPD0355636');
INSERT INTO doc_tab VALUES('992452533663', 'Pan card', 'CHXPS5522D');
INSERT INTO doc_tab VALUES('992452533663', 'Drivers licence', 'DL-0420110141769');
COMMIT;
SELECT
loan_number,
MAX(DECODE(document_type, 'Voters ID', document_id)) AS voters_id,
MAX(DECODE(document_type, 'Pan card', document_id)) AS pan_card,
MAX(DECODE(document_type, 'Drivers licence', document_id)) AS drivers_licence
FROM
doc_tab
GROUP BY loan_number
ORDER BY loan_number;
输出:
LOAN_NUMBER VOTERS_ID PAN_CARD DRIVERS_LICENCE ------------- -------------------- -------------------- -------------------- 992452533663 XPD0355636 CHXPS5522D DL-0420110141769
使用11g中引入的Oracle PIVOT
子句可以实现相同的目的:
SELECT *
FROM doc_tab
PIVOT (
MAX(document_id) FOR document_type IN ('Voters ID','Pan card','Drivers licence')
);
两个解决方案的SQLFiddle示例: SQLFiddle example
在此处阅读有关透视的更多信息:Pivot In Oracle by Tim Hall
答案 2 :(得分:3)
select * FROM doc_tab
PIVOT
(
Min(document_id)
FOR document_type IN ('Voters ID','Pan card','Drivers licence')
)
outputs as this