Home > Database > Mysql Tutorial > How to Transform Rows into Columns in Oracle Using DECODE and PIVOT?

How to Transform Rows into Columns in Oracle Using DECODE and PIVOT?

Susan Sarandon
Release: 2024-12-31 15:54:21
Original
604 people have browsed it

How to Transform Rows into Columns in Oracle Using DECODE and PIVOT?

How to Convert Rows to Columns in Oracle

In Oracle, you can face scenarios where data is arranged in rows but it needs to be displayed in a columnar fashion. This article delves into the methods for converting rows into columns using the DECODE function or the PIVOT clause.

Consider the following table containing loan details:

LOAN NUMBER   DOCUMENT_TYPE                DOCUMENT_ID
992452533663  Voters ID                    XPD0355636
992452533663  Pan card                     CHXPS5522D
992452533663  Drivers license              DL-0420110141769
Copy after login

To pivot the rows into columns, you can use the DECODE function:

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 license', document_id)) AS drivers_licence
  FROM
    doc_tab
GROUP BY loan_number
ORDER BY loan_number;
Copy after login

This query will produce the following output:

LOAN_NUMBER   VOTERS_ID            PAN_CARD             DRIVERS_LICENCE    
------------- -------------------- -------------------- --------------------
992452533663  XPD0355636           CHXPS5522D           DL-0420110141769     
Copy after login

In Oracle versions 11g and above, the PIVOT clause provides a simpler way to achieve the same result:

SELECT *
  FROM doc_tab
PIVOT (
  MAX(document_id) FOR document_type IN ('Voters ID','Pan card','Drivers license')
);
Copy after login

Both methods can effectively pivot rows into columns, allowing you to manipulate and display your data in the preferred format.

The above is the detailed content of How to Transform Rows into Columns in Oracle Using DECODE and PIVOT?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template