Saturday, February 15, 2020

Display row data in column using SQL query

By using Union ALL you will display row format records in column.

Below is an Example:
Follow below steps to convert row in column-

Step 1) Create Table and insert record:

         CREATE TABLE xx_emp_data ( emp_name VARCHAR2(50)
                                                              , emp_number VARCHAR2(50)
                                                              , salary NUMBER
                                                             );

          INSERT INTO xx_emp_data VALUES ('Sunil', 'EMP_007', 60000);
          COMMIT;

          SELECT * FROM xx_emp_data;

          Output:

         -------------------------------------------------------------
         EMP_NAME      EMP_NUMBER      SALARY
  -------------------------------------------------------------
          Sunil                    EMP_007                 60000
          -------------------------------------------------------------

Step 2) Using Union ALL you convert row into column

         SELECT 'Emp_Name' AS ColName,
                          Emp_name AS COLVALUE
          FROM xx_emp_data
          UNION ALL
          SELECT 'Emp_Number' AS ColName,
                          Emp_Number AS COLVALUE
          FROM xx_emp_data
          UNION ALL
          SELECT 'Salary' as ColName,
                          CAST(Salary AS VARCHAR(50)) AS COLVALUE
          FROM xx_emp_data;

        Output:

        ---------------------------------------
        COLNAME        COLVALUE
        ---------------------------------------
        Emp_Name           Sunil
        Emp_Number       EMP_007
        Salary                    60000
        ---------------------------------------

No comments:

Post a Comment

Steps to get ZPL code output using Zebra viewer - Online

Introduction ZPL is a print language used by many label printers. A print language is a set of commands that can be used to draw elements li...