SQL to convert a row with 4 columns to 4 rows with 1 column

Sorry, I know this question has been asked hundreds of times before!

This is my starting SQL:

set linesize 500

with tbl_data AS
 (select 'N' argument1, 'Y' argument2, NULL argument3, 'Y' argument4 from dual)
select * from tbl_data;


ARGUMENT1 ARGUMENT2 ARGUMENT3 ARGUMENT4
--------- --------- --------- ---------
N         Y                   Y        

Is it possible to enter the data in this format:

                COL_HEADING
ARGUMENT1       N
ARGUMENT2       Y
ARGUMENT3       
ARGUMENT4       Y

I have read comments UNPIVOT but can't really work on the syntax to get a single line with 4 columns to appear as 4 rows with 1 column.

Sorry - I realize that I'm probably be lazy and stupid.

Any advice much appreciated, thank you.

Hello

Here's a way to do it with UNPIVOT:

SELECT *.

OF tbl_data

MUST INCLUDE NULL VALUES

(col_heading

FOR column-name IN (argument1

argument2

argument3

argument4

)

)

;

Output:

COLUMN COL_HEADING

--------- -----------

ARGUMENT1 N

ARGUMENT2 Y

ARGUMENT3

ARGUMENT4 Y

Tags: Database

Similar Questions

  • SQL to convert a row with 4 columns, 4 rows by 4 columns

    With the help of Frank Kulash yesterday (https://community.oracle.com/thread/3810284)

    I can now use UNPIVOT start with this:

    with tbl_data AS  
     (select 'N' argument1, 'Y' argument2, NULL argument3, 'Y' argument4 from dual)  
    select * from tbl_data;  
    
    
    ARGUMENT1 ARGUMENT2 ARGUMENT3 ARGUMENT4  
    --------- --------- --------- ---------  
    N         Y                   Y   
    

    And eventually conversion of a single line of output to 4 rows and 2 columns via:

    with tbl_data AS
     (select 'N' argument1, 'Y' argument2, NULL argument3, 'Y' argument4 from dual)
        SELECT  *
        FROM    tbl_data
        UNPIVOT INCLUDE NULLS
                (    col_heading
                FOR  col_name  IN ( argument1
                                  , argument2
                                  , argument3
                                  , argument4
                                  )
                );
    
        COL_NAME  COL_HEADING
        --------- -----------
        ARGUMENT1 N
        ARGUMENT2 Y
        ARGUMENT3
        ARGUMENT4 Y
    

    I was wondering if there are sort of Frank solution can be modified to include the 2 columns (for example, COL_SEQ and COL_PROMPT) with them, hard coded values for example, '1' for the SEQ and 'TEST' for the GUEST, as I have the solution to a Frank's UNION with another query that returns the 4 columns.

    i.e. the performance:

    COL_NAME  COL_HEADING COL_SEQ     COL_PROMPT
    --------- ----------- ----------- -----------
    ARGUMENT1 N           1           TEST
    ARGUMENT2 Y           1           TEST
    ARGUMENT3             1           TEST
    ARGUMENT4 Y           1           TEST
    

    Thank you

    Hello

    969483 wrote:

    With the help of Frank Kulash yesterday (https://community.oracle.com/thread/3810284)

    I can now use UNPIVOT start with this:

    1. with tbl_data AS
    2. (select "n" argument1, argument2 'Y', NULL argument3, 'Y' double argument4)
    3. Select * from tbl_data;
    4. ARGUMENT1 ARGUMENT2, ARGUMENT3 ARGUMENT4
    5. --------- --------- --------- ---------
    6. N         Y                   Y

    And eventually conversion of a single line of output to 4 rows and 2 columns via:

    1. with tbl_data AS
    2. (select "n" argument1, argument2 'Y', NULL argument3, 'Y' double argument4)
    3. SELECT *.
    4. OF tbl_data
    5. MUST INCLUDE NULL VALUES
    6. (col_heading
    7. FOR column-name IN (argument1
    8. argument2
    9. argument3
    10. argument4
    11. )
    12. );
    13. COLUMN COL_HEADING
    14. --------- -----------
    15. ARGUMENT1 N
    16. ARGUMENT2 Y
    17. ARGUMENT3
    18. ARGUMENT4 Y

    I was wondering if there are sort of Frank solution can be modified to include the 2 columns (for example, COL_SEQ and COL_PROMPT) with them, hard coded values for example, '1' for the SEQ and 'TEST' for the GUEST, as I have the solution to a Frank's UNION with another query that returns the 4 columns.

    i.e. the performance:

    1. COLUMN COL_HEADING COL_SEQ COL_PROMPT
    2. --------- ----------- ----------- -----------
    3. ARGUMENT1 N 1 TEST
    4. ARGUMENT2 Y 1 TEST
    5. ARGUMENT3 1 TEST
    6. ARGUMENT4 Y 1 TEST

    Thank you

    Of course, you can include constants hardcoded in any set of results; just put constants in the SELECT clause and assign aliases for columns.

    Don't forget, I havef you need anything in the more SELECT clause *, then * must be qualified with a table name or alias, so that in this case, you can do something like:

    SELECT d. *.

    1 AS col_seq

    'TEST' AS col_prompt

    OF tbl_data

    MUST INCLUDE NULL VALUES

    (col_heading

    FOR column-name IN (argument1

    argument2

    argument3

    argument4

    )

    d

    ;

  • Is there a way to convert 8 rows by 2 columns of 2 rows of 8 columns?

    I tried, but came to a stop...

    How can I convert 8 rows by 2 columns of 2 rows of 8 columns?

    as shown in the attached vi

    Thank you very much...

    JohnMc19 wrote:

    Hi Diego2000,

    Tried using the conversion table 2D function found in the functions Array palette, it's what you're asking.

    Kind regards

    No, for the necessary transformation reshaping table is required, not transpose.

    Compare:

    Andrey.

  • SQL error: ORA-01779: cannot modify a column that matches a key examine

    Hi all

    The requirement is that I have two tables s_party_d and S_CONTACT_d. the need to update the column name with FST_NAME | ',' | Last_name when column rowid in both tables are equal. I used the query previously below: -.

    Update
    (select
    E1. Name,
    e.FST_NAME,
    Select
    Of
    s_party_d e1,
    E S_CONTACT_d
    where
    E1. Game of ROW_ID = e.ROW_ID)
    name = FST_NAME | ',' | LAST_NAME;

    But I get the error message when executing the query

    Error in the command line: 31 column: 3
    Error report:
    SQL error: ORA-01779: cannot modify a column that is mapped to a table not preserved key
    01779 00000 - 'impossible to change a column that is mapped to a non-preserved table at key'
    * Cause: An attempt was made to insert or update columns in a join finds out who
    map to a table not kept the key.
    * Action: Change the directly underlying base tables.

    Can U please tell me why this error and how to solve?

    Thank you
    Mathon

    Mathon wrote:

    So, I have to look into some other method... I can't achieve this using a single update statement...

    Well, no matter what you do you need to decide what FST_NAME | ',' | Name to use. As I already pointed out for each line of the line of the s_party_d table there are several rows in table S_CONTACT_d. Again, you must yo decide what S_CONTACT_d table row you want to use. For example:

    update s_party_d e1
       set e1.name = (
                      select  max(e.FST_NAME) ||', '|| max(e.LAST_NAME)
                        from  S_CONTACT_d e
                        where e1.ROW_ID=e.ROW_ID
                     )
     where e1.ROW_ID in (
                         select  e.ROW_ID
                           from  S_CONTACT_d e
                        )
    /
    

    SY.

  • How to convert .vi .exe with the student LabView version

    Hello

    I would like to know if it is possible to convert .vi .exe with the student Labview version.

    Thank you

    N ° if I remember correctly, your license agreement specifically prohibits this. You would have to buy the professional version of LabVIEW. No real need for a student to create an exe file.

  • What would cause a SQL server to blue screen with FFFFF81001BA5198 code

    What would cause a SQL server to blue screen with FFFFF81001BA5198 code

    Hello

    Your question of Windows is more complex than what is generally answered in the Microsoft Answers forums. It is better suited for the IT Pro TechNet public. Please post your question in the Windows Server forum. You can follow the link to your question:

    http://social.technet.Microsoft.com/forums/en-us/category/WindowsServer

  • Update of security for sql server sp3 KB94981 fails with error 2B 33

    Each update for SQL Server 2005 on my computer Vista Home Premuim fails. The most recent example is:

    Update of security for sql server sp3 KB94981 fails with error 2B 33

    for SP2, it was

    Security for sql server sp2 KB960089 update fails with error 6AA

    Other updates have been ad are successful, although I found out recently that it is the recovery disc option to create under maintenance contract. I fdound the recdisk.exe file, but running it does nothing.

    Mike

    Maybe check this forum:

    SQL Installation of Server & upgrade
    http://social.msdn.Microsoft.com/forums/en-us/sqlsetupandupgrade/threads/

    TaurArian [MVP] 2005-2010 - Update Services

  • PDF documents converted into Word with ExportPDF are secure?

    PDF documents converted into Word with ExportPDF are secure?

    Hi stonermarker,

    Please see this thread on the security of the documents on service online ExportPDF: Adobe ExportPDF security

    Best,

    Sara

  • How to convert a PDF with handwritten signature?

    How to convert a PDF with handwritten signature?

    Hi Lotus1215,

    Once the document is signed this document, we can edit, where the conversion is not possible

    Please see the article mentioned below

    http://forums.Adobe.com/docs/doc-1515

    I would like to know if you have any further questions.

    Kind regards

    ~ Dominique

  • Can I convert a server with software RAID with cold clone CD?

    I have a win2k3 server that has two disks (RAID 1 software), I can convert the server with software RAID with cold clone CD?

    Yes

    ___________________________________

    VMX-settings- WS FAQ -[MOAcd | http://sanbarrow.com/moa241.html]- VMDK-manual

  • Convert previously converted from raw with Adobe DNG converter files?

    It seems that I'm not able to convert my raw files that have already been previously converted to DNG with the dng converter.  I am wanting to start editing everything new with the raw image, but before I can start editing a raw image, I have to convert it to a .dng.  Why doesn't the converter program let me convert the raw file again and give me the opportunity to appoint differently than the first file?  What I am doing wrong?

    If not, is it possible I can say ACR (whether in bridge or photoshop) to get rid of all the changes made on the first converted .dng file and start over again with image in camera?

    Thanks for any help!

    I don't know why your DNG Converter has stopped working.  You have successfully updated to a later version?  But you don't need to go through this process again.  In Bridge, just click on the images and there is an option to reset the Camera Raw settings.  Or, inside of Camera Raw, press the Alt key and a button will change to "Reset".  In both cases, all the camera raw settings are erased, giving you the image as it has been downloaded.

  • SQL query to identify customers with 2 identification codes

    Every morning!

    Here is the configuration:

    create the table adam_test
    (
    char (6) of the ACCT.
    Tank code (3)
    );

    insert into adam_test values ('100000 ', ' 100');
    insert into adam_test values ('100001 ', ' 100');
    insert into adam_test values ('100001 ', ' 200');
    insert into adam_test values ('100001 ', ' 300');
    insert into adam_test values ('100002 ', ' 200');
    insert into adam_test values ('100003 ', ' 100');
    insert into adam_test values ('100004 ', ' 100');
    insert into adam_test values ('100004 ', ' 200');

    I need to write a SQL select to identify accounts with codes 100 and 200. All other accounts should be ignored.

    Write the output for this example:

    ACCT
    100001
    100004

    I don't know that it's ridiculously simple but nevertheless stuck.

    Thank you!
    Adam
    select acct
      from adam_test
     where code in ('100','200')
     group by acct
    having count(distinct code) = 2
    
  • SQL Loader - ignore the lines with "rejected - all null columns."

    Hello

    Please see the attached log file. Also joined the table creation script, data file and the bad and throw the files after execution.

    Sqlldr customer in the version of Windows-

    SQL * Loader: release 11.2.0.1.0 - Production

    The CTL file has two clauses INTO TABLE due to the nature of the data. The data presented are a subset of data in the real world file. We are only interested in the lines with the word "Index" in the first column.

    The problem we need to do face is, according to paragraph INTO TABLE appears first in the corresponding CTL lines file to the WHEN CLAUSE it would insert and the rest get discarded.

    1. statement of Create table : create table dummy_load (varchar2 (30) name, number, date of effdate);

    2. data file to simulate this issue contains the lines below 10. Save this as name.dat. The intention is to load all of the rows in a CTL file. The actual file would have additional lines before and after these lines that can be discarded.

    H15T1Y Index | 2. 19/01/2016 |

    H15T2Y Index | 2. 19/01/2016 |

    H15T3Y Index | 2. 19/01/2016 |

    H15T5Y Index | 2. 19/01/2016 |

    H15T7Y Index | 2. 19/01/2016 |

    H15T10Y Index | 2. 19/01/2016 |

    CPDR9AAC Index | 2. 15/01/2016 |

    MOODCAVG Index | 2. 15/01/2016 |

    H15TXXX Index | 2. 15/01/2016 |

    H15TXXX Index | 2. 15/01/2016 |

    3. the CTL file - name.ctl

    DOWNLOAD THE DATA

    ADD

    IN THE TABLE dummy_load

    WHEN (09:13) = "Index".

    TRAILING NULLCOLS

    (

    COMPLETED name BY ' | ',.

    rate TERMINATED BY ' | '.

    COMPLETED effdate BY ' | '. ' TO_DATE (: effdate, "MM/DD/YYYY").

    )

    IN THE TABLE dummy_load

    WHEN (08:12) = "Index".

    TRAILING NULLCOLS

    (

    COMPLETED name BY ' | ',.

    rate TERMINATED BY ' | '.

    COMPLETED effdate BY ' | '. ' TO_DATE (: effdate, "MM/DD/YYYY").

    )

    invoke SQL loader in a file-> beats

    C:\Oracle\product\11.2.0\client\bin\sqlldr USERID = myid/[email protected] CONTROL=C:\temp\t\name.ctl BAD=C:\temp\t\name_bad.dat LOG=C:\temp\t\name_log.dat DISCARD=C:\temp\t\name_disc.dat DATA=C:\temp\t\name.dat

    Once this is run, the following text appears in the log file (excerpt):

    Table DUMMY_LOAD, charged when 09:13 = 0X496e646578 ('Index' character)

    Insert the option in effect for this table: APPEND

    TRAILING NULLCOLS option in effect

    Column Position Len term Encl. Datatype name

    ------------------------------ ---------- ----- ---- ---- ---------------------

    NAME                                FIRST     *   |       CHARACTER

    RATE                                 NEXT     *   |       CHARACTER

    EFFDATE NEXT * |       CHARACTER

    SQL string for the column: ' TO_DATE (: effdate, "MM/DD/YYYY").

    Table DUMMY_LOAD, charged when 08:12 = 0X496e646578 ('Index' character)

    Insert the option in effect for this table: APPEND

    TRAILING NULLCOLS option in effect

    Column Position Len term Encl. Datatype name

    ------------------------------ ---------- ----- ---- ---- ---------------------

    NAME                                 NEXT     *   |       CHARACTER

    RATE                                 NEXT     *   |       CHARACTER

    EFFDATE NEXT * |       CHARACTER

    SQL string for the column: ' TO_DATE (: effdate, "MM/DD/YYYY").

    Record 1: Ignored - all null columns.

    Sheet 2: Cast - all null columns.

    Record 3: Ignored - all null columns.

    Record 4: Ignored - all null columns.

    Sheet 5: Cast - all null columns.

    Sheet 7: Discarded - failed all WHEN clauses.

    Sheet 8: Discarded - failed all WHEN clauses.

    File 9: Discarded - failed all WHEN clauses.

    Case 10: Discarded - failed all WHEN clauses.

    Table DUMMY_LOAD:

    1 row loaded successfully.

    0 rows not loaded due to data errors.

    9 lines not loading because all WHEN clauses were failed.

    0 rows not populated because all fields are null.

    Table DUMMY_LOAD:

    0 rows successfully loaded.

    0 rows not loaded due to data errors.

    5 rows not loading because all WHEN clauses were failed.

    5 rows not populated because all fields are null.


    The bad file is empty. The discard file has the following

    H15T1Y Index | 2. 19/01/2016 |

    H15T2Y Index | 2. 19/01/2016 |

    H15T3Y Index | 2. 19/01/2016 |

    H15T5Y Index | 2. 19/01/2016 |

    H15T7Y Index | 2. 19/01/2016 |

    CPDR9AAC Index | 2. 15/01/2016 |

    MOODCAVG Index | 2. 15/01/2016 |

    H15TXXX Index | 2. 15/01/2016 |

    H15TXXX Index | 2. 15/01/2016 |


    Based on the understanding of the instructions in the CTL file, ideally the first 6 rows will have been inserted into the table. Instead the table comes from the line 6' th.

    NAMERATEEFFDATE
    H15T10Y Index2January 19, 2016



    If the INTO TABLE clauses were put in the CTL file, then the first 5 rows are inserted and the rest are in the discard file. The line 6' th would have a ""rejected - all columns null. "in the log file. "


    Could someone please take a look and advise? My apologies that the files cannot be attached.

    Unless you tell it otherwise, SQL * Loader assumes that each later in the table and what clause after the first back in the position where the previous left off.  If you want to start at the beginning of the line every time, then you need to reset the position using position (1) with the first column, as shown below.  Position on the first using is optional.

    DOWNLOAD THE DATA

    ADD

    IN THE TABLE dummy_load

    WHEN (09:13) = "Index".

    TRAILING NULLCOLS

    (

    name POSITION (1) TERMINATED BY ' | '.

    rate TERMINATED BY ' | '.

    COMPLETED effdate BY ' | '. ' TO_DATE (: effdate, "MM/DD/YYYY").

    )

    IN THE TABLE dummy_load

    WHEN (08:12) = "Index".

    TRAILING NULLCOLS

    (

    name POSITION (1) TERMINATED BY ' | '.

    rate TERMINATED BY ' | '.

    COMPLETED effdate BY ' | '. ' TO_DATE (: effdate, "MM/DD/YYYY").

    )

  • SQL help - Need help to rotate the columns to rows

    I have a HughesNet to divide the columns into multiple lines. For example:

    EMP_DEPT

    ROWID empid1 ename1 empid2 ename2 empid2 ename2 empid4 ename4 dept4 dep3 dep2 dept1
    100001 1 'SCOTT' 10 2 'DAVE' 20 3 10 4 20 SMITH "MILLER"
    100002 1 'SCOTT' 10 2 'DAVE' 20 3 'MILLER' 20

    Note: EMP_DEPT do not always have information about the 4 employees settled for example in info only 3 employees rank 2 are there

    I need to convert and insert it into the EMPLOYEE table as follows:

    EMPLOYEE

    EmpID ename dept
    1 SCOTT 10
    2 20 DAVE
    3 MILLER 10
    4 SMITH 20

    1 SCOTT 10
    2 20 DAVE
    3 MILLER 20

    Thank you
    KeV

    Hey Kevin,

    Here's one way:

    WITH t AS (
      SELECT level i FROM dual CONNECT BY level <= 4
    )
    SELECT enty_type, enty_name, enty_id
    FROM (
      SELECT case when mod(t.i,2) = 0 then 'DEPARTMENT'
                  else 'EMPLOYEE'
             end as enty_type
           , case t.i
               when 1 then emp_name1
               when 2 then dept_name1
               when 3 then emp_name2
               when 4 then dept_name2
             end as enty_name
           , case t.i
               when 1 then emp_id1
               when 2 then dept_id1
               when 3 then emp_id2
               when 4 then dept_id2
             end as enty_id
      FROM emp
           CROSS JOIN t
    )
    WHERE enty_id IS NOT NULL
    ;
    

    Another using the MODEL clause:

    SELECT *
    FROM (
      SELECT enty_id, enty_name, enty_type
      FROM emp
      MODEL
      RETURN UPDATED ROWS
      PARTITION BY (pk)
      DIMENSION BY (0 i)
      MEASURES(
         emp_id1, emp_name1
       , emp_id2, emp_name2
       , dept_id1, dept_name1
       , dept_id2, dept_name2
       , cast(null as number(10)) enty_id
       , cast(null as varchar2(200)) enty_name
       , cast(null as varchar2(30)) enty_type
      )
      RULES (
         enty_type[1] = 'EMPLOYEE' , enty_id[1] = emp_id1[0], enty_name[1] = emp_name1[0]
       , enty_type[2] = 'EMPLOYEE' , enty_id[2] = emp_id2[0], enty_name[2] = emp_name2[0]
       , enty_type[3] = 'DEPARTMENT' , enty_id[3] = dept_id1[0], enty_name[3] = dept_name1[0]
       , enty_type[4] = 'DEPARTMENT' , enty_id[4] = dept_id2[0], enty_name[4] = dept_name2[0]
      )
    )
    WHERE enty_id IS NOT NULL
    ;
    

    Published by: odie_63 on 8 Dec. 2010 21:00

  • Convert the equivalent function stragg columns in oracle sql

    Hello

    Sorry I forgot my version of Oracle:
    SQL> select * from v$version;
    
    BANNER
    ----------------------------------------------------------------
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bi
    PL/SQL Release 10.2.0.3.0 - Production
    CORE    10.2.0.3.0      Production
    TNS for 64-bit Windows: Version 10.2.0.3.0 - Production
    NLSRTL Version 10.2.0.3.0 - Production
    I searched on google but I have not found the solution.


    I'm looking for a function equivalent to the SQL stragg discoverer.


    Note: stragg function convert columns in lines.

    Thank you
    SELECT   deptno, stragg ('-' || ename)
        FROM emp_test
    GROUP BY deptno;
    
    
        DEPTNO STRAGG_STR                                                  
    ---------- ------------------------------------------------------------
            10 -CLARK-KING-MILLER                                          
            20 -SMITH-FORD-ADAMS-SCOTT-JONES                               
            30 -ALLEN-BLAKE-MARTIN-TURNER-JAMES-WARD                       
    
    
    3 rows selected.
    Published by: Salim champion 2010-01-29 08:32

    Hello Salim
    This feature does not exist inside the discoverer.

    My suggestion would be to create a SQL function, then import it in Finder using the System Administration tool. Now, you will be able to pass the deptno to the function and the function returns a single string containing the concatenated names.

    This isn't a function difficult to write and if you would like some help please let us know.

    Best wishes
    Michael

Maybe you are looking for