Values of Colum as separate columns

I have a table that looks like this:

Company (varchar),
FieldName (varchar)
Valuex (varchar)

Data can look like this:

Company Fieldname valuex
------------- --------------- -----------

John 123 name
MiddleName 123 C
LastName 123 Smith

I would like to write a query that comes out like this:

MiddleName t first name last name company
------------- ------------ ---------------- ------------
Smith John 123 C



It can be? Thanks in advance.

Hello

Column definitions must be hard-coded in the application.
You cannot hardcode anything today and make sure that it reflects accurately data next year.
but you can write soemthing today who, when it is executed next year, will make the hardcode then.
This is called dynamic SQL.
Here's a way to do it in SQL * Plus, with the command of the COIL:

/*
How to Pivot a Table with a Dynamic Number of Columns

For example, you want to make a cross-tab output of
the scott.emp table.
Each row will represent a department.
There will be a separate column for each job.
Each cell will contain the number of employees in
     a specific department having a specific job.
The exact same solution must work with any number
of departments and columns.
(Within reason: there's no guarantee this will work if you
want 2000 columns.)
*/

PROMPT     ==========  0. Basic Pivot  ==========

SELECT     deptno
,     COUNT (CASE WHEN job = 'ANALYST' THEN 1 END)     AS analyst_cnt
,     COUNT (CASE WHEN job = 'CLERK'   THEN 1 END)     AS clerk_cnt
,     COUNT (CASE WHEN job = 'MANAGER' THEN 1 END)     AS manager_cnt
FROM     scott.emp
WHERE     job     IN ('ANALYST', 'CLERK', 'MANAGER')
GROUP BY     deptno
ORDER BY     deptno
;

PROMPT     ==========  1. Dynamic Pivot  ==========

--     *****  Start of dynamic_pivot.sql  *****

-- Suppress SQL*Plus features that interfere with raw output
SET     FEEDBACK     OFF
SET     PAGESIZE     0

SPOOL     p:\sql\cookbook\dynamic_pivot_subscript.sql

SELECT     DISTINCT
     ',     COUNT (CASE WHEN job = '''
||     job
||     ''' '     AS txt1
,     'THEN 1 END)     AS '
||     job
||     '_CNT'     AS txt2
FROM     scott.emp
ORDER BY     txt1;

SPOOL     OFF

-- Restore SQL*Plus features suppressed earlier
SET     FEEDBACK     ON
SET     PAGESIZE     50

SPOOL     p:\sql\cookbook\dynamic_pivot.lst

SELECT     deptno
@@dynamic_pivot_subscript
FROM     scott.emp
GROUP BY     deptno
ORDER BY     deptno
;

SPOOL     OFF

--     *****  End of dynamic_pivot.sql  *****

/*
EXPLANATION:
The basic pivot assumes you know the number of distinct jobs,
and the name of each one.  If you do, then writing a pivot query
is simply a matter of writing the correct number of ", COUNT ... AS ..."\
lines, with the name entered in two places on each one.  That is easily
done by a preliminary query, which uses SPOOL to write a sub-script
(called dynamic_pivot_subscript.sql in this example).

The main script invokes this sub-script at the proper point.
In practice, .SQL scripts usually contain one or more complete
statements, but there's nothing that says they have to.
This one contains just a fragment from the middle of a SELECT statement.

Before creating the sub-script, remember to turn off SQL*Plus features
that are designed to help humans read the output (such as headings and
feedback messages like "7 rows selected.", since we do not want these
to appear in the sub-script.
Remember to turn these features on again before running the main query.

*/

The first HOLD file that it creates, dynaic_pivot_subscript.sql, looks like this

,     COUNT (CASE WHEN job = 'ANALYST'    THEN 1 END)     AS ANALYST_CNT
,     COUNT (CASE WHEN job = 'CLERK'      THEN 1 END)     AS CLERK_CNT
,     COUNT (CASE WHEN job = 'MANAGER'    THEN 1 END)     AS MANAGER_CNT
,     COUNT (CASE WHEN job = 'PRESIDENT'  THEN 1 END)     AS PRESIDENT_CNT
,     COUNT (CASE WHEN job = 'SALESMAN'   THEN 1 END)     AS SALESMAN_CNT

Tags: Database

Similar Questions

  • How to display a value of transitional attribute to column db entity column?

    Mr President

    Help me at the time 12.2.1 jdev.

    How to display a value of transitional attribute to column db entity column?

    I have the requirement to indicate a value of transitional attribute column in the column db entity for some reason any.

    Any body can help as my show in the picture below

    The StAmt is a transitional column and a column db of the entity.

    tworows.png

    Any body can help please. !

    Concerning

    This means that the amount to be the attribute will always has the same value of the transient attribute? If so, why do you want the amount attribute the transient attribute is sufficient?

    Anyway, if you want to get attribute data in attribute transitional amounts you can open class ViewRowImpl and appearing in the getter or amount, you can get the value in the transitional as attribute:

      public Number getAmount()
      {
        return getTransientAttribute();
        //return (Number) getAttributeInternal(AMOUNT);
      }
    

    in this case, the quantity data store database will not appear on the table it will still get the transitional attribute data and it's meaningless.

  • My requirement is, if we click on the POP UP LOV element so I want the dependent value of this item in column of the text element in a table.

    My requirement is

    If we click on the POP UP dot LOV button then I want the dependent value of this item in column of the text element in a table.

    How do I get this as a table?

    Hi Dan,.

    I have a table, in the first column is popup LOV.and second column key is text element.

    So my question is if we click contextual key lov and select employee name, then I want to show the email address of this employee in the second column of tabular presentation.

    This can be done with AJAX. Write a JavaScript function on the onchange event of popup LOV item (Employee) key and pass the number of the employee selected to your AJAX call, go get the employee email and assign it to your entry corresponding to the key LOV popup text has changed.

    As your dealing with Form (Wizard Based/APEX_ITEM Based-not specified) in a table, you take insofar as each column is the table of elements mapped to APEX_APPLICATION input. G_FXX tables and therefore to write JavaScript to locate the item to update.

    I hope this helps!

    Kind regards

    Kiran

  • A way to return to the controls at the top of the files and thumbnails when hovering over the name of the file?  I can't even read the sticker because it has been moved to a separate column on the right.

    A way to return to the controls at the top of the files and thumbnails when hovering over the name of the file?

    I can't even read the sticker because it has been moved to a separate column on the right.

    Hi Bobca,

    I'm sorry, but the forecast of nail has been deprecated in the latest version due to security problems.

    Kind regards

    Nicos

  • The value of the cell in column

    Hello

    We report with a number of columns and columns of cells have value with a lot of characters (more than 100). We want to adjust the value of the cell in this column for example 20 characters and all characters of the value of the cell in column value of title HTML TD as "flag". Something like this:

    < code >
    "< td #ALIGNMENT headers # =" "#COLUMN_HEADER_NAME #" title = "#FULL_COLUMN_VALUE #" class = "data" > #TRIMED_COLUMN_VALUE # < table >
    < code >

    We can do as a model? You have an idea?

    I have an idea that uses JavaScript and the value of the total column in the hidden column, but I thing that there could be a better way to do this :-)

    Regarding.

    David

    Published by: user4893970 on November 23, 2010 16:11

    While I don't think that there is a way to do it with a normal report

    If it's a standard and not interactive report, then it can be done using the column Expression of HTML:

    #TRIMMED_COLUMN_VALUE#
    
  • Can sql RS only 1 column of return can be printed as a separate column value

    Hello
    I wonder if the result set sql returning only one column can be printed as a separate values column?

    IE.with a simple change to select empno, emp; It should be able to print.
    101,102,103

    Instead of
    EmpNo
    ----------
    101
    102
    103

    Thank you
    Jean Claude

    Here is an example with the EMP table in the Scott schema.

    select ltrim(sys_connect_by_path(empno,','),',') empno_list
      from (select e.*, row_number() over(order by empno) rno from emp e)
     where connect_by_isleaf = 1
     start with rno = 1
    connect by rno = prior rno+1
    
  • How to show the value of string with spaces in separate columns

    Hi all, I am using Oracle 10 g.

    create table
    create table sample_test (
      Name    VARCHAR2(20 BYTE))
    Insert a table
    insert into sample_test values ('JOAN   SCT')
         insert into sample_test values ('MELIA FILCK')
          insert into sample_test values ('SSAN LIER-LILEY')
           insert into sample_test values ('C.M. DANY WES')
               insert into sample_test values ('A L SCOTT')
    Select * from sample_test;
    Name
    JOAN   SCT
    MELIA FILCK
    SSAN LIER-LILEY
    C.M. DANY WES
    A L SCOTT
    I would like the following output
    NAME1        NAME2      NAME3
    JOAN          SCT               
    MELIA        FILCK               
    SSAN       LIER-LILEY
    C.M.          DANY       WES
    A             L          SCOTT
    whenever there is a space in the name of the value next to who should be included in another column. Please note the name joan has TBS of two spaces. but it must be treated as a single space.

    also is it possible to get something like that
    NAME1        NAME2     
    JOAN          SCT               
    MELIA        FILCK               
    SSAN       LIER-LILEY
    C.M.DANY       WES
    A L          SCOTT
    the value before the first space on the right must be everything in domain Name1 Name2.

    Thanks in advance.

    Hello

    Since you have Oracle 10, you can use regular expressions:

    For the release of 3 columns:

    SELECT        REGEXP_SUBSTR (name, '[^ ]+', 1, 1)     AS name1
    ,        REGEXP_SUBSTR (name, '[^ ]+', 1, 2)     AS name2
    ,        REGEXP_SUBSTR (name, '[^ ]+', 1, 3)     AS name3
    FROM        sample_test;     
    

    [^ xyz] means "any character except x, y or z."
    + means "1 or more of the previous ones.
    The 4th argument to REGEXP_SUBSTR indicates where we want the appearance of the model.

    For the release of 2 columns:

    SELECT        REGEXP_REPLACE (name, ' *[^ ]+$')     AS before_last_space
    ,        REGEXP_SUBSTR  (name,   '[^ ]+$')     AS after_last_space
    FROM        sample_test;
    

    $ here means "the end of the string.

    In Oracle 10, you will often use REGEXP_REPLACE to get substrings.

    Thanks for posting the CREATE TABLE and INSERT statements; It's very useful!

    Published by: Frank Kulash, 7 Sep 2011 15:21

  • SUM and CASES on SEPARATE column

    1 query 1:

    SELECT IN_SRC_SYSTEM, COUNT (1)

    (SELECT

    (IN THE CASE WHERE THE VALUE LIKE '% LO %' THEN 'LO'

    WHAT VALUE LIKE ' % THE % ' THEN 'THE

    WHAT VALUE LIKE '% SAP %' THEN 'SAP '.

    WHAT VALUE AS 'SPA %' THEN 'SPA' OTHER 'OTHER '.

    IN_SRC_SYSTEM END)

    OF LOGTD

    WHEN TRUNC (DATE_AGS) = TRUNC (SYSDATE)-1

    AND LOG_STATUS = 'P '.

    AND VALUE IS NOT NULL)

    IN_SRC_SYSTEM GROUP

    ORDER BY 1;

    output:

    IN_SRC_SYSTEM count (*)

    THE 62140

    LO 59611

    SAP 2685

    SPA 95

    I changed above query returns the results online wise.

    Question:-how to add a total of column below sql. (I can reach to above sql by cumulative Group)

    SELECT

    SUM (CASE WHERE THE VALUE LIKE '% LO %' THEN 1 0) OTHERWISE END "LO."

    SUM (CASE WHERE THE VALUE AS THE ' %') THEN 1 OTHER END 0 'LA',)

    SUM (CASE WHERE THE VALUE AS "SAP %') THEN 1 OTHER 0 END 'SAP',)

    SUM (CASE WHERE THE VALUE LIKE ' % SPA %') THEN 1 ANOTHER END 'SPA' 0)

    OF LOGTD

    WHEN TRUNC (DATE_AGS) = TRUNC (SYSDATE)-1

    AND LOG_STATUS = 'P '.

    AND VALUE IS NOT NULL

    output

    THE SAP LO SPA

    62140 59611 2685 95

    2.

    SELECT ERR_SRC_SYSTEM, COUNT (VALUE)

    (SELECT DISTINCT VALUE,

    (IN THE CASE WHERE THE VALUE LIKE '% LO %' THEN 'LO'

    WHAT VALUE LIKE ' % THE % ' THEN 'THE

    WHAT VALUE LIKE '% SAP %' THEN 'SAP '.

    WHAT VALUE AS 'SPA %' THEN 'SPA' OTHER 'OTHER '.

    ERR_SRC_SYSTEM END)

    OF LOGTD

    WHEN TRUNC (DATEAGS) = TRUNC (SYSDATE)-1

    AND LOG_STATUS = 'E '.

    AND VALUE IS NOT NULL)

    ERR_SRC_SYSTEM GROUP

    ORDER BY 1;

    ERR_SRC_SYSTEM, COUNT (VALUE)

    THE 174

    LO 3

    63 SPA

    Question:-how to display columns for bottom case distinct values and the State (I can reach to above sql by cumulative Group)

    Expected:

    THE SPA SAP LO

    174-3-63-0

    I tried something below, but it didn't work because it lead to a distinct value for the column name

    SELECT

    SUM (SEPARATE CASE WHEN TRANSACTION_SID LIKE '% LO %' THEN 1 0) OTHERWISE END "LO."

    SUM (DISTINCT CASES WHERE TRANSACTION_SID LIKE ' % THE %') THEN 1 OTHER END 0 'LA',)

    SUM (DISTINCT CASES WHERE TRANSACTION_SID LIKE ' % SAP %') THEN 1 OTHER 0 END 'SAP',)

    SUM (separate BOX WHEN TRANSACTION_SID LIKE '% SPA %' THEN 1 ELSE 0 END) "SPA".

    OF OD_LG_TRANSACTION_LOG

    WHEN TRUNC (CREATED_DATE) = TRUNC (SYSDATE)-1

    AND LOG_STATUS = 'E '.

    AND TRANSACTION_SID IS NOT NULL

    Kind regards

    Veera

    It's a shame that we didn't give examples of input data to go with your question. Therefore, it is difficult to answer. Saying that, here are my attempts to answer your questions:

    (1) to add columns, you do: col1 and col2 +... + colN. This applies, even if those columns are functions - for example. (Col1) FN + fn (col2) +... + fn (colN).

    (2) maybe you're after something like ' count (distinct cases where trasnaction_sid ' % THE %' as the end value)?

    For example I think you're after, based on a small sample of the dataset:

    with sample_data as (select 1 col1, 'abc' col2 from dual union all
                         select 2 col1, 'bcd' col2 from dual union all
                         select 3 col1, 'abc' col2 from dual union all
                         select 4 col1, 'efg' col2 from dual union all
                         select 5 col1, 'abc' col2 from dual union all
                         select 6 col1, 'hij' col2 from dual union all
                         select 7 col1, 'bcd' col2 from dual union all
                         select 8 col1, 'dfg' col2 from dual union all
                         select 9 col1, 'cde' col2 from dual)
    select count(distinct case when col2 like '%b%' then col2 end) b,
           count(distinct case when col2 like '%d%' then col2 end) d,
           count(distinct case when col2 like '%l%' then col2 end) l
    from   sample_data;
    
             B          D          L
    ---------- ---------- ----------
             2          3          0
    
  • How to dynamically set the filter IR APEX of the value of a radio button column?

    Hello

    I built a simple APEX 4.2 IR report that includes column, namely "Source_Data" and a separate user to input radio button namly "P33_SOURCE_DATA" with two possible values in 'X' or 'Y '.

    I would like the report filter source_data = 'X' or source_data = "Y" is applied, after each time the user clicks on the radio button P33_SOURCE_DATA. "

    So my question is, how to set the value of the IR filter using the value of P33_SOURCE_DATA to the dynamic action and javascript?

    Thanks in advance.

    Concerning

    Susanna

    In this case, you can pull an onchange dynamic action on the radio, or at the click of a button.

    This dynamic action update your IR region

    And your IR region would have an appropriate where clause, with "Page to go" set on your radio.

  • How to select the lines whose value min on a specific column

    I have a query:

    Select

    m.X1,

    round (to_date (l.y1, ' dd/mm/yyyy hh: mi: SS AM')-m.x 2, 0) as numofdays

    Of

    Table 1 m,

    Table2 l

    where

    l.x3 = m.x3 and

    TO_DATE (l.y1, ' mm/dd/yyyy hh: mi: SS AM' ') > = TO_DATE('01012013','MMDDYYYY') and

      ... ;

    and I got this result table:

    x 1 (ID) NumOfDays
    0015

    001

    1000220033003140 °000566......

    several IDs have several values on the second column, I want to have only separate IDs with smaller "numofdays' like this:

    x 1 (ID) NumOfDays
    0015
    0022
    0031
    0040
    00566
    ......

    Any ideas?

    Hello

    The more general and more versatile way is a Request of Top - N:

    WITH got_r_num AS

    (

    Select

    m.X1,

    round (to_date (l.y1, ' dd/mm/yyyy hh: mi: SS AM')-m.x 2, 0) as numofdays

    ROW_NUMBER () OVER (PARTITION BY m.x1

    ORDER BY to_date (l.y1, ' mm/dd/yyyy hh: mi: SS AM' ')-m.x 2

    ) AS r_num

    Of

    Table 1 m,

    Table2 l

    where

    l.x3 = m.x3 and

    TO_DATE (l.y1, ' mm/dd/yyyy hh: mi: SS AM' ') > = TO_DATE('01012013','MMDDYYYY') and

    ...

    )

    SELECT x 1, numofdays

    OF got_r_num

    WHERE r_num = 1

    ;

    If you would care to post CREATE TABLE and INSERT statements for your sample data, then I could test it.

    Note that the subquery (got_r_num) is exactly what you have posted, only with a new column (r_num) added to the SELECT clause.

  • Dynamic SQL query to get the unique value of list in a column

    I have two tables: tblWorkers and tblSkills. tblWorkers has a column, skills, which is populated by a field of multiple-checkbox with one or more skill_IDs of tblSkills, so each tblWorkers.Skills consists of a list of one or more comma-delimited values. For any Skill_ID, I need to generate a list of all workers with the appropriate skills, so I tried to do something in the direction of SELECT WorkerName FROM tblWorkers WHERE IN of skills (skills, #FORM. Skill_ID #)... or WHERE skills (ListFind (skills, #FORM. Skill_ID #))... etc.? My results (once I have had data type mismatches of the road) return all workers, not just those with the desired skills. There must be an easy way to do... How people with a little more experience CF/SQL I do this?

    > each tblWorkers.Skills consists of a list of one or more comma-delimited values

    This is your problem. You store a list of values that you want to access power/query separately in a single column. You will have to burst in a separate table.
    TblWorkers

    TblSkills

    TblWorkerSkills
    mapping table of many workers with skills.

    If you do not change your data model now, you will constantly be butting your head against that.

  • Insert in the table in separate columns

    I did the vi in the attachments. This basically vi, calculate a value from the device, this is the channel dashboard. I need more so: when calculating terminate, I need to insert data into a table, but the problem is: the number of lines in the constant table is the number of columns, I need the Temp Org chart. And these values are variable. I need a method to do this automatically. Or, I need a vi to 'build' these columns according to the number of rows in the table of constants.

    If the table of constants (number of lines) and the channel table (number of items) to match the size, where the other constants come when the size has to increase?

    What intrigues me is your use of construction "array index... build array. It's the same as truncate the initial 3-element array, regardless of the number of items is originally in there.

    Here's a quick rewrite that eliminates some of the questionable things. As I mentioned in the first sentence, I don't know really what you want.

  • separate column

    Oracle 12 c.

    I have a table that has several columns for the accommodation of the languages (for some reason that I don't want a child table to accommodate the langauges).  Try to find the DISTINCT languages in the table.

    col1

    col2

    COL3

    COL4

    The sample files are:

    COL1 COL2 COL3 COL4

    Row1: English Spanish Italian Korean

    row2: English Japanese Spanish

    row3: English Spanish Thai Danish

    Italian German row4

    If there is only a SINGLE column which hosts the languages, I can just use:

    Select distinct col1 of table X.

    But now there are several accommodation the langauges columns, how do I enumerate the distinct (NON-DUPPLICATE) langauges, such as return the result set to:

    English

    Spanish

    Korean

    Italian

    Japanese

    Thai

    German

    Danish

    Thank you for helping.

    Scott

    Hi, Scott.

    scottjhn wrote:

    Oracle 12 c.

    I have a table that has several columns for the accommodation of the languages (for some reason that I don't want a child table to accommodate the langauges).

    Looks like you already realize that it is a design of the wrong table.  Any reason you have booked using this model, you should think about it again.  The reasonable way to store data and the reasonable way to solve this problem, are all languages to in 1 column.  If you store the data in a smart way, you will have to convert on the fly, whenever you have to solve a problem like this.  You can use SELECT... UNPIVOT function to convert the 4 columns in 1 and then use plain old SEPARATE to get a single output.

    The FAQ Forum page on swivel also treats of unpivoting.  See Re: 4. How can I convert rows to columns?

    If you get stuck, see this other Forum FAQ page: Re: 2. How can I ask a question on the forums?

  • different values on the same grouping column

    Hi all

    I have a requirement to find different recordings of the same grouping columns have value different values in the columns, for example:

    WITH

    Data (G1, COL)

    AS

    (

    SELECT 'A', '456' FROM dual UNION ALL

    SELECT 'A', '345' FROM dual UNION ALL

    SELECT 'A', ' ' FROM dual UNION ALL

    SELECT ' 'B, 123' FROM dual UNION ALL.

    SELECT ' 'B, 123' FROM dual UNION ALL.

    SELECT ' 'B, 123' FROM dual UNION ALL.

    SELECT 'C', "789' FROM dual UNION ALL

    SELECT 'C', "789' FROM dual UNION ALL

    SELECT 'C', "" the DOUBLE

    )

    Select g1, pass data

    Ideally for G1 = A, the NECK should have that a single value across records ' 456 'or ' 345'. So I need to check the values in NOT NULL of the COL where, for any value of G1, we have different values of the colonel G1 = 'B' is perfectly fine, so I don't need. G1 = C is good too and I'm not worried about it. I only need these entries when the neck was non-empty value / NULL not different for the same value of G1.

    So expected out put is

    Capture.PNG

    WITH

    Data (G1, COL)

    AS

    (

    SELECT 'A', '456' FROM dual UNION ALL

    SELECT 'A', '345' FROM dual UNION ALL

    SELECT 'A', "double UNION ALL

    SELECT ' 'B, 123' FROM dual UNION ALL.

    SELECT ' 'B, 123' FROM dual UNION ALL.

    SELECT ' 'B, 123' FROM dual UNION ALL.

    SELECT 'C', "789' FROM dual UNION ALL

    SELECT 'C', "789' FROM dual UNION ALL

    SELECT 'C', "the DOUBLE

    )

    Select g1,

    Col

    de)

    Select g1,

    Col,

    Count (distinct trim (col)) at the NTC (g1 partition)

    from the data

    )

    where NTC! = 1

    and trim (col) is not null

    /

    G COL. NO.
    - ---
    A 345
    A 456

    SQL >

    SY.

  • IR report visible cell based on the value of the hidden highlight column

    I have an IR with a date in the format DD-MON-AA column.  I have an obligation to change the background color of the date cell according to the day of the week (2 yellow =, 3 = purple, etc.), where Monday is day 2, Tuesday is the day 3, etc.

    My idea on how to proceed was to create a hidden like this to_char (date_col, 'r') column, but I can not set the background color of the date column based on the value of another column (the column hidden in this case). 

    Any ideas on how I can do this?  Can I use the Expression of implementation form/HTML column on the column date to set the background color; If so, can you give an example?

    Thank you.

    Use column formatting

    #COLTOHIGHLIGHT #.

    Add css to the page

Maybe you are looking for

  • Power button on my MacBook Pro is slow.

    The power button on my MacBook Pro seems to be failing.  The last time I got to turn on the machine, that it does not seem to start.  I had to press several times to get any action.  Is it a hardware fault?  Or could there be another reason why the m

  • I forgot quisthon

    I forgot quisthon App Store

  • How to view all accounts

    I still had all my accounts shwing upward in the homepage. I did something that caused one now appears. How can I get all accounts appears again? Thank you

  • HP 550-119ea Bios password recovery

    Hello I had trouble with my BIOS. I would like to install ubuntu and to do this, I need to turn off secure in the bios boot. The thing is, when I bought the computer, I stupidly added a BIOS password, and now I can not remember. I guessed all of my u

  • Upgradeing Mainboard on HP 4510 s?

    Hello I would like to know to what extent the motherboard on the HP Probook 4510 s is scalable? Specifically, can I switch to a motherboard that has a processor Intel Quad Core and DDR 3 RAM support and possibly a nVidea or Radeon graphics card? My c