如果您使用的是 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 中引入的 OraclePIVOT
子句实现相同的目的:
SELECT *
FROM doc_tab
PIVOT (
MAX(document_id) FOR document_type IN ('Voters ID','Pan card','Drivers licence')
);
两种解决方案的 SQLFiddle 示例:SQLFiddle example
在此处阅读有关旋转的更多信息:Tim Hall 的 Pivot In Oracle