Need Help on PL/SQL Cursor

Hi friends ,
I am getting 3 columns from one table thr cursor,
At the same time I am getting 7 columns from another one table.
Now I am comparing the 1st tables first_name with the 2nd tables firs_name
as
FOR I IN C_DS_OP_M_USER_MAP LOOP
V_COUNT := 0;
FOR J IN C_SI_OP_M_USER LOOP
          IF (I.FIRST_NAME = J.FIRST_NAME) AND (I.LAST_NAME = J.LAST_NAME) AND (I.USER_CODE = J.USER_ID) THEN
DBMS_OUTPUT.PUT_LINE('MATCHES ' ||I.USER_CODE||' '||I.FIRST_NAME||' '||I.LAST_NAME);
V_COUNT := V_COUNT+1;
END IF;
     END LOOP;
IF V_COUNT = 0 THEN
DBMS_OUTPUT.PUT_LINE('NOT MATCHES '|| I.USER_CODE ||' '|| I.FIRST_NAME ||' '|| I.LAST_NAME);
END IF;
But the problem is , I couldn't get the first record comparison only, all the other records are being displayed correctly.
Please help me to recover this problem.
Thank you

Where is the other END LOOP in the procedure?
Moreover, I think it is better if you achaive this using joins.
declare
cursor c1 as select a.col1, b.col2, a.col2
from a, b
where a.col1 = b.col1
and a.col2 = b.col2
and a.col3 = b.col3;
v_val number := 0;
begin
   for r1 in c1 loop
      dbms_output.put_line(col1||','col2||','||col3);
      v_val := v_val +1;
   end loop;
   if v_val = 0 then
      dbms_output.put_line('No matches');
   end if;
end;Cheers
Sarma.

Similar Messages

  • Need help on Dynamic SQL Cursor in Forms

    Hi All,
    I am trying to execute Dynamic SQL Cursor in forms using EXEC_SQL built in.
    I have a cursor for example:
    'select * from supplier where supplier = '||p_supplier||' and processing_order = '||p_order
    My code is
    cur_num := Exec_SQL.Open_cursor;
    sql_order := 'select * from supplier where supplier = '||p_supplier||' and processing_order = '||p_order;
    EXEC_SQL.PARSE(cursor_number, sql_order);
      EXEC_SQL.DEFINE_COLUMN(cur_num ,1,ln_Supp_Id);
      EXEC_SQL.DEFINE_COLUMN(cur_num ,2,ls_Suppl_Name,30);
    EXEC_SQL.DEFINE_COLUMN(cur_num ,24,ls_exchange,20);
      sql_count := EXEC_SQL.EXECUTE(cur_num );
      While EXEC_SQL.FETCH_ROWS(cur_num ) > 0 Loop
            EXEC_SQL.COLUMN_VALUE(cur_num ,1,ln_Supp_Id);
            EXEC_SQL.COLUMN_VALUE(cur_num ,2,ls_Suppl_Name);
            EXEC_SQL.COLUMN_VALUE(cur_num ,24,ls_exchange);
    End Loop;
    EXEC_SQL.CLOSE_CURSOR(cur_num );
    In this case I have to write 24 Define Columns and 24 Column value. Is there any way to assign them to %rowtype at one time as I need all coulmn of the table.
    I had similar case on multiple tables.
    Please help me
    Thanks,
    Maddy

    I need this dynamic sql because p_supplier and p_order values changes at run time
    I do not understand. Is this a simplified sample or the real thing? You do know that you can pass variables to cursors:
    cursor test is
    select * from supplier where supplier = p_supplier and processing_order = p_order;
    or does e.g. p_supplier hold other parts of the query?
    cheers

  • New To Oracle.. Needs Help:: Conversion from SQL Server to Oracle 11g

    I am new to Oracle 11g and badly need the conversion of SQL Server Functions to Oracle.. Sample Pasted Code not working .. end with error.. pls help
    Create Table TempT (ID1 Varchar (10),
    ID2 Varchar (10)
    CREATE OR REPLACE PACKAGE GLOBALPKG
    AS
    TYPE RCT1 IS REF CURSOR;
    TRANCOUNT INTEGER := 0;
    IDENTITY INTEGER;
    END;
    CREATE OR REPLACE FUNCTION fTempT
    i IN VARCHAR2 DEFAULT NULL
    RETURN GLOBALPKG.RCT1
    IS
    REFCURSOR GLOBALPKG.RCT1;
    BEGIN
    OPEN REFCURSOR FOR
    SELECT TT.*
    FROM TempT TT
    WHERE (fTempT.i = ''
    OR TT.ID1 = fTempT.i)
    RETURN REFCURSOR;
    END;
    CREATE OR REPLACE FUNCTION fTempTF
    i IN VARCHAR2 DEFAULT NULL
    RETURN GLOBALPKG.RCT1
    IS
    REFCURSOR GLOBALPKG.RCT1;
    BEGIN
    OPEN REFCURSOR FOR
    SELECT *
    FROM TABLE(fTempT(i))
    RETURN REFCURSOR;
    END;
    LAST FUNCTION ENDs WITH ERROR
    Error(13,7): PL/SQL: ORA-22905: cannot access rows from a non-nested table item

    2. The major purpose is to get a simplest way to create a parameterized function who can return a table like output. 2nd function has no use instead i was testing the result of First Function like thisIf you just want to select from a select, you should use a view not a function.
    1. which program is more help ful for writing and executing queries bcoz after using Query Analyzer of Microsoft It seems difficult to work on SQL Developer.
    sqlplus? If you are having difficulty learning new tools because of an old one you used, probably best to forget the old one and concentrate on learning the new one because it will be different. This goes for the database itself also.
    2. Can DMLs be used within a Function.Yes, you just can't execute the function in another SQL statement if it modifies data and this is a good thing.
    3. Can temporary tables be used within a function.Unfortunately yes, but they shouldn't be unless you are in a slowest application competition.
    5. Each Function which is a Table Function must be accompanied with Type Definitions?? its a bit longer way of doing the things than SQL ServerThat is why it is better to use views instead, is there any reason you want a select that you can select from inside a function?
    SQL Server for last 9 years thats why i refer this toolThat is not in itself a problem, if you try and do what you did in SQLServer in Oracle, that will be a problem though.

  • I need help on This SQL problem ASAP :)

    Hi All,
    I need help on this....
    I have a table...
    Say table name: one
    with these values
    premnum status
    1234 C
    1234 F
    1234 P
    1234 F
    5678 C
    5678 F
    5678 P
    9112 C
    9112 F
    9112 P
    9112 F
    3456 C
    3456 F
    3456 P
    7890 C
    7890 P
    7890 F
    Now, I want to output only those premnum with status = 'C' and those premnum with Status 'F' having a count > 1 (with two status = 'F')
    So the output would be something like this
    premnum status
    1234 C
    1234 F
    1234 F
    5678 C
    9112 C
    9112 F
    9112 F
    3456 C
    7890 C
    I really need help on this asap...
    I need the SQL statement on this....
    Thank you in advance. :)
    Edited by: 804697 on Oct 23, 2010 9:45 PM

    Hi,
    you can use the following query.
    CREATE TABLE PREM_TEST ( premnum NUMBER , STATUS VARCHAR2(1));
    INSERT INTO PREM_TEST VALUES(1234 ,'C');
    INSERT INTO PREM_TEST VALUES(1234 ,'F');
    INSERT INTO PREM_TEST VALUES(1234 ,'P');
    INSERT INTO PREM_TEST VALUES(1234 ,'F');
    INSERT INTO PREM_TEST VALUES(5678 ,'C');
    INSERT INTO PREM_TEST VALUES(5678 ,'F');
    INSERT INTO PREM_TEST VALUES(5678 ,'P');
    INSERT INTO PREM_TEST VALUES(9112 ,'C');
    INSERT INTO PREM_TEST VALUES(9112 ,'F');
    INSERT INTO PREM_TEST VALUES(9112 ,'P');
    INSERT INTO PREM_TEST VALUES(9112 ,'F');
    INSERT INTO PREM_TEST VALUES(3456 ,'C');
    INSERT INTO PREM_TEST VALUES(3456 ,'F');
    INSERT INTO PREM_TEST VALUES(3456 ,'P');
    INSERT INTO PREM_TEST VALUES(7890 ,'C');
    INSERT INTO PREM_TEST VALUES(7890 ,'P');
    INSERT INTO PREM_TEST VALUES(7890 ,'F');
    SELECT     PREMNUM , STATUS
    FROM     PREM_TEST
    WHERE     STATUS = 'C'
    OR          (PREMNUM , STATUS ) IN (     SELECT PREMNUM , STATUS
                                                 FROM     PREM_TEST
                                                 WHERE     STATUS = 'F'
                                                 GROUP BY PREMNUM , STATUS
                                                 HAVING COUNT(*) > 1
    PREMNUM S
    1234 C
    1234 F
    1234 F
    5678 C
    9112 C
    9112 F
    9112 F
    3456 C
    7890 C
    9 rows selected.

  • Need help on a sql query

    Hi Friends,
    I am trying to load Employees and their Assignments using APIs.
    I have various columns in my staging table like Last Name, First Name, etc., but I need help in writing query in the cursor especially for columns Emp Number and Supervisor Number.
    I have data as below
    Emp_Number     Supervisor_Number
    GE0002               GE0064
    GE0064               EG0009
    EG0009               EG0001
    100009                EG0001
    EG0001               TU0001
    Cursor I write will process the data in the same order as above, but here the problem is...
    When it processes first row, it checks for supervisor GE0064 which do not exist and so it errors out.
    Similarly for second row, it checks for supervisor EG0009 which again do not exist and so it errors out.
    So in order to prevent this, the cursor should process the rows as below
    Emp_Number     Supervisor_Number
    EG0001               TU0001
    EG0009               EG0001
    GE0064               EG0009
    GE0002               GE0064
    100009                EG0001
    By this way, Supervisor should be defined first as an employee and then it can be used as a supervisor for other employees
    is there a way that I can get the output as above(second set of data), when the table has records randomly as above(first set of data)
    Appreciate your help!
    Thanks,
    Srikanth

    Srikanth wrote:
    ... but the number of records returned by above query are lot more than number of records in the table.
    Why did the number go up?
    It's something only you can find out
    Maybe some Emp have several Supervisor(s) like
    with
    t as
    (select 'GE0002' Emp,'GE0064' Supervisor from dual union all
    select 'GE0064','EG0009' from dual union all
    select 'EG0009','EG0001' from dual union all
    select 'GE0064','100009' from dual union all
    select '100009','EG0001' from dual union all
    select 'EG0001','TU0001' from dual
    select Emp,Supervisor,lpad('_',3 * (level - 1),'_')||Emp indent
      from (select Emp,Supervisor
              from t
            union all
            select supervisor,null
              from t tt
             where not exists(select null
                                from t
                               where emp = tt.supervisor
    start with Supervisor is null
    connect by prior Emp = Supervisor
    EMP
    SUPERVISOR
    INDENT
    TU0001
    TU0001
    EG0001
    TU0001
    ___EG0001
    100009
    EG0001
    ______100009
    GE0064
    100009
    _________GE0064
    GE0002
    GE0064
    ____________GE0002
    EG0009
    EG0001
    ______EG0009
    GE0064
    EG0009
    _________GE0064
    GE0002
    GE0064
    ____________GE0002
    Regards
    Etbin

  • Hi all, need help in PL SQL?

    I am new in this industry. I have my training going on ORACLE PL SQL.
    Can somebody help me out:
    1.) How do we write program to add two numbers and then printing them as output.
    2.) How do we write program to read from a file and then write to another file.
    3.) How do we write program to send an email from your program.
    4.) How do we write program to create random numbers.
    Thanks in advance. . .

    Hello;
    This forum is dedicated for Oracle Beehive, if you need help and advices on SQL/PL-SQL please open a thread on the following forum: PL/SQL
    About your third question, if you want to send an email from Beehive the best way is to perform that through the Web Services.
    Fred

  • Need Help in Simple SQL

    Hi,
    I need help. I did not know how to make this select statement run without error.
    select iif(max(numberseries) is null,'0',numberseries+ 1) from registration
    Thank

    Hi ,
    May i know what are you trying to do ,
    if you are trying to use if else in query, then it wont work
    if else is not valid in query.
    try to use decode or case , such that your need can be full filled
    Thank you
    Raj Deep.A

  • Need a help in pl/sql cursors

    Hi,
    wrong posted...if i have any clarifications i can mail to all.
    thanks...

    This is how formatted code looks like.
    I have removed superflous BEGIN .. END (Which lead to code that would not compile)
    This is your code, not mine
    DECLARE
      CURSOR stagingtablerecords IS
        SELECT *
        FROM   mdat_lseveh_options;
      r      mdat_lseveh_options%ROWTYPE;
      svar   NUMBER;
    BEGIN
      FOR r IN stagingtablerecords LOOP
        IF r.heading_sw = 'Y' THEN
          INSERT INTO pref_accessory_category (acc_cat_id,
                                               acc_cat_desc,
                                               last_modified,
                                               model_cd,
                                               model_yr,
                                               interior,
                                               ext_accessory
          VALUES      (refcatidseq.NEXTVAL,
                       r.std_equip_txt,
                       SYSDATE,
                       r.model_cd,
                       r.model_year,
                       NULL,
                       NULL
          svar := acc_cat_id; -- Problem here
        ELSIF r.heading_sw = 'N' THEN
          INSERT INTO pref_accessory (acc_id,
                                      acc_desc,
                                      acc_cat_id,
                                      model_cd,
                                      model_yr,
                                      last_modified
          VALUES      (refaccidseql.NEXTVAL,
                       r.std_equip_txt,
                       svar,
                       r.model_cd,
                       r.model_year,
                       SYSDATE
        END IF;
      END LOOP;
      COMMIT;
    END;
    /You have a problem with your staging table, since there is no information on which accessories belongs to which categories.
    You seem to rely on some sort of order, but this order do not exist, unless expressed explicitly.
    If data comes from a file and is sorted in there, then you could add a line number, or a sequential number or such as you load them into stage table.
    This number should be used when reading from stage table to ensure lines are processed like
    Y1
    N1
    N1
    N1
    Y2
    N2
    N2
    Right now, you have no control over the stage table
    Edit:
    I would try with something like, (Not tested, or anything else - And never tried this with sequences, suspect it may not work)
    INSERT ALL
    WHEN heading_sw = 'Y' THEN
      INTO   pref_accessory_category (acc_cat_id,
                                      acc_cat_desc,
                                      last_modified,
                                      model_cd,
                                      model_yr,
                                      interior,
                                      ext_accessory
      VALUES (refcatidseq.NEXTVAL,
              std_equip_txt,
              SYSDATE,
              model_cd,
              model_year,
              NULL,
              NULL
    WHEN heading_sw = 'N' THEN
      INTO   pref_accessory (acc_id,
                             acc_desc,
                             acc_cat_id,
                             model_cd,
                             model_yr,
                             last_modified
      VALUES (refaccidseql.NEXTVAL,
              r.std_equip_txt,
              refcatidseq.CURRVAL,
              r.model_cd,
              r.model_year,
              SYSDATE
      SELECT   std_equip_txt,
               model_cd,
               model_year
      FROM     stagingtablerecords
      ORDER BY your_new_column;Regards
    Peter

  • Need help with jdbc and cursor

    Hi all,
    I know I can specify a cursor to be scrollable with
    cs = conn.prepareCall("{call server.procedure(?,?)}",ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
    but my problem is that this cursor is returning 2 oracle cursors and I need to move inside those but I cannot find the way to do it.
    cs.registerOutParameter(2, OracleTypes.CURSOR);
    rs = (ResultSet) cs.getObject(2); //this is the first cursor and is scrollable
    rs1= (ResultSet) rs.getObject(1); //this is one of the cursors inside the cursor and I cannot make it scrollable
    Thanks for the help,
    A.

    well, I didn't really check if the first one was scrollable since I didn't need it to be, but it seems that Oracle does not support scrollable cursors as out parameter of a stored procedure...
    anybody has a workaround?

  • Need help in using SQL in a jsp file to compare date and time

    hi every one,
    Actually I am doing a project using JSP. I need to compare a date field in the database (MS Acess) to the current system date and time. I have to do this in a select statement.
    I have alredy defined a variable of type Date in the JSP file and I am comparing this variable to the date in the database through a select statemant.
    Here is what I am doing
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
              java.util.Date today = new java.util.Date();
              String myDate=sdf.format(today);
    query = "SELECT Car_ID, Model_ID, Year, Ext_Color, Price from Cars where EDate <= "+myDate+" ;";
    EDate is the feild in the database and it's format is (5/12/2008 5:29:47 PM) it is of type Date/Time in MS Acess.
    when I execute the query it gives the following error
    SQL error:java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression 'EDate <= 2008-10-16 08:10:07'.
    I hope any one can help me with that error and answer my question, I've tried too many things but nothing helps
    Thanks in advance :-)

    Hi,
    When the comparision is needed to be done with the current date , we don't need to send in Java
    Date then format it and compare with MS Acess Date.
    In MS Access we have Date() function which will give you the current date.
    So you can try rewriting your query as following :
    query = "SELECT Car_ID, Model_ID, Year, Ext_Color, Price from Cars where EDate <= Date() ;"; ---------------------
    Hope this helps.
    Thanks

  • Need help on small sql query

    Hi,
    I have a requirement where I need to show 'F&D' string. I can explain this by below query.
    select 'F&D' from dual
    but when I run this query, toad prompts me to enter value for &D variable :( But my requirement is to show 'F&D' string.
    Can anyone please tell me what modification needs to be done to above query to get string 'F&D' as output.
    I know work around for this as below.
    select 'F'||chr(38)||'D' from dual
    I want permenant solution for this. Can anyone please help me?
    Thanks
    Shantanu

    see if below make difference
    SQL> select 'F&D' from dual ;
    Enter value for d: &D
    old   1: select 'F&D' from dual
    new   1: select 'F&D' from dual
    'F&
    F&D
    SQL> select 'F'||'&'||'D' from dual ;
    'F'
    F&D

  • Need help: Form6i PL/SQL library not found!

    New oracle user need your help:
    I installed Form6i and PO8i on NT, and config the tnsnames.ora file, they both worked fine to connect. But when I try to look into the PL/SQL library, it said PL/SQL library can not found. I deleted the classpath because with it I can't run Java, and the Sun help menu told me I can delete classpath to let it use current directory, is this the reason that Oracle can't find the library?
    One more question: when I connect to database from Form, Username, Password, then Databasename, for this last one, if I leave it blank, it will connect to the database, but if I type in my database name(the default DB name), it will again give me error message, said TNS can't resolve service. Does anybody have a clue? Thank you so much!

    The answer for on more question:
    It's not db name but service name.
    A sample in tnsname.ora:
    DKORCL[the service name].world =
    (DESCRIPTION =
    (ADDRESS_LIST =
    (ADDRESS = (PROTOCOL = TCP)(HOST = dlt_db_srv[host_name])(PORT = 1521))
    (CONNECT_DATA =
    (SERVICE_NAME = dkorcl[oracle service name])
    You say,"u can leave it blank ",then u must work at the server.And the name u type in is not correct.
    May this help u!
    null

  • Need help to run sql loader from Form6i

    Hi All,
    I have some problem with the sql loader running from form 6i.
    I have done following steps for that.
    1. have created bat file to run sql loader.
    2.Alos created ctl and txt files inside the same folder.
    In the form , in button press i have written below code
    HOST('cmd /c C:\load1.bat > C:\output.txt');
    But it is giving error as -
    "Unable to open Load1.ctl."
    but i have run that bat files from command prompt ; and it is running fine.
    I guess probably it is not getting the correct path.
    Will pls help me, wt exacly I'm doing wrong?
    Rg,
    Subir

    Hi Francois,
    Thanks for reply.
    It is not a problem with the batch files. Coz, I just able to run batch files, but that is not correct solution.
    Once the host command id firing, that time it is going to path -
    "c:\orant\Form60\"
    And in this path it searching for that batch files and all the require files; but the require files are present in some different folder. So i think I need to change the path as well, but that I'm unable to do.
    To resolve the problem, I have copied all the files in "c:\orant\Form60\" folder, and then it is working.
    So I think I need to changed the path, so how to change the path. If I able to change the path I think it will worked. How to change the path?
    Best Rg,
    Subir

  • Need Help on the sql

    Hi All,
    I need to prepare a report having monthly data. For this i am using query to pull data from the table having monthly data. Below are the complete details.
    Table Details:
    column_name data_type
    status varchar2(5)
    description varchar2(35)
    report_date date
    member_count number
    It have the sample data like below:
    status Description Report_date member_count
    0 Voluntary Disenrollment 7/1/2012
    1 Regular 7/1/2012 96540
    5 HOLD - Medi-Cal Ineligibility 7/1/2012 57
    55 Unmet Share of Cost 7/1/2012 6074
    59 HOLD - HCP Coverage Limits 7/1/2012 699
    P4 Pending Enrollment 7/1/2012
    S0 Retro - Voluntary Disenrollment 7/1/2012
    S1 Retro - Add 7/1/2012
    S9 Retro - Mandatory Disenrollment 7/1/2012
    similarly it have data for different report_date's. I need to pull data from this table like below.
    Status Description 7/1/2012 6/1/2012 5/1/2012 4/1/2012
    00 Voluntary Disenrollment 1 3
    01 Regular 96,540 96,620 96,500 96,429
    05 HOLD - Medi-Cal Ineligibility 57
    55 Unmet Share of Cost 6,074 6,652 6,899 6,922
    59 HOLD - HCP Coverage Limits 699
    P4 Pending Enrollment 1
    S0 Retro - Voluntary Disenrollment 14 13 24
    S1 Retro - Add 4,587 7,200 8,288
    S9 Retro - Mandatory Disenrollment 2 4 1
    i need to get all the details like above from 07/01/2012 to 07/01/2011. Similarly if i pull the data next month it should have all details form 08/01/2012 to 08/01/2011.
    I am using below query i am not able to get the result as intended.
    select status,description,
    max(decode(TO_CHAR(report_date,'MON'),'JAN',member_count,0)) jan,
    max(decode(TO_CHAR(report_date,'MON'),'FEB',member_count,0)) feb,
    max(decode(TO_CHAR(report_date,'MON'),'MAR',member_count,0)) mar,
    max(decode(TO_CHAR(report_date,'MON'),'APR',member_count,0)) apr,
    max(decode(TO_CHAR(report_date,'MON'),'JUN',member_count,0)) may,
    max(decode(TO_CHAR(report_date,'MON'),'JUL',member_count,0)) jun,
    max(decode(TO_CHAR(report_date,'MON'),'AUG',member_count,0)) jul,
    max(decode(TO_CHAR(report_date,'MON'),'SEP',member_count,0)) aug
    from MONTHLY_MEMBERSHIP_REPORT_834
    where report_date >=to_date('2012/01/01','yyyy/dd/mm')
    group by description,status
    order by status;
    Can some one help me on this..?
    Edited by: 948188 on Jul 23, 2012 11:36 AM
    Edited by: 948188 on Jul 23, 2012 11:36 AM

    Hi,
    Are the results you posted really what you want given the sample data you posted? If looks like all the report_dates in the sample data are in July, 2011, so I don't see how you get non-0 values in the other columns.
    To automatically get the most recent 13 months, you can do something like this:
    WITH   got_month_num       AS
         SELECT     status, description, member_count
         ,     MONTHS_BETWEEN ( TRUNC (SYSDATE,     'MONTH')
                          , TRUNC (report_date, 'MONTH')     
                          )            AS month_num
         FROM    monthly_membership_report_834
         WHERE     report_date     >= ADD_MONTHS ( TRUNC (SYSDATE, 'MONTH')
                                      , -12
         AND     report_date     <  ADD_MONTHS ( TRUNC (SYSDATE, 'MONTH')
                                      , 1
    SELECT       status,       description
    ,       MAX (DECODE (month_num,  0, member_count, 0))     AS m0
    ,       MAX (DECODE (month_num,  1, member_count, 1))     AS m1
    ,       MAX (DECODE (month_num, 11, member_count, 0))     AS m11
    ,       MAX (DECODE (month_num, 12, member_count, 0))     AS m12
    FROM       got_month_num
    GROUP BY  status,       description
    ORDER BY  status,       description
    ;Output from the sample data you posted:
    STATUS DESCRIPTION                              M0      M1     M11     M12
    00     Voluntary Disenrollment                   0       1       0
    01     Regular                                   0       1       0   98294
    05     HOLD - Medi-Cal Ineligibility             0       1       0
    55     Unmet Share of Cost                       0       1       0    5488
    59     HOLD - HCP Coverage Limits                0       1       0
    P4     Pending Enrollment                        0       1       0
    S0     Retro - Voluntary Disenrollment           0       1       0      75
    S1     Retro - Add                               0       1       0    7586
    S9     Retro - Mandatory Disenrollment           0       1       0       2If you want the column names to indicate the actual months, insrtead of having generic names like m0, then you need dynamic SQL.
    In SQL*Plus, that isn't very difficult. Here's one way, using SQL*Plus substiotution variables:
    --  Preliminary Query, to set substritution variables
    COLUMN      m0_col          NEW_VALUE     m0
    COLUMN      m1_col          NEW_VALUE     m1
    COLUMN      m11_col     NEW_VALUE     m11
    COLUMN      m12_col     NEW_VALUE     m12
    SELECT      TO_CHAR (             SYSDATE      , 'fmMM/YYYY')     AS m0_col
    ,      TO_CHAR ( ADD_MONTHS (SYSDATE,  -1), 'fmMM/YYYY')     AS m1_col
    ,      TO_CHAR ( ADD_MONTHS (SYSDATE, -11), 'fmMM/YYYY')     AS m11_col
    ,      TO_CHAR ( ADD_MONTHS (SYSDATE, -12), 'fmMM/YYYY')     AS m12_col
    FROM     dual
    --  Main Query
    WITH   got_month_num       AS
         SELECT     status, description, member_count
         ,     MONTHS_BETWEEN ( TRUNC (SYSDATE,     'MONTH')
                          , TRUNC (report_date, 'MONTH')     
                          )            AS month_num
         FROM    monthly_membership_report_834
         WHERE     report_date     >= ADD_MONTHS ( TRUNC (SYSDATE, 'MONTH')
                                      , -12
         AND     report_date     <  ADD_MONTHS ( TRUNC (SYSDATE, 'MONTH')
                                      , 1
    SELECT       status,       description
    ,       MAX (DECODE (month_num,  0, member_count, 0))     AS "&m0"
    ,       MAX (DECODE (month_num,  1, member_count, 1))     AS "&m1"
    ,       MAX (DECODE (month_num, 11, member_count, 0))     AS "&m11"
    ,       MAX (DECODE (month_num, 12, member_count, 0))     AS "&m12"
    FROM       got_month_num
    GROUP BY  status,       description
    ORDER BY  status,       description
    ;Output (when run in July, 2012)
    STATUS DESCRIPTION                          7/2012  6/2012  8/2011  7/2011
    00     Voluntary Disenrollment                   0       1       0
    01     Regular                                   0       1       0   98294
    05     HOLD - Medi-Cal Ineligibility             0       1       0
    55     Unmet Share of Cost                       0       1       0    5488
    59     HOLD - HCP Coverage Limits                0       1       0
    P4     Pending Enrollment                        0       1       0
    S0     Retro - Voluntary Disenrollment           0       1       0      75
    S1     Retro - Add                               0       1       0    7586
    S9     Retro - Mandatory Disenrollment           0       1       0       2Notice that the main query is exacly what I posted earlier, except that the column aliases reference the siubstitution variables set in the preliminary query.
    Edited by: Frank Kulash on Jul 23, 2012 4:39 PM
    Added version with dynamic column aliases

  • Need help with a SQL qurey that returns multiple rows for one record?

    I have the following query where I use a CASE WHEN clause to determine the date of a shift that begins with "FRLO" on day1 - day14 of the pay period. It works great if a schedule record contains one day that begins "FRLO", but if more than one day is "FRLO" then it only returns the first day it finds and not the others. Is there some way to get the query to return a ron for every day 1 - 14 that begins "FRLO"? System if Oracle 11G
    Order of the results is not important as this is part of a larger query that orders the results.
    Thanks in advance for any help,
    George
    SELECT s.empid,
    CASE
    WHEN UPPER (SUBSTR (s.Day1, 0, 4)) = 'FRLO'
    THEN
    pp.startpp
    WHEN UPPER (SUBSTR (s.Day2, 0, 4)) = 'FRLO'
    THEN
    pp.startpp + 1
    WHEN UPPER (SUBSTR (s.Day3, 0, 4)) = 'FRLO'
    THEN
    pp.startpp + 2
    WHEN UPPER (SUBSTR (s.Day4, 0, 4)) = 'FRLO'
    THEN
    pp.startpp + 3
    WHEN UPPER (SUBSTR (s.Day5, 0, 4)) = 'FRLO'
    THEN
    pp.startpp + 4
    WHEN UPPER (SUBSTR (s.Day6, 0, 4)) = 'FRLO'
    THEN
    pp.startpp + 5
    WHEN UPPER (SUBSTR (s.Day7, 0, 4)) = 'FRLO'
    THEN
    pp.startpp + 6
    WHEN UPPER (SUBSTR (s.Day8, 0, 4)) = 'FRLO'
    THEN
    pp.startpp + 7
    WHEN UPPER (SUBSTR (s.Day9, 0, 4)) = 'FRLO'
    THEN
    pp.startpp + 8
    WHEN UPPER (SUBSTR (s.Day10, 0, 4)) = 'FRLO'
    THEN
    pp.startpp + 9
    WHEN UPPER (SUBSTR (s.Day11, 0, 4)) = 'FRLO'
    THEN
    pp.startpp + 10
    WHEN UPPER (SUBSTR (s.Day12, 0, 4)) = 'FRLO'
    THEN
    pp.startpp + 11
    WHEN UPPER (SUBSTR (s.Day13, 0, 4)) = 'FRLO'
    THEN
    pp.startpp + 12
    WHEN UPPER (SUBSTR (s.Day14, 0, 4)) = 'FRLO'
    THEN
    pp.startpp + 13
    END
    startdate,
    NULL starttime,
    NULL endtime,
    8 hours,
    0 minutes
    FROM schedules s
    JOIN
    payperiods pp
    ON pp.periodid = s.periodid
    WHERE UPPER (SUBSTR (s.Day1, 0, 4)) = 'FRLO'
    OR UPPER (SUBSTR (s.Day2, 0, 4)) = 'FRLO'
    OR UPPER (SUBSTR (s.Day3, 0, 4)) = 'FRLO'
    OR UPPER (SUBSTR (s.Day4, 0, 4)) = 'FRLO'
    OR UPPER (SUBSTR (s.Day5, 0, 4)) = 'FRLO'
    OR UPPER (SUBSTR (s.Day6, 0, 4)) = 'FRLO'
    OR UPPER (SUBSTR (s.Day7, 0, 4)) = 'FRLO'
    OR UPPER (SUBSTR (s.Day8, 0, 4)) = 'FRLO'
    OR UPPER (SUBSTR (s.Day9, 0, 4)) = 'FRLO'
    OR UPPER (SUBSTR (s.Day10, 0, 4)) = 'FRLO'
    OR UPPER (SUBSTR (s.Day11, 0, 4)) = 'FRLO'
    OR UPPER (SUBSTR (s.Day12, 0, 4)) = 'FRLO'
    OR UPPER (SUBSTR (s.Day13, 0, 4)) = 'FRLO'
    OR UPPER (SUBSTR (s.Day14, 0, 4)) = 'FRLO';
    CURRENT OUTPUT
    EMPID STARTDATE STARTTIME ENDTIME HOURS MINUTES
    753738, 3/25/2013 , , ,8 ,0
    753740, 3/25/2013 , , ,8 ,0
    753748, 3/25/2013 , , ,8 ,0
    DESIRED OUTPUT
    EMPID STARTDATE STARTTIME ENDTIME HOURS MINUTES
    753738, 3/25/2013 , , ,8 ,0
    753740, 3/25/2013 , , ,8 ,0
    753748, 3/25/2013 , , ,8 ,0
    753738, 3/26/2013 , , ,8 ,0
    753740, 3/26/2013 , , ,8 ,0
    753740, 3/28/2013 , , ,8 ,0
    753748, 1/1/2013 , , ,8 ,0
    753738, 4/3/2013 , , ,8 ,0
    753748, 4/3/2013 , , ,8 ,0
    CREATE TABLE SCHEDULES
    SCHEDULEID NUMBER(12) NOT NULL,
    EMPID NUMBER(12) NOT NULL,
    PERIODID VARCHAR2(6 BYTE) NOT NULL,
    AREAID NUMBER(12) NOT NULL,
    DAY1 VARCHAR2(50 BYTE),
    DAY2 VARCHAR2(50 BYTE),
    DAY3 VARCHAR2(50 BYTE),
    DAY4 VARCHAR2(50 BYTE),
    DAY5 VARCHAR2(50 BYTE),
    DAY6 VARCHAR2(50 BYTE),
    DAY7 VARCHAR2(50 BYTE),
    DAY8 VARCHAR2(50 BYTE),
    DAY9 VARCHAR2(50 BYTE),
    DAY10 VARCHAR2(50 BYTE),
    DAY11 VARCHAR2(50 BYTE),
    DAY12 VARCHAR2(50 BYTE),
    DAY13 VARCHAR2(50 BYTE),
    DAY14 VARCHAR2(50 BYTE),
    NOPTIND1 INTEGER DEFAULT 0,
    NOPTIND2 INTEGER DEFAULT 0,
    NOPTIND3 INTEGER DEFAULT 0,
    NOPTIND4 INTEGER DEFAULT 0,
    NOPTIND5 INTEGER DEFAULT 0,
    NOPTIND6 INTEGER DEFAULT 0,
    NOPTIND7 INTEGER DEFAULT 0,
    NOPTIND8 INTEGER DEFAULT 0,
    NOPTIND9 INTEGER DEFAULT 0,
    NOPTIND10 INTEGER DEFAULT 0,
    NOPTIND11 INTEGER DEFAULT 0,
    NOPTIND12 INTEGER DEFAULT 0,
    NOPTIND13 INTEGER DEFAULT 0,
    NOPTIND14 INTEGER DEFAULT 0
    CREATE TABLE PAYPERIODS
    PERIODID VARCHAR2(6 BYTE) NOT NULL,
    STARTPP DATE,
    ENDPP DATE
    Insert into SCHEDULES
    (SCHEDULEID, EMPID, PERIODID, AREAID, DAY1,
    DAY2, DAY3, DAY4, DAY5, DAY6,
    DAY7, DAY8, DAY9, DAY10, DAY11,
    DAY12, DAY13, DAY14, NOPTIND1, NOPTIND2,
    NOPTIND3, NOPTIND4, NOPTIND5, NOPTIND6, NOPTIND7,
    NOPTIND8, NOPTIND9, NOPTIND10, NOPTIND11, NOPTIND12,
    NOPTIND13, NOPTIND14)
    Values
    (3693744, 753738, '082013', 2167, 'X',
    'FRLO<1530>', 'FRLO<1530>', '1530', '1530', '1530',
    'X', 'X', '1530', '1530', 'FRLO',
    '1530', '1530', 'X', 0, 0,
    0, 0, 0, 0, 0,
    0, 0, 0, 0, 0,
    0, 0);
    Insert into SCHEDULES
    (SCHEDULEID, EMPID, PERIODID, AREAID, DAY1,
    DAY2, DAY3, DAY4, DAY5, DAY6,
    DAY7, DAY8, DAY9, DAY10, DAY11,
    DAY12, DAY13, DAY14, NOPTIND1, NOPTIND2,
    NOPTIND3, NOPTIND4, NOPTIND5, NOPTIND6, NOPTIND7,
    NOPTIND8, NOPTIND9, NOPTIND10, NOPTIND11, NOPTIND12,
    NOPTIND13, NOPTIND14)
    Values
    (3693745, 753740, '082013', 2167, 'X',
    'FRLO<1530>', 'FRLO<1530>', '1530', 'FRLO', '1530',
    'X', 'X', '1530', '1530', '1530',
    '1530', '1530', 'X', 0, 0,
    0, 0, 0, 0, 0,
    0, 0, 0, 0, 0,
    0, 0);
    Insert into SCHEDULES
    (SCHEDULEID, EMPID, PERIODID, AREAID, DAY1,
    DAY2, DAY3, DAY4, DAY5, DAY6,
    DAY7, DAY8, DAY9, DAY10, DAY11,
    DAY12, DAY13, DAY14, NOPTIND1, NOPTIND2,
    NOPTIND3, NOPTIND4, NOPTIND5, NOPTIND6, NOPTIND7,
    NOPTIND8, NOPTIND9, NOPTIND10, NOPTIND11, NOPTIND12,
    NOPTIND13, NOPTIND14)
    Values
    (3693746, 753748, '082013', 2167, 'X',
    'FRLO<1530>', '1530', '1530', '1530', '1530',
    'X', 'X', 'FRLO<1530>', '1530', 'FRLO',
    '1530', '1530', 'X', 0, 0,
    0, 0, 0, 0, 0,
    0, 0, 0, 0, 0,
    0, 0);
    COMMIT;
    Insert into PAYPERIODS
    (PERIODID, STARTPP)
    Values
    ('082013', TO_DATE('03/24/2013 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    COMMIT;

    Do you have the opportunity to change the data model to have one day per row ? It would make this easier to get this result without the need for a 14-way CASE or UNION.
    If not...
    The case statement will return as soon as it matches one of the conditions. Since you want a match when any column in the row starts with FRLO you can use a UNION ALL treating each column as a separate result. There may be more efficient ways to do this, but here is one way:
    Select S.Empid,       Pp.Startpp Startdate,       Null Starttime,       Null Endtime,       8 Hours,       0 Minutes
      From Schedules S       Join  Payperiods Pp On Pp.Periodid = S.Periodid
      Where Upper (Substr (S.Day1, 0, 4)) = 'FRLO'
    Union All 
    Select S.Empid,       Pp.Startpp+1 Startdate,       Null Starttime,       Null Endtime,       8 Hours,       0 Minutes
      From Schedules S       Join  Payperiods Pp On Pp.Periodid = S.Periodid
      Where Upper (Substr (S.Day2, 0, 4)) = 'FRLO'
    Union All 
    Select S.Empid,       Pp.Startpp+2 Startdate,       Null Starttime,       Null Endtime,       8 Hours,       0 Minutes
      From Schedules S       Join  Payperiods Pp On Pp.Periodid = S.Periodid
      Where Upper (Substr (S.Day3, 0, 4)) = 'FRLO'
    Union All 
    Select S.Empid,       Pp.Startpp+3 Startdate,       Null Starttime,       Null Endtime,       8 Hours,       0 Minutes
      From Schedules S       Join  Payperiods Pp On Pp.Periodid = S.Periodid
      Where Upper (Substr (S.Day4, 0, 4)) = 'FRLO'
    Union All 
    Select S.Empid,       Pp.Startpp+4 Startdate,       Null Starttime,       Null Endtime,       8 Hours,       0 Minutes
      From Schedules S       Join  Payperiods Pp On Pp.Periodid = S.Periodid
      Where Upper (Substr (S.Day5, 0, 4)) = 'FRLO'
    Union All 
    Select S.Empid,       Pp.Startpp+5 Startdate,       Null Starttime,       Null Endtime,       8 Hours,       0 Minutes
      From Schedules S       Join  Payperiods Pp On Pp.Periodid = S.Periodid
      Where Upper (Substr (S.Day6, 0, 4)) = 'FRLO'
    Union All 
    Select S.Empid,       Pp.Startpp+6 Startdate,       Null Starttime,       Null Endtime,       8 Hours,       0 Minutes
      From Schedules S       Join  Payperiods Pp On Pp.Periodid = S.Periodid
      Where Upper (Substr (S.Day7, 0, 4)) = 'FRLO'
    Union All 
    Select S.Empid,       Pp.Startpp+7 Startdate,       Null Starttime,       Null Endtime,       8 Hours,       0 Minutes
      From Schedules S       Join  Payperiods Pp On Pp.Periodid = S.Periodid
      Where Upper (Substr (S.Day8, 0, 4)) = 'FRLO'
    Union All 
    Select S.Empid,       Pp.Startpp+8 Startdate,       Null Starttime,       Null Endtime,       8 Hours,       0 Minutes
      From Schedules S       Join  Payperiods Pp On Pp.Periodid = S.Periodid
      Where Upper (Substr (S.Day9, 0, 4)) = 'FRLO'
    Union All 
    Select S.Empid,       Pp.Startpp+9 Startdate,       Null Starttime,       Null Endtime,       8 Hours,       0 Minutes
      From Schedules S       Join  Payperiods Pp On Pp.Periodid = S.Periodid
      Where Upper (Substr (S.Day10, 0, 4)) = 'FRLO'
    Union All 
    Select S.Empid,       Pp.Startpp+10 Startdate,       Null Starttime,       Null Endtime,       8 Hours,       0 Minutes
      From Schedules S       Join  Payperiods Pp On Pp.Periodid = S.Periodid
      Where Upper (Substr (S.Day11, 0, 4)) = 'FRLO'
    Union All 
    Select S.Empid,       Pp.Startpp+11 Startdate,       Null Starttime,       Null Endtime,       8 Hours,       0 Minutes
      From Schedules S       Join  Payperiods Pp On Pp.Periodid = S.Periodid
      Where Upper (Substr (S.Day12, 0, 4)) = 'FRLO'
    Union All 
    Select S.Empid,       Pp.Startpp+12 Startdate,       Null Starttime,       Null Endtime,       8 Hours,       0 Minutes
      From Schedules S       Join  Payperiods Pp On Pp.Periodid = S.Periodid
      Where Upper (Substr (S.Day13, 0, 4)) = 'FRLO'
    Union All 
    Select S.Empid,       Pp.Startpp+13 Startdate,       Null Starttime,       Null Endtime,       8 Hours,       0 Minutes
      From Schedules S       Join  Payperiods Pp On Pp.Periodid = S.Periodid
      Where Upper (Substr (S.Day14, 0, 4)) = 'FRLO'

Maybe you are looking for