Supplying row value as column name

Hi all,
I have two tables in which row value in one table is column name of other. How do i relate it to retreive the data...
Table 1: control (contains 3 columns in it)
table_name - parametername - parametervalue
MI     - UNPROCESSED_FLAG -     N
MI     - PROCESSED_FLAG - Y
MI     - FROM_DATE     - 01-JAN-2008
MI     - TO_DATE     - 31-DEC-2010
EMP     - DEPTNO     - 30
EMP     - JOB     - SALESMAN
EMP     - FROM_DATE     - 01-JAN-1982
EMP     - TO_DATE     - 31-DEC-1995
Table 2: emp (contains the columns: empno,ename,deptno,job,hiredate)
I want to display all details from emp table according to the parameter given in control table. I have already written a query using subquery
select *
from emp
where
deptno = (select parameter_value from job_control where parameter_name = 'DEPTNO')
and
job = (select parameter_value from job_control where parameter_name = 'JOB')
and
hiredate between (select parameter_value from job_control where parameter_name = 'FROM_DATE' and table_name = 'EMP') and (select parameter_value from job_control where parameter_name = 'TO_DATE' and table_name = 'EMP');
But i want to write ot using joins. Plz help me out.....
Thanks

Hi,
Welcome to the forum!
Whenever you have a question, please post CREATE TABLE and INSERT statements for your sample data, so that the people who want to help you can re-create the problem and test their ideas. (There's no need to post commonly available tables. like those in the scott schema, but make it clear which such tables you're using.) Since this is your first post, I'll do it for you:
CREATE TABLE     control_table
     table_name     VARCHAR2 (20)
,     parametername     VARCHAR2 (20)
,     parametervalue     VARCHAR2 (20)
INSERT INTO control_table (table_name, parametername, parametervalue) VALUES ('EMP', 'DEPTNO',       '30');
INSERT INTO control_table (table_name, parametername, parametervalue) VALUES ('EMP', 'JOB',       'SALESMAN');
INSERT INTO control_table (table_name, parametername, parametervalue) VALUES ('EMP', 'FROM_DATE', '01-SEP-1981');
INSERT INTO control_table (table_name, parametername, parametervalue) VALUES ('EMP', 'TO_DATE',       '31-DEC-1995');
INSERT INTO control_table (table_name, parametername, parametervalue) VALUES ('MI',  'FROM_DATE', '01-JAN-2008');
;Also post the exact results you want from that sample data. The query below produces these results from the control_table above and the standard scott.emp table:
EMPNO ENAME      JOB         MGR HIREDATE    SAL  COMM DEPTNO
7654 MARTIN     SALESMAN   7698 28-SEP-81  1250  1400     30
7844 TURNER     SALESMAN   7698 08-SEP-81  1500     0     30Always say which version of Oracle you're using. The query below works in Oracle 9.1 and up.
One thing you can do is pivot the appropriate parameters into a one-row result set, and treat it as a table, like this:
WITH     got_params     AS
     SELECT  TO_NUMBER (MIN (CASE WHEN parametername = 'DEPTNO'    THEN parametervalue END))               AS deptno
     ,             MIN (CASE WHEN parametername = 'JOB'       THEN parametervalue END)               AS job
     ,     TO_DATE   (MIN (CASE WHEN parametername = 'FROM_DATE' THEN parametervalue END), 'DD-MON-YYYY')     AS fromdate
     ,     TO_DATE   (MIN (CASE WHEN parametername = 'TO_DATE'   THEN parametervalue END), 'DD-MON-YYYY')     AS todate
     FROM     control_table
     WHERE     table_name     = 'EMP'
SELECT  e.*
FROM     emp         e
JOIN     got_params  p  ON   e.deptno     = p.deptno
                 AND  e.job     = p.job
                 AND  e.hiredate     BETWEEN  p.fromdate
                                    AND      p.todate
;This assumes that the combination (table_name, parametername) is unique in the control_table.

Similar Messages

  • Changing rows into different column names

    Hi,
    i need to tranpose the rows into differnent column names
    my sample data :
    id , val
    1 3
    1 4
    1 5
    into
    id , val1, val2 , val3 , val4 ... valn ..
    1 3 4 5
    from askTom's i see that it's tranpose into a single column using the ref cursor ?
    how can i do made it into different column names ?
    kindly advise
    tks & rdgs

    For example, lets say that you want to order your columns from least value to greatest and that you'll never have more than three values per id. Then you can use the analytic function row_number() like this to create a pivot value.
    select id, val,
           row_number() over (partition by id order by val) as rn
      from your_table;And so your pivot query ends up looking like this.
    select id,
           max(case when rn=1 then val end) AS val1,
           max(case when rn=2 then val end) AS val2,
           max(case when rn=3 then val end) AS val3
      from (
    select id, val,
           row_number() over (partition by id order by val) as rn
      from your_table
    group by id;But notice that I started out by making up answers to Justin's questions. You'll have to supply the real answers.

  • Row Values To Columns.

    Hi,
    I'm looking to cut row-values to columns and here is my data-set and my objective...
    delimiter ( for readability ) : "," ( comma )
    column1, column2, column3, column4
    10, name=john, age=30, state=ca, country=usa
    20, name=jane, age=25, null, null
    Output
    column1, column2, column3
    10, name, john
    10, age, 30
    10, state, ca
    10, country, usa
    20, name, jane
    20, age, 25
    Please advice.
    Thanks much.
    Edited by: shankariyer on Nov 2, 2008 11:17 AM
    Edited by: shankariyer on Nov 2, 2008 11:18 AM

    Here is one method with more dynamic approach - a little weired ;)
    satyaki>
    satyaki>select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod
    PL/SQL Release 10.2.0.3.0 - Production
    CORE    10.2.0.3.0      Production
    TNS for 32-bit Windows: Version 10.2.0.3.0 - Production
    NLSRTL Version 10.2.0.3.0 - Production
    hello welcome
    Elapsed: 00:00:00.39
    satyaki>
    satyaki>
    satyaki>with pro_satyaki
      2  as
      3    (
      4       select 10 col_1, 'name=john, age=30, state=ca, country=usa' d_col from dual
      5       union all  
      6       select 20, 'name=jane, age=25, null, null' from dual 
      7    )
      8  select col_1, 
      9         trim(
    10               substr(
    11                       cast(tt.column_value.extract('//text()') as varchar2(100)),
    12                       1,
    13                       instr(cast(tt.column_value.extract('//text()') as varchar2(100)),'=')-1
    14                     )
    15             ) col_2,
    16         trim(
    17               substr(
    18                       cast(tt.column_value.extract('//text()') as varchar2(100)),
    19                       instr(cast(tt.column_value.extract('//text()') as varchar2(100)),'=')+1
    20                     )
    21             ) col_3
    22  from pro_satyaki,
    23       table(xmlsequence(xmltype('<x><x>' || replace(d_col,',','</x><x>') || '</x></x>').extract('//x/*'))) tt
    24  where trim(
    25              substr(
    26                      cast(tt.column_value.extract('//text()') as varchar2(100)),
    27                      instr(cast(tt.column_value.extract('//text()') as varchar2(100)),'=')+1
    28                    )
    29            ) <> 'null' ;
         COL_1 COL_2                                                                                                COL_3
            10 name                                                                                                 john
            10 age                                                                                                  30
            10 state                                                                                                ca
            10 country                                                                                              usa
            20 name                                                                                                 jane
            20 age                                                                                                  25
    6 rows selected.
    Elapsed: 00:00:00.27
    satyaki>Regards.
    Satyaki De.

  • Row Insert Failed - Column name or number of supplied values does not match

    Hi ,
    I am trying add a new field to an existing table in MSSQL and access it in portlets,
    I added the new field in the table, and making necessary updations to the accessing java code seems to look fine. but when i insert the new rwo, fails with exception listed below.
    My code tidbits is as follows.
                   System.out.println("Column Location of outsidePhysician"+ aResultSet.findColumn("outsidePhysician")); // works and returns 24
                   if (anIntake.getOutsidePhysician() != null && !(anIntake.getOutsidePhysician().equals("")))
                        System.out.println("Now Alternate Physician will be added to resultset");
                        aResultSet.updateString(24, anIntake.getOutsidePhysician());
                        aResultSet.updateString("outsidePhysician",anIntake.getOutsidePhysician());
                        System.out.println("Now Alternate Physician already added to resultset"); // also printed
                   }else{
                        aResultSet.updateString(24, "new Physician");
                        aResultSet.updateString("outsidePhysician","new Physician");
                   //NOT NULL
                   aResultSet.insertRow(); // fails here
                   System.out.println("Inserted");
    The table has the right field name too, which is proved when i retrieve the fieldno, based on field name. I tried to delete the field and removing these changes work ok..
    Any ideas would be of help
    Thanks in Advance
    Usha
    [Microsoft][SQLServer 2000 Driver for JDBC]Row insert failed. at com.microsoft.jdbc.base.BaseExceptions.createException(Unknown Source) at com.microsoft.jdbc.base.BaseExceptions.getException(Unknown Source) at com.microsoft.jdbc.base.BaseImplUpdatableResultSet.executeStatement(Unknown Source) at com.microsoft.jdbc.base.BaseImplUpdatableResultSet.insertRow(Unknown Source) at com.microsoft.jdbc.base.BaseResultSet.insertRow(Unknown Source) at com.microsoft.jdbcx.base.BaseResultSetWrapper.insertRow(Unknown Source) at com.ibm.ws.rsadapter.jdbc.WSJdbcResultSet.insertRow(WSJdbcResultSet.java:2181) ... 14 more Caused by: java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Insert Error: Column name or number of supplied values does not match table definition. at com.microsoft.jdbc.base.BaseExceptions.createException(Unknown Source) at com.microsoft.jdbc.base.BaseExce

    I haven't ever used that method of inserting rows, but from the example in the API documentation it looks to me like you have to callaResultSet.moveToInsertRow();before you callaResultSet.insertRow();Or are you just "inserting" the physician's name into existing rows of the database? If that's what you are doing then you need to callaResultSet.updateRow();Message was edited by:
    DrClap

  • Item value as column name in select

    Hi,
    I have a problem with selecting the columns in the query using items. For example: I have a query:
    select column_a from table; or select column_b from table;
    and I want to do something like this:
    - any item in which I choose the column name
    - query: select column_from_item from tale
    Is it possible?
    My apex version: 4.0.2.00.07
    My oracle db version: oracle 11g

    Unfortunately, it does not work. For example:
    I have a table book (title, themes ...), which is eight rows. When I create a static list of items containing the column names (display name and returns the name) and a report based on select according to your design(select :P5_select from table;), you get eight records in the name of the column.
    item: select list -> static list -> display value: Title, return value: Title, name: P1_title
    select :P1_title from books;
    result which i get:
    Title
    Title
    Title
    Title

  • Problem in displaying row vale as column name

    Hello Experts,
    Please help me,its very urgent....
    i want to dispaly a column value as a column name.
    i have two column into selete statement and i want to dispaly one column value as a column name and other column value as a single row.
    My query is :
    SELECT MAX(DECODE (NAME,'virtualDeviceId',VALUE))vdid ,
    MAX(DECODE (NAME,'virtualDeviceType',VALUE)) vdevtype,
    MAX(DECODE (NAME,'domainName',VALUE)) vdevtype1,
    MAX(DECODE (NAME,'sCTPPortSip',VALUE)) vdevtype2,
    MAX(DECODE (NAME,'signallingIpAddress',VALUE)) vdevtype,
    MAX(DECODE (NAME,'signallingNetworkMask',VALUE)) vdevtype,
    MAX(DECODE (NAME,'uDPPort',VALUE)) vdevtype,
    MAX(DECODE (NAME,'uDPPortEnum',VALUE)) vdevtype,
    MAX(DECODE (NAME,'sCTPPort',VALUE)) vdevtype,
    MAX(DECODE (NAME,'sCTPPortM3UA',VALUE)) vdevtype FROM(          
    SELECT extractvalue(VALUE(l),'/S109:trafficParameters/S109:name'
    , 'xmlns="http://itprogrammes.intra.bt.com/pdb/capabilities/ManageDaaliResource/2005/11/16" xmlns:header="http://wsi.nat.bt.com/2005/06/StandardHeader/" xmlns:S97="http://ccm.intra.bt.com/2005/11/16/LIB/Info/CCM/AnalysisModel/Services" xmlns:S109="http://ccm.intra.bt.com/2005/11/16/LIB/Info/MTOSI"') NAME,
         extractvalue(VALUE(l),'/S109:trafficParameters/S109:value'
    , 'xmlns="http://itprogrammes.intra.bt.com/pdb/capabilities/ManageDaaliResource/2005/11/16" xmlns:header="http://wsi.nat.bt.com/2005/06/StandardHeader/" xmlns:S97="http://ccm.intra.bt.com/2005/11/16/LIB/Info/CCM/AnalysisModel/Services" xmlns:S109="http://ccm.intra.bt.com/2005/11/16/LIB/Info/MTOSI"') VALUE
         FROM INTERFACE_MESSAGE_DESTINATION imd ,TABLE(xmlsequence(EXTRACT(XMLTYPE(imd.remote_request),'/activateConnection_Payload/jobBody/subnetworkConnection/S109:aEndTerminationPoint/S109:managedElement/S109:physicalTerminationPoint/S109:connectionTerminationPoint/S109:trafficDescriptor/*'
    , 'xmlns="http://itprogrammes.intra.bt.com/pdb/capabilities/ManageDaaliResource/2005/11/16" xmlns:header="http://wsi.nat.bt.com/2005/06/StandardHeader/" xmlns:S97="http://ccm.intra.bt.com/2005/11/16/LIB/Info/CCM/AnalysisModel/Services" xmlns:S109="http://ccm.intra.bt.com/2005/11/16/LIB/Info/MTOSI"'))) l
    WHERE message_id ='NIAS/0000041608') GROUP BY VALUE ;
    output is :
    Col1 Col2 col3 col4 col5 col
    1.'1001105'          '1001105'                                   
    2. 'MGC'                                        
    3.'value' 'value' 'value'
    output display : MGC in Col2 and in row 2, 'values' are in col4 and col5 and in row 3.
    I want all values in a single row.
    Please help me
    Surender Rana

    It is ugly to force multiple rows into a single row. But it can be done and can be done dynamically as the following approach shows.
    SQL> create or replace type TStrings as table of varchar2(4000);
    2 /
    Type created.
    SQL>
    SQL> create or replace function ForceColumns( cur SYS_REFCURSOR ) return TStrings is
    2 setCols TStrings;
    3 setResults TSTrings;
    4 begin
    5 setResults := new TStrings();
    6 loop
    7 fetch cur into setCols;
    8 exit when cur%NOTFOUND;
    9
    10 if setCols.Count > 0 then
    11 setResults.Extend( setCols.Count );
    12 for i in 1..setCols.Count
    13 loop
    14 setResults( setResults.Count-i+1 ) := setCols(i);
    15 end loop;
    16 end if;
    17 end loop;
    18
    19 return(setResults);
    20 end;
    21 /
    Function created.
    SQL>
    SQL> select
    2 ForceColumns(
    3 CURSOR(
    4 select TStrings(object_id,object_name,object_type) from user_objects where rownum <= 5
    5 )
    6 ) as RESULT_SET
    7 from dual
    8 /
    RESULT_SET
    TSTRINGS('TABLE', 'A', '70998',
    'PROCEDURE', 'ABC', '54360',
    'TABLE', 'ANIMALS', '84829',
    'TABLE', 'B', '69604',
    'PROCEDURE', 'BUILDNAMEMAP', '70155')
    SQL>Note that as the row can contain any number of columns, it needs to be dynamic. This approach uses a collection type called TStrings to achieve this.

  • How to use a value as column name in Triggers?

    Hello All!!!!!
    How can i use a column value instead of field name in triggers? e.g. table X has one column and having following data.
    COL1*
    Id
    Name
    Contact No.
    now in triggers i want to use "Id" instead of :new.id, is it possible?
    Any solution?

    actually i am trying to write a trigger on lets say Table2 and i dont want to specify the column name in the trigger.
    CREATE OR REPLACE TRIGGER TR_AIUDR_002
    AFTER UPDATE
    ON mytable
    FOR EACH ROW
    DECLARE
    CURSOR C IS
    SELECT * FROM t_table_columns;
    BEGIN
    IF UPDATING then
    FOR I IN C LOOP
    IF *:new.column_name <> :OLD.column_name* THEN
    insert into....
    END IF;
    END LOOP;
    END IF;
    END TR_AIUDR_002;
    instead of :new.column_name <> :old.column_name i want to compare on the base of loop column
    Edited by: rha2 on Jan 31, 2009 7:04 PM

  • Using select list value as column name in SQL

    Folks,
    Thanks in advance for any help with this
    I have a select list with two values (Instance and Username) created by
    STATIC2:Username;USERNAME,Instance;INSTANCE
    I am trying to pass the value of this (:P2_SELECT) and use it as a column name in a SQL query as below
    select USERNAME,
    INSTANCE
    from table_name
    where :P2_SELECT like '%'||:P2_TEXTSEARCH||'%'
    When I substitue the :P2_SELECT for one of the values (either instance or username) this works fine
    I suspect it is due to how Application Express interprets the value of :P2_SELECT
    Any help would be much appreciated!
    Gareth

    Thanks Munky that worked a treat!
    The next hurdle I have now is that because I have changed the region type to "PL/SQL Function(returning SQL Query)" there is no longer the option to add sorting to the columns as I have had to change the Source option to "Use Generic Column Names (parse query at runtime only)"
    I will have a scout around and see how I can get around this
    Gareth

  • Display column value as column name

    Hi,
    I have a requirement to display column names as column values and vice versa. Pls suggest how to do this.
    Test data
    create table oratest as select 'saurabh' "name",23 "age" from dual;
    SQL> select * from oratest;
    name           age
    saurabh         23Expected output
    saurabh         23
    name           age

    Ok, I've only got 10g here at the minute, so this is what I'd do...
    SQL> ed
    Wrote file afiedt.buf
      1  DECLARE
      2    v_v_val     VARCHAR2(4000);
      3    v_n_val     NUMBER;
      4    v_d_val     DATE;
      5    v_ret       NUMBER;
      6    c           NUMBER;
      7    d           NUMBER;
      8    col_cnt     INTEGER;
      9    f           BOOLEAN;
    10    rec_tab     DBMS_SQL.DESC_TAB;
    11    col_num     NUMBER;
    12    v_rowcount  NUMBER := 0;
    13    v_name      VARCHAR2(20);
    14    v_age       NUMBER;
    15    v_sql       VARCHAR2(4000);
    16    v_str       VARCHAR2(250);
    17    v_und       VARCHAR2(250);
    18  BEGIN
    19    select "name", "age"
    20    into   v_name, v_age
    21    from   oratest;
    22    v_sql := 'SELECT ''name'' as "'||v_name||'", ''age'' as "'||v_age||'" from dual';
    23    c := DBMS_SQL.OPEN_CURSOR;
    24    DBMS_SQL.PARSE(c, v_sql, DBMS_SQL.NATIVE);
    25    d := DBMS_SQL.EXECUTE(c);
    26    DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
    27    --
    28    -- Bind local return variables to the various columns based on their types
    29    FOR j in 1..col_cnt
    30    LOOP
    31      CASE rec_tab(j).col_type
    32        WHEN 1 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000); -- Varchar2
    33        WHEN 2 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_n_val);      -- Number
    34        WHEN 12 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_d_val);     -- Date
    35      ELSE
    36        DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);  -- Any other type return as varchar2
    37      END CASE;
    38    END LOOP;
    39    -- Display the header
    40    FOR j in 1..col_cnt
    41    LOOP
    42      v_str := v_str || rpad(rec_tab(j).col_name,30,' ')||' ';
    43      v_und := v_und || rpad('-',30,'-')||' ';
    44    END LOOP;
    45    v_str := rtrim(v_str);
    46    v_und := rtrim(v_und);
    47    DBMS_OUTPUT.PUT_LINE(v_str);
    48    DBMS_OUTPUT.PUT_LINE(v_und);
    49    --
    50    -- This part outputs the DATA
    51    v_str := '';
    52    LOOP
    53      v_ret := DBMS_SQL.FETCH_ROWS(c);
    54      EXIT WHEN v_ret = 0;
    55      v_rowcount := v_rowcount + 1;
    56      FOR j in 1..col_cnt
    57      LOOP
    58        CASE rec_tab(j).col_type
    59          WHEN 1  THEN DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
    60                       v_str := v_str||rpad(v_v_val,30,' ')||' ';
    61          WHEN 2  THEN DBMS_SQL.COLUMN_VALUE(c,j,v_n_val);
    62                       v_str := v_str||lpad(to_char(v_n_val,'fm999999999999'),30,' ')||' ';
    63          WHEN 12 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_d_val);
    64                       v_str := v_str||rpad(to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'),30,' ')||' ';
    65        ELSE
    66          DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
    67          v_str := v_str||rpad(v_v_val,30,' ')||' ';
    68        END CASE;
    69      END LOOP;
    70      v_str := rtrim(v_str);
    71      dbms_output.put_line(v_str);
    72    END LOOP;
    73    DBMS_SQL.CLOSE_CURSOR(c);
    74* END;
    SQL> /
    saurabh                        23
    name                           age
    PL/SQL procedure successfully completed.
    SQL>Now, with 11g you can actuall create the DBMS_SQL cursor from the top part of the code...
    18  BEGIN
    19    select "name", "age"
    20    into   v_name, v_age
    21    from   oratest;
    22    v_sql := 'SELECT ''name'' as "'||v_name||'", ''age'' as "'||v_age||'" from dual';
    23    c := DBMS_SQL.OPEN_CURSOR;
    24    DBMS_SQL.PARSE(c, v_sql, DBMS_SQL.NATIVE);And using the new function in 11g's DBMS_SQL package called dbms_sql.to_refcursor and convert the DBMS_SQL cursor to a REF CURSOR which you can then use in your applications (if that's the way you need to go)...
    http://www.oracle.com/technology/oramag/oracle/07-nov/o67asktom.html
    Whatever route you take though, you won't do this simply in SQL as the column names of a query are required to be known before any data is retrieved when a query (cursor) executes. You can see that when you use the DBMS_SQL package, where the query has to be parsed and the column names and descriptions are determined before any fetching of data.

  • Need to use Select List value as column name

    I want to have a WHERE ? IS BETWEEN ? AND ? clause.
    I am using the PL/SQL Query returning a SQL Query as a report. This uses bind variables for items I had set on my form..... If I hardcode something like:
    'WHERE STARTDATE IS BETWEEN '||
    'TO_DATE(:P1_START,''dd-MON-YYYY HH24:MI'') AND '||
    'TO_DATE(:P2_END,''dd-MON-YYYY HH24:MI'')';
    I have no problem, but I have 2 date columns, STARTDATE and ENDDATE, and would like to use the value in a select list and not have to hardcode "STARTDATE" in there. I have not been able to do this, does anyone know how to use a bind variable as a column name? From reading some posts I think it might not be possible.

    Heather,
    You're on the right track, just glue in the column name so that it becomes part of the returned query string from the function (...'WHERE '||:COLNAME||' IS BETWEEN '|| ...).
    Note that the bind variable is not part of the returned query string, but the column name obtained from the bind variable when the function executes does become part of the query string.
    Scott

  • How to convert some row values in columns

    Hello guys,
    I'm using Oracle 10g in a windows platform, I have the following data:
    with test as
    select '000-ME-001' tag_number, 'Capacity 150' tag_details1, '000-TS-M-226' tag_details2 from dual union all
    select '000-ME-001' tag_number, 'Capacity 250' tag_details1, '000-TS-M-227' tag_details2 from dual union all
    select '000-ME-001' tag_number, 'Capacity 350' tag_details1, '000-TS-M-228' tag_details2 from dual union all
    select '000-ME-002' tag_number, 'Capacity 150' tag_details1, '000-TS-M-226' tag_details2 from dual union all
    select '000-ME-002' tag_number, 'Capacity 250' tag_details1, '000-TS-M-227' tag_details2 from dual union all
    select '000-ME-002' tag_number, 'Capacity 350' tag_details1, '000-TS-M-228' tag_details2 from dual union all
    select '000-ME-003' tag_number, 'Capacity 150' tag_details1, '000-TS-M-226' tag_details2 from dual union all
    select '000-ME-003' tag_number, 'Capacity 250' tag_details1, '000-TS-M-227' tag_details2 from dual union all
    select '000-ME-003' tag_number, 'Capacity 350' tag_details1, '' tag_details2 from dual
    )How can I covert the values of tag_details1 as column name to achieve this result:
    tag_number     Capacity 150     Capacity 250     Capacity 350
    000-ME-001     000-TS-M-226     000-TS-M-227     000-TS-M-228
    000-ME-002     000-TS-M-226     000-TS-M-227     000-TS-M-228
    000-ME-003     000-TS-M-226     000-TS-M-227Hope you can help me, best regards.

    select tag_number
         , max (decode (tag_details1, 'Capacity 150', tag_details2))
         , max (decode (tag_details1, 'Capacity 250', tag_details2))
         , max (decode (tag_details1, 'Capacity 350', tag_details2))
      from test
    group by tag_numberas in
    SQL> with test as
      2  (
      3  select '000-ME-001' tag_number, 'Capacity 150' tag_details1, '000-TS-M-226' tag_details2 from dual union all
      4  select '000-ME-001' tag_number, 'Capacity 250' tag_details1, '000-TS-M-227' tag_details2 from dual union all
      5  select '000-ME-001' tag_number, 'Capacity 350' tag_details1, '000-TS-M-228' tag_details2 from dual union all
      6  select '000-ME-002' tag_number, 'Capacity 150' tag_details1, '000-TS-M-226' tag_details2 from dual union all
      7  select '000-ME-002' tag_number, 'Capacity 250' tag_details1, '000-TS-M-227' tag_details2 from dual union all
      8  select '000-ME-002' tag_number, 'Capacity 350' tag_details1, '000-TS-M-228' tag_details2 from dual union all
      9  select '000-ME-003' tag_number, 'Capacity 150' tag_details1, '000-TS-M-226' tag_details2 from dual union all
    10  select '000-ME-003' tag_number, 'Capacity 250' tag_details1, '000-TS-M-227' tag_details2 from dual union all
    11  select '000-ME-003' tag_number, 'Capacity 350' tag_details1, '' tag_details2 from dual
    12  )
    13  select tag_number
    14       , max (decode (tag_details1, 'Capacity 150', tag_details2))
    15       , max (decode (tag_details1, 'Capacity 250', tag_details2))
    16       , max (decode (tag_details1, 'Capacity 350', tag_details2))
    17    from test
    18   group by tag_number
    19  /
    TAG_NUMBER MAX(DECODE(T MAX(DECODE(T MAX(DECODE(T
    000-ME-002 000-TS-M-226 000-TS-M-227 000-TS-M-228
    000-ME-001 000-TS-M-226 000-TS-M-227 000-TS-M-228
    000-ME-003 000-TS-M-226 000-TS-M-227Edited by: Alex Nuijten on Jun 3, 2009 4:03 PM

  • Convert row values to columns

    
    I have a SQL statement which outputs a two column table with a ProjectName and a MemberFullValue, both text types values:
    SELECT proj.ProjectName, lt.MemberFullValue
    FROM dbo.MSP_EpmProject_UserView AS proj
    LEFT JOIN [dbo].[MSPCFPRJ_IT Pillar(s)_AssociationView] AS itpillar
    ON proj.ProjectUID = itpillar.EntityUID
    LEFT JOIN dbo.MSP_EpmLookupTable AS lt
    ON itpillar.LookupMemberUID = lt.MemberUID
    Both columns can contain duplicate values and both contain text.
    When there are duplicate values for 'ProjectName' I want to convert the corresponding 'MemberFullValue' values to columns. I have looked at a lot of different solutions to questions already posted, but I am not a SQL genius so I cannot get any of them to work.
    Can someone help me out? Thanks.
    

    Sounds like this to me
    SELECT ProjectName,
    [1] AS Value1,
    [2] AS value2,
    [3] AS Value3,
    [4] AS Value4,
    [5] AS Value5,
    [6] AS Value6
    FROM
    SELECT ROW_NUMBER() OVER (PARTITION BY proj.ProjectName ORDER BY proj.ProjectName) AS Seq,
    proj.ProjectName, lt.MemberFullValue
    FROM dbo.MSP_EpmProject_UserView AS proj
    LEFT JOIN [dbo].[MSPCFPRJ_IT Pillar(s)_AssociationView] AS itpillar
    ON proj.ProjectUID = itpillar.EntityUID
    LEFT JOIN dbo.MSP_EpmLookupTable AS lt
    ON itpillar.LookupMemberUID = lt.MemberUID
    )t
    PIVOT (MAX(MemberFullValue) FOR Seq IN ([1],[2],[3],[4],[5],[6]))p
    to make it dynamic you can use this
    http://beyondrelational.com/modules/2/blogs/70/posts/10840/dynamic-pivot-in-sql-server-2005.aspx
    If this is not what you're after, post some sample data and explain the required output
    Please Mark This As Answer if it solved your issue
    Please Mark This As Helpful if it helps to solve your issue
    Visakh
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Please help - Joining three tables and get row values into Column. Please help!

    Hi,
    There is a SourceTable1 (Employee) with Columns like EmployeeID,Name,DOB.
    There is a sourcetable2 (EmployeeCode) with columns like EmployeeID,Code,Order.
    There is a source table 3  #EmployeeRegioncode  and its columns are (EmployeeID , RegionCode , [Order] 
    The target table 'EmployeeDetails' has the following details. EmployeeID,Name,DOB,Code1,Code2,Code3,Code4,regioncode1
    regioncode2 ,regioncode3 ,regioncode4 
    The requirement is , the value of the target table columns the Code1,code2,code3 ,code4,code5 values should
    be column 'Code' from Sourcetable2 where its 'Order' column is accordingly. ie) Code1 value should be the 'Code' value where [Order] column =1, and Code2 value should be the 'Code' value where [Order] =2, and so on.
    Same is the case for Source table 3- 'Region code' column also for the columns  regioncode1
    regioncode2 ,regioncode3 ,regioncode4 
    Here is the DDL and Sample date for your ref.
    IF OBJECT_ID('TEMPDB..#Employee') IS NOT NULL DROP TABLE #Employee;
    IF OBJECT_ID('TEMPDB..#EmployeeCode') IS NOT NULL DROP TABLE #EmployeeCode;
    IF OBJECT_ID('TEMPDB..#EmployeeDetails') IS NOT NULL DROP TABLE #EmployeeDetails;
    ---Source1
    CREATE table #Employee 
    (EmployeeID int, Empname varchar(20), DOB date )
    insert into #Employee VALUES (1000,'Sachin','1975-12-12') 
    insert into #Employee VALUES (1001,'Sara','1996-12-10') 
    insert into #Employee  VALUES (1002,'Arjun','2000-12-12')
    ---Source2
    CREATE table #EmployeeCode 
    (EmployeeID int, Code varchar(10), [Order] int)
    insert into #EmployeeCode VALUES (1000,'AA',1) 
    insert into #EmployeeCode VALUES (1000,'BB',2)   
    insert into #EmployeeCode  VALUES (1000,'CC',3)  
    insert into #EmployeeCode VALUES  (1001,'AAA',1)  
    insert into #EmployeeCode  VALUES  (1001,'BBB',2)  
    insert into #EmployeeCode  VALUES  (1001,'CCC',3)  
    insert into #EmployeeCode  VALUES  (1001,'DDD',4)  
    insert into #EmployeeCode  VALUES  (1002,'AAAA',1)  
    insert into #EmployeeCode  VALUES  (1002,'BBBB',2)  
    insert into #EmployeeCode  VALUES  (1002,'CCCC',3)  
    insert into #EmployeeCode  VALUES  (1002,'DDDD',4)  
    insert into #EmployeeCode  VALUES  (1002,'EEEE',5)  
    ---Source tbl 3
    CREATE table #EmployeeRegioncode 
    (EmployeeID int, RegionCode varchar(10), [Order] int)
    insert into #EmployeeRegioncode VALUES (1000,'xx',1) 
    insert into #EmployeeRegioncode VALUES (1000,'yy',2)   
    insert into #EmployeeRegioncode  VALUES (1000,'zz',3)  
    insert into #EmployeeRegioncode VALUES  (1001,'xx',1)  
    insert into #EmployeeRegioncode  VALUES  (1001,'yy',2)  
    insert into #EmployeeRegioncode  VALUES  (1001,'zz',3)  
    insert into #EmployeeRegioncode  VALUES  (1001,'xy',4)  
    insert into #EmployeeRegioncode  VALUES  (1002,'qq',1)  
    insert into #EmployeeRegioncode  VALUES  (1002,'rr',2)  
    insert into #EmployeeRegioncode  VALUES  (1002,'ss',3)  
    ---Target
    Create table #EmployeeDetails
    (EmployeeID int, Code1 varchar(10), Code2 varchar(10),Code3 varchar(10),Code4 varchar(10),Code5 varchar(10) , regioncode1 varchar(10),
    regioncode2 varchar(10),regioncode3 varchar(10),regioncode4 varchar(10))
    insert into #EmployeeDetails  VALUES (1000,'AA','BB','CC','','','xx','yy','zz','')  
    insert into #EmployeeDetails  VALUES (1001,'AAA','BBB','CCC','DDD','','xx','yy','zz','xy')  
    insert into #EmployeeDetails VALUES (1002,'AAAA','BBBB','CCCC','DDDD','EEEE','qq','rr','ss','')  
    SELECT * FROM  #Employee
    SELECT * FROM  #EmployeeCode
    SELECT * FROM  #EmployeeRegioncode
    SELECT * FROM  #EmployeeDetails
    Can you please help me to get the desired /targetoutput?  I have sql server 2008.
    Your help is greatly appreciated.

    select a.EmployeeID,b.code1,b.code2,b.code3,b.code4,b.code5,c.Reg1,c.Reg2,c.Reg3,c.Reg4 from
    #Employee a
    left outer join
    (select EmployeeID,max(case when [Order] =1 then Code else '' end) code1,
    max(case when [Order] =2 then Code else '' end)code2,
    max(case when [Order] =3 then Code else '' end)code3,
    max(case when [Order] =4 then Code else '' end)code4,
    max(case when [Order] =5 then Code else '' end)code5 from #EmployeeCode group by EmployeeID) b
    on a.EmployeeID=b.EmployeeID
    left outer join
    (select EmployeeID,max(case when [Order] =1 then RegionCode else '' end) Reg1,
    max(case when [Order] =2 then RegionCode else '' end)Reg2,
    max(case when [Order] =3 then RegionCode else '' end)Reg3,
    max(case when [Order] =4 then RegionCode else '' end)Reg4 from #EmployeeRegioncode group by EmployeeID) c
    on a.EmployeeID=c.EmployeeID
    Thanks
    Saravana Kumar C

  • Row values into column....

    Hi Experts,
    Can i add column values into a single cell. Like my requirement is i want to add values of Name column in a single cell of some other table. For example if Table A contains A, B, C D names then in second table i want all these name in one cell as ABCD. I'm not able to find solution. please help me. i'm working on ODI. Any help or clue.
    Regards
    -Kirti

    Hi,
    2 suggestions:
    1) If you have a constant number of columns you could put, at an interface, so much "instances" of the datastore as the number of columns, create the join and put the necessary filter at each "instance". The mapping will be the concatenation of the column from each instance
    or
    2) Create a procedure where you have the select column_to_be_concatenated at Source TAB and an update of that at Target TAB (if necessary you can define a dynamic PL/SQL to deal with insert update!)
    Does it help you?

  • Move row values to columns

    Hi all,
    i have a a table that looks like this:
    ID NAME ADDR
    01 SAM USA
    02 JIM USA
    03 BEN USA
    03 BEN ENG
    04 TIM ENG
    05 MEG USA
    05 MEG JAP
    05 MEG ENG
    i need it so that names BEN and MEG do not have separate records for every ADDR they have. every ADDR should be in a column within the same record. the maximum ADDR is 3.
    ID NAME ADDR1 ADDR2 ADDR3
    01 SAM USA
    02 JIM USA
    03 BEN USA ENG
    04 TIM ENG
    05 MEG USA JAP ENG
    can somebody help?
    Thanks!

    SQL> with t
      2  as
      3  (select '01' ID ,'SAM' NAME,'USA' ADDR from dual
      4  union all
      5  select'02','JIM','USA' from dual
      6  union all
      7  select'03','BEN','USA' from dual
      8  union all
      9  select'03','BEN','ENG' from dual
    10  union all
    11  select'04','TIM','ENG' from dual
    12  union all
    13  select'05','MEG','USA' from dual
    14  union all
    15  select'05','MEG','JAP' from dual
    16  union all
    17  select'05','MEG','ENG' from dual
    18  )
    19  select id,
    20         name,
    21         max(decode(rn,1,addr,null)) ADDR1,
    22         max(decode(rn,2,addr,null)) ADDR2,
    23         max(decode(rn,3,addr,null)) ADDR3
    24  from
    25      (select id,name,addr,row_number() over(partition by ID order by 1) rn
    26       from t)
    27  group by id,name
    28  order by 1
    29  /
    ID NAM ADD ADD ADD
    01 SAM USA
    02 JIM USA
    03 BEN USA ENG
    04 TIM ENG
    05 MEG USA JAP ENG
    SQL>

Maybe you are looking for