Help with sql subquery/grouping

Hi... having trouble getting this query to work. Here's the table and data:
create table mytable (
rec_num number,
status_num number,
status_date date
insert into mytable values (1,1,'01-AUG-2006');
insert into mytable values (1,2,'14-AUG-2006');
insert into mytable values (1,8,'01-SEP-2006');
insert into mytable values (1,3,'15-SEP-2006');
insert into mytable values (1,2,'03-SEP-2006');
insert into mytable values (2,2,'17-AUG-2006');
insert into mytable values (3,2,'02-SEP-2006');
insert into mytable values (3,4,'07-SEP-2006');
insert into mytable values (4,1,'18-SEP-2006');
insert into mytable values (4,4,'27-SEP-2006');
insert into mytable values (4,2,'18-SEP-2006');
insert into mytable values (5,1,'01-OCT-2006');
insert into mytable values (5,2,'03-OCT-2006');
insert into mytable values (5,3,'05-OCT-2006');
insert into mytable values (6,1,'01-OCT-2006');
insert into mytable values (7,2,'14-OCT-2006');
insert into mytable values (7,8,'15-OCT-2006');
I'm trying to select the rec_num, status_num, and status_date for the max date for each individual rec_num... it basically tells me the current status of each individual record by getting the status for the most recent date... like the following:
rec_num, status_num, date
1, 3, 15-SEP-2006
2, 2, 17-AUG-2006
3, 4, 07-SEP-2006
etc
This query works... it gets me the max date for each record... but it doesn't give me the status_num:
select rec_num, max(status_date)
from mytable
group by rec_num
Adding status_num messes it up... I know I need some kindof sub-query, but haven't been able to get one to work.
I'd also like a query to get a count on how many records currently exist in each status.
Can someone help me out? Oracle 8i. Thanks!

SQL> select * from my_table;
   REC_NUM STATUS_NUM STATUS_DA
         1          1 01-AUG-06
         1          2 14-AUG-06
         1          8 01-SEP-06
         1          3 15-SEP-06
         1          2 03-SEP-06
         2          2 17-AUG-06
         3          2 02-SEP-06
         3          4 07-SEP-06
         4          1 18-SEP-06
         4          4 27-SEP-06
         4          2 18-SEP-06
         5          1 01-OCT-06
         5          2 03-OCT-06
         5          3 05-OCT-06
         6          1 01-OCT-06
         7          2 14-OCT-06
         7          8 15-OCT-06
SQL> select mt.rec_num,
  2         mt.status_num,
  3         mt.status_date
  4    from (select row_number() over (partition by rec_num order by status_date desc) rn,
  5                 rec_num,
  6                 status_num,
  7                 status_date
  8            from my_table) mt
  9   where mt.rn = 1;
   REC_NUM STATUS_NUM STATUS_DA
         1          3 15-SEP-06
         2          2 17-AUG-06
         3          4 07-SEP-06
         4          4 27-SEP-06
         5          3 05-OCT-06
         6          1 01-OCT-06
         7          8 15-OCT-06
7 rows selected.
SQL>

Similar Messages

  • Need help with SQL Query with Inline View + Group by

    Hello Gurus,
    I would really appreciate your time and effort regarding this query. I have the following data set.
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*20.00*-------------19
    1234567----------11223--------------7/5/2008-----------Adjustment for bad quality---------44345563------------------A-----------------10.00------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765--------------------I---------------------30.00-------------19
    Please Ignore '----', added it for clarity
    I am trying to write a query to aggregate paid_amount based on Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number and display description with Invoice_type 'I' when there are multiple records with the same Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number. When there are no multiple records I want to display the respective Description.
    The query should return the following data set
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*10.00*------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765-------------------I---------------------30.00--------------19
    The following is my query. I am kind of lost.
    select B.Description, A.sequence_id,A.check_date, A.check_number, A.invoice_number, A.amount, A.vendor_number
    from (
    select sequence_id,check_date, check_number, invoice_number, sum(paid_amount) amount, vendor_number
    from INVOICE
    group by sequence_id,check_date, check_number, invoice_number, vendor_number
    ) A, INVOICE B
    where A.sequence_id = B.sequence_id
    Thanks,
    Nick

    It looks like it is a duplicate thread - correct me if i'm wrong in this case ->
    Need help with SQL Query with Inline View + Group by
    Regards.
    Satyaki De.

  • Please help with SQL amount calulation

    -- Results
    with t as ( 
    select 'P11877' Mstr_Program,   1 Year_of_study, 'BUSI1490' program_module,  20 no_of_stud,    1 rank,   30 program_credits,  30 cumm_credits   from dual union all
    select 'P11877',                1,              'COMP1365',                 20,               2,        30,                  60               from dual union all
    select 'P11877',                1,              'BUSI1375',                 20,               3,        30,                  90               from dual union all
    select 'P11877',                1,              'COMP1363',                 20,               4,        30,                  120              from dual union all
    select 'P11877',                2,              'MARK1174',                 8,                1,        30,                  30               from dual union all
    select 'P11877',                2,              'FINA1068',                 8,                2,        15,                  45               from dual union all
    select 'P11877',                2,              'INDU1062',                 8,                3,        30,                  75               from dual union all
    select 'P11877',                2,              'BUSI1329',                 8,                4,        15,                  90               from dual union all
    select 'P11877',                2,              'MARK1138',                 8,                5,        30,                  120              from dual)
    select * from t;-- Each MSTR_PROGRAM can have 1 or many program_module
    -- MSTR_PROGRAM's can run for 1 or 2 years (case above is two years) so some modules run in year 1 and some in year 2
    -- NO_OF_STUD is the number of students on the module
    -- RANK basically ranks the modules by the number of students on them grouped by program and year
    -- e.g.row_number() OVER (PARTITION BY Mstr_Program, Year_of_study) ORDER BY COUNT(STUDENT_ID) DESC) rank
    -- PROGRAM_CREDITS: each module has a fixed number of credits
    -- CUMM_CREDITS: Increments the credit count of modules
    -- SUM(program_credits * 10) OVER (PARTITION BY Mstr_Program, Year_of_study
    -- ORDER BY count(STUDENT_ID) desc ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) cumm_credits
    -- I want to trim of any modules once the CUM_CREDITS hits 120. As seen above. I achieve this by wrapping the main query is another SELECT then LIMIT
    -- that WHERE cum_credit <=120.
    -- But what I need is:
    -- In some cases the the cumm_credit maybe on lets say 90credits then the next module is worth 40 credits. This next module will not show as it
    -- will be greater than 120 credits, so i need to pro-rata it:
    -- So if credit_count > 120, then the last module is counted pro-rata as follows: 1- ((credit count - 120) / credits from last module
    -- Can anyone help with how I can incorporate this into my current code: The SELECT portion of the Original SQL is below: I simplified column names
    -- e.t.c in the above so they wont be the same
    SELECT * FROM (
         SELECT
               ,SR_PROGRAM Mstr_Program
               ,DECODE (SORLCUR_YEAR, 1, 1,
                                      2, 2,
                                      3, 3,
                                      4, 3, SR_YEAR) year_of_study
               ,SCT_SUBJ_CODE||SCT_CRSE_NUMB program_module
               ,COUNT(student_ID)                    no_of_stud
               ,row_number() OVER (PARTITION BY sr_program,
                                            DECODE (sr_year, 1, 1,
                                                                  2, 2,
                                                                  3, 3,
                                                                  4, 3, SR_YEAR) ORDER BY COUNT(student_id) DESC, scbcrse_title asc) rank
               ,(SCT_CREDIT_HRS * 10) program_credits
               ,SUM(SCT_CREDIT_HRS * 10) OVER (PARTITION BY sr_program, DECODE (sorlcur_year, 1, 1,
                                                                                                       2, 2,
                                                                                                       3, 3,
                                                                                                       4, 3, SR_YEAR)
                                                    ORDER BY count(student_id) desc ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) cumm_credits
    WHERE cumm_credit <=120
    ORDER BY Mstr_Program, YEAR_OF_STUDY, RANK asc;

    Maybe
    SELECT Mstr_Program,year_of_study,program_module,no_of_stud,rank,program_credits old_program_credits,cumm_credits old_cumm_credits,
           case when cumm_credits > 120
                then program_credits - cumm_credits + 120
                else program_credits
           end new_program_credits,
           case when cumm_credits > 120
                then 120
                else cumm_credits
           end new_cumm_credits
      FROM (SELECT SR_PROGRAM Mstr_Program,
                   DECODE(SORLCUR_YEAR,1,1,2,2,3,3,4,3,SR_YEAR) year_of_study,
                   SCT_SUBJ_CODE||SCT_CRSE_NUMB program_module,
                   COUNT(student_ID) no_of_stud,
                   row_number() OVER (PARTITION BY sr_program,DECODE(sr_year,1,1,2,2,3,3,4,3,SR_YEAR)
                                          ORDER BY COUNT(student_id) DESC,scbcrse_title) rank,
                   10 * SCT_CREDIT_HRS program_credits,
                   10 * SUM(SCT_CREDIT_HRS) OVER (PARTITION BY sr_program,DECODE(sorlcur_year,1,1,2,2,3,3,4,3,SR_YEAR)
                                                      ORDER BY count(student_id) desc
                                                  ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) cumm_credits
    WHERE 0 <= case when cumm_credits > 120
                     then program_credits - cumm_credits + 120
                     else program_credits
                end
    ORDER BY Mstr_Program,YEAR_OF_STUDY,RANKRegards
    Etbin
    Edited by: Etbin on 16.12.2011 8:50
    with
    t as   /* simulating the result achieved */
    (select 'P11877' Mstr_Program,1 Year_of_study, 'BUSI1490' program_module,20 no_of_stud,1 rank,30 program_credits,30 cumm_credits from dual union all
    select 'P11877',             1,               'COMP1365',               20,           2,     40,                70              from dual union all
    select 'P11877',             1,               'BUSI1375',               20,           3,     30,                100             from dual union all
    select 'P11877',             1,               'COMP1363',               20,           4,     40,                140             from dual union all
    select 'P11877',             2,               'MARK1174',               8,            1,     30,                30              from dual union all
    select 'P11877',             2,               'FINA1068',               8,            2,     50,                80              from dual union all
    select 'P11877',             2,               'INDU1062',               8,            3,     30,                110             from dual union all
    select 'P11877',             2,               'BUSI1329',               8,            4,     50,                160             from dual union all
    select 'P11877',             2,               'MARK1138',               8,            5,     30,                190             from dual
    select Mstr_Program,Year_of_study,program_module,no_of_stud,rank,program_credits old_credits,cumm_credits old_cumm,
           case when cumm_credits > 120
                then program_credits - cumm_credits + 120
                else program_credits
           end new_program_credits,
           case when cumm_credits > 120
                then 120
                else cumm_credits
           end new_cumm_credits
      from t
    where 0 <= case when cumm_credits > 120
                     then program_credits - cumm_credits + 120
                     else program_credits
                end

  • Help with Keywording a group of Images

    I need help applying keywords to a group of selected images. For some reason I can't get this to work. I've done it before and now it won't work. Here is what I'm doing. I've selected a group of images in a project by using shift and clicking the first and last image I want and using comand to select images that are not next to each other. They all show up in the viewer and the thin white lines show up around the images in the browser. Now I go and add a keyword. It doesn't seem to matter if I use the Keyword control bar buttons or if I type in a key word in the bar in the lower right hand side, the same thing happens. The keyword is only being applied to the primary selection and not the whole group. Why isn't this working? I'm sure I'm missing something simple, but it's starting to drive me crazy. Any help with this would be great thanks.
    -Matthew

    You have switched 'toggle primary only' on. To turn it off click on the button with a square in it at the bottom of the screen or press 's'

  • Where to find help with SQL Developer installation?

    Hi,
    I just want to try out SQL Developer and compare its capabilities to TOAD's. Unfortunately, I am not PC software savvy and now am stuck with a SQL Developer (sqldeveloper-1.2.2998) installation problem. When I clicked on the .exe file, I got a blank SQL Developer screen - there is nothing in the screen except a heading that reads 'Oracle SQL Developer'...
    Does anyone know of a blog or a site that I can get some help with problems like mine?
    Any help is much appreciated!

    Hi,
    SQL Developer forum link:
    "http://forums.oracle.com/forums/forum.jspa?forumID=260"
    There are 2 versions of SQL Developer, with/without JRE.
    Try out the full install version with JRE.
    HTH
    Zack

  • Need help with SQL*Loader not working

    Hi all,
    I am trying to run SQL*Loader on Oracle 10g UNIX platform (Red Hat Linux) with below command:
    sqlldr userid='ldm/password' control=issue.ctl bad=issue.bad discard=issue.txt direct=true log=issue.log
    And get below errors:
    SQL*Loader-128: unable to begin a session
    ORA-01034: ORACLE not available
    ORA-27101: shared memory realm does not exist
    Linux-x86_64 Error: 2: No such file or directory
    Can anyone help me out with this problem that I am having with SQL*Loader? Thanks!
    Ben Prusinski

    Hi Frank,
    More progress, I exported the ORACLE_SID and tried again but now have new errors! We are trying to load an Excel CSV file into a new table on our Oracle 10g database. I created the new table in Oracle and loaded with SQL*Loader with below problems.
    $ export ORACLE_SID=PROD
    $ sqlldr 'ldm/password@PROD' control=prod.ctl log=issue.log bad=bad.log discard=discard.log
    SQL*Loader: Release 10.2.0.1.0 - Production on Tue May 23 11:04:28 2006
    Copyright (c) 1982, 2005, Oracle. All rights reserved.
    SQL*Loader: Release 10.2.0.1.0 - Production on Tue May 23 11:04:28 2006
    Copyright (c) 1982, 2005, Oracle. All rights reserved.
    Control File: prod.ctl
    Data File: prod.csv
    Bad File: bad.log
    Discard File: discard.log
    (Allow all discards)
    Number to load: ALL
    Number to skip: 0
    Errors allowed: 50
    Bind array: 64 rows, maximum of 256000 bytes
    Continuation: none specified
    Path used: Conventional
    Table TESTLD, loaded from every logical record.
    Insert option in effect for this table: REPLACE
    Column Name Position Len Term Encl Datatype
    ISSUE_KEY FIRST * , CHARACTER
    TIME_DIM_KEY NEXT * , CHARACTER
    PRODUCT_CATEGORY_KEY NEXT * , CHARACTER
    PRODUCT_KEY NEXT * , CHARACTER
    SALES_CHANNEL_DIM_KEY NEXT * , CHARACTER
    TIME_OF_DAY_DIM_KEY NEXT * , CHARACTER
    ACCOUNT_DIM_KEY NEXT * , CHARACTER
    ESN_KEY NEXT * , CHARACTER
    DISCOUNT_DIM_KEY NEXT * , CHARACTER
    INVOICE_NUMBER NEXT * , CHARACTER
    ISSUE_QTY NEXT * , CHARACTER
    GROSS_PRICE NEXT * , CHARACTER
    DISCOUNT_AMT NEXT * , CHARACTER
    NET_PRICE NEXT * , CHARACTER
    COST NEXT * , CHARACTER
    SALES_GEOGRAPHY_DIM_KEY NEXT * , CHARACTER
    value used for ROWS parameter changed from 64 to 62
    Record 1: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 2: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 3: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 4: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 5: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 6: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 7: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 8: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 9: Rejected - Error on table ISSUE_FACT_TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 10: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 11: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 12: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 13: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 14: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 15: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 16: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 17: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 18: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 19: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 20: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 21: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 22: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 23: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 24: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 39: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    MAXIMUM ERROR COUNT EXCEEDED - Above statistics reflect partial run.
    Table TESTLD:
    0 Rows successfully loaded.
    51 Rows not loaded due to data errors.
    0 Rows not loaded because all WHEN clauses were failed.
    0 Rows not loaded because all fields were null.
    Space allocated for bind array: 255936 bytes(62 rows)
    Read buffer bytes: 1048576
    Total logical records skipped: 0
    Total logical records read: 51
    Total logical records rejected: 51
    Total logical records discarded: 0
    Run began on Tue May 23 11:04:28 2006
    Run ended on Tue May 23 11:04:28 2006
    Elapsed time was: 00:00:00.14
    CPU time was: 00:00:00.01
    [oracle@casanbdb11 sql_loader]$
    Here is the control file:
    LOAD DATA
    INFILE issue_fact.csv
    REPLACE
    INTO TABLE TESTLD
    FIELDS TERMINATED BY ','
    ISSUE_KEY,
    TIME_DIM_KEY,
    PRODUCT_CATEGORY_KEY,
    PRODUCT_KEY,
    SALES_CHANNEL_DIM_KEY,
    TIME_OF_DAY_DIM_KEY,
    ACCOUNT_DIM_KEY,
    ESN_KEY,
    DISCOUNT_DIM_KEY,
    INVOICE_NUMBER,
    ISSUE_QTY,
    GROSS_PRICE,
    DISCOUNT_AMT,
    NET_PRICE,
    COST,
    SALES_GEOGRAPHY_DIM_KEY
    )

  • Help with record selection/grouping

    I am trying to create a report as follows, but am running into some problems with my selection/grouping:
    Data Structure (each line is a separate record; each employee has 2 records)
    Employee             TaskID      TaskStatus           Marker         Date Modified
    1                               A                CLOSED             x
    1                               B                OPEN                  N/A
    2                               A                CLOSED              y
    2                               B                OPEN                 N/A
    3                               A                CLOSED             x
    3                               B                CLOSED            N/A
    4                               A                CLOSED             y
    4                               B                CLOSED           N/A
    Report Requirements
    I want a report that displays only employee number and the date that Task B was completed for all employees, and I want these records grouped based on Task B's Task Status (no problem.  I did this).
    However, I want to sub-group these Task B records (within Task Status) by the Marker field for Task A records!  (I can't figure this out?  If I only pull in Task B records, how can I compare what the associated employee has as a marker for their Task A record?)
    Again, I only want to display data from the employee's Task B record, while subgrouping on a field value from the empoyee's Task A record.  The report would be structured as follows:
    Task B (OPEN), with Task A - Marker (x)
                     {Date Modified}
    Task B (OPEN), with Task A - Marker (y)
                     {Date Modified}
    Task B (CLOSED), with Task A - Marker (x)
                    {Date Modified}
    Task B (CLOSED), with Task A - Marker (y)
                      {Date Modified}
    Thanks.
    Gary

    The easiest way would be to use an SQL Command that returns both the Task A and Task B data on one record.  Something like (MS SQL):
    select b.employee, b.taskid as task_b, b.task_status_b, b.marker as marker_b, b.date_modified as date_modified_b,
        a.taskid as task_a, a.task_status_a, a.marker as marker_a, a.date_modified as date_modified_a
    from table a, table b
    where a.employee = b.employee
    and a.taskid = 'A'
    and b.taskid = 'B'
    HTH,
    Carl

  • I need help with SQL query

    Hi All,
    I have a problem in the query below. When I run the query I got a pop-up screen to ente value for
    :total_balance,
    :emp_code,
    :from_date,
    :to_date
    total_balance supose to be a result of a calculation.
    Your assistance is apreciated. Thanks,
    Ribhi
    select      FK_VOUCHERSERIAL_N,
         FK_VOUCHERVALUE_DA,
         DESCRIPTION,
         nvl(AMOUNT,0) amount,
         TYPE,
         Accnt101.postive_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) postive_amount,
         Accnt101.negative_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) negative_amount,
         Accnt101.total_balanceformula(:total_balance, EMPLOYEE_TRANSACTI.TYPE,Accnt101.negative_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) ,Accnt101.postive_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) , nvl(AMOUNT,0)) total_balance
    from      EMPLOYEE_TRANSACTI
    where     FK_EMPLOYEENUMBER0=:emp_code
    and     STATUS=1
    and     FK_VOUCHERVALUE_DA<=:to_date
    and     FK_VOUCHERVALUE_DA>=:from_date
    and     ((TYPE >7 and TYPE <16)
         or (TYPE >34 and TYPE <43)
         or (TYPE =7)
         or (TYPE =18)
         or (TYPE >26 and TYPE <35)
         or (TYPE =17)
         OR (TYPE = 60)
         OR (TYPE = 70)
    OR (TYPE = 72)
    OR (TYPE = 73)
    OR (TYPE = 74)
         or (type = 21)
         or (type =24)
         or (type = 81)
         or (type = 82))
    order by      FK_VOUCHERVALUE_DA asc, FK_VOUCHERSERIAL_N asc, type desc

    Hi Satyaki,
    My problem is with SQL and PL/SQL codd. I managed to convert some of my reports and now I'm facing a problem with converted SQL and PL/SQL code. To give you an Idea the following is a sample of a converted report.
    Pls have a look. (p.s how can i post formated text)
    Thanks,
    Ribhi
    1 - XML template file
    <?xml version="1.0" encoding="UTF-8" ?>
    - <dataTemplate name="Accnt101" defaultPackage="Accnt101" version="1.0">
    - <properties>
    <property name="xml_tag_case" value="upper" />
    </properties>
    - <parameters>
    <parameter name="FROM_DATE" dataType="date" defaultValue="01/01/1998" />
    <parameter name="TO_DATE" dataType="date" defaultValue="31/12/1998" />
    <parameter name="EMP_CODE" dataType="number" defaultValue="44" />
    </parameters>
    <lexicals />
    - <dataQuery>
    - <sqlStatement name="employee_trans">
    - <![CDATA[
    select      FK_VOUCHERSERIAL_N,
         FK_VOUCHERVALUE_DA,
         DESCRIPTION,
         nvl(AMOUNT,0) amount,
         TYPE,
         Accnt101.postive_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) postive_amount,
         Accnt101.negative_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) negative_amount,
         Accnt101.total_balanceformula(:total_balance, EMPLOYEE_TRANSACTI.TYPE,Accnt101.negative_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) ,Accnt101.postive_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) , nvl(AMOUNT,0)) total_balance
    from      EMPLOYEE_TRANSACTI
    where     FK_EMPLOYEENUMBER0=:emp_code
    and     STATUS=1
    and     FK_VOUCHERVALUE_DA<=:to_date
    and     FK_VOUCHERVALUE_DA>=:from_date
    and     ((TYPE >7 and TYPE <16)
         or (TYPE >34 and TYPE <43)
         or (TYPE =7)
         or (TYPE =18)
         or (TYPE >26 and TYPE <35)
         or (TYPE =17)
         OR (TYPE = 60)
         OR (TYPE = 70)
                    OR (TYPE = 72)
                    OR (TYPE = 73)
                    OR (TYPE = 74)
         or (type = 21)
         or (type =24)
         or (type = 81)
         or (type = 82))
    order by      FK_VOUCHERVALUE_DA asc, FK_VOUCHERSERIAL_N asc, type desc
      ]]>
    </sqlStatement>
    - <sqlStatement name="employee">
    - <![CDATA[
    select NAME,NUMBER0
    from EMPLOYEE
    where  NUMBER0=:emp_code
      ]]>
    </sqlStatement>
    </dataQuery>
    <dataTrigger name="beforeReportTrigger" source="Accnt101.beforereport" />
    - <dataStructure>
    - <group name="G_employee_trans" dataType="varchar2" source="employee_trans">
    <element name="FK_VOUCHERSERIAL_N" dataType="number" value="FK_VOUCHERSERIAL_N" />
    <element name="FK_VOUCHERVALUE_DA" dataType="date" value="FK_VOUCHERVALUE_DA" />
    <element name="DESCRIPTION" dataType="varchar2" value="DESCRIPTION" />
    <element name="AMOUNT" dataType="number" value="AMOUNT" />
    <element name="postive_amount" dataType="number" value="postive_amount" />
    <element name="negative_amount" dataType="number" value="negative_amount" />
    <element name="total_balance" dataType="number" value="total_balance" />
    <element name="TYPE" dataType="number" value="TYPE" />
    <element name="CS_1" function="sum" dataType="number" value="G_employee_trans.total_balance" />
    </group>
    - <group name="G_employee" dataType="varchar2" source="employee">
    <element name="NUMBER0" dataType="number" value="NUMBER0" />
    <element name="NAME" dataType="varchar2" value="NAME" />
    </group>
    <element name="balance" dataType="number" value="Accnt101.balance_p" />
    <element name="CS_2" function="count" dataType="number" value="G_employee.NUMBER0" />
    <element name="CS_3" function="count" dataType="number" value="G_employee_trans.AMOUNT" />
    </dataStructure>
    </dataTemplate>
    2 - PLS/SQL package
    CREATE OR REPLACE PACKAGE Accnt101 AS
         from_date     date;
         to_date     date;
         emp_code     number;
         balance     number := 0 ;
         function postive_amountformula(TYPE in number, amount in number) return number ;
         function negative_amountformula(TYPE in number, amount in number) return number ;
         function BeforeReport return boolean ;
         function total_balanceformula(total_balance in number, TYPE in number, negative_amount in number, postive_amount in number, amount in number) return number ;
         Function balance_p return number;
    END Accnt101;
    3- Package Body
    CREATE OR REPLACE PACKAGE BODY Accnt101 AS
    function postive_amountformula(TYPE in number, amount in number) return number is
    begin
         if ((TYPE>26 and TYPE<35)
              or (TYPE=17))
         then
              return(amount);
         elsif (type = 70)and (amount >=0) then
              return (amount) ;
    elsif (type = 72)and (amount >=0) then
              return (amount) ;
    elsif (type = 73)and (amount >=0) then
              return (amount) ;
    elsif (type = 74)and (amount >=0) then
              return (amount) ;
         elsif (type = 60)and (amount >=0) then
              return (amount) ;
         else
              return (null) ;
         end if;
    RETURN NULL; end;
    function negative_amountformula(TYPE in number, amount in number) return number is
    begin
         if ((TYPE>7 and TYPE<16)
              or (TYPE >34 and TYPE <43)
              or (TYPE=7)
              or (TYPE=18)
              or (type=21)
              or (type=24)
              or (type= 81)
              or (type=82))
         then
              return(amount);
         elsif (type = 70)and (amount <0) then
              return (abs (amount)) ;
    elsif (type = 72)and (amount <0) then
              return (abs (amount)) ;
    elsif (type = 73)and (amount <0) then
              return (abs (amount)) ;
    elsif (type = 74)and (amount <0) then
              return (abs (amount)) ;
         elsif (type = 60)and (amount <0) then
              return (abs(amount)) ;
         else
              return (null) ;
         end if;
    RETURN NULL; end;
    function BeforeReport return boolean is
    var_pos     number(15,3) ;
    var_neg     number(15,3) ;
    beg_bal     number(15,3) ;
    Begin
    begin
    select sum (nvl(amount,0)) into beg_bal
         from EMPLOYEE_TRANSACTI
         where (TYPE=99 or type = 92 or type = 93 or type = 94)
         and to_char(from_date,'YYYY')=to_char(date0,'YYYY')
         and FK_EMPLOYEENUMBER0=emp_code;
    EXCEPTION
         WHEN NO_DATA_FOUND THEN
         beg_bal := 0;
    end;
    begin
         select      sum(nvl(amount,0)) into var_pos
         from      EMPLOYEE_TRANSACTI
         where      
              (TYPE=17
              or type=60
              OR TYPE=70
    oR TYPE=72
    OR TYPE=73
    OR TYPE=74
              or (TYPE>26 and TYPE<35))
         and      fk_vouchervalue_da<from_date
         and      fk_vouchervalue_da>= trunc(from_date,'year')
         and      FK_EMPLOYEENUMBER0=emp_code;
    EXCEPTION
         WHEN NO_DATA_FOUND THEN
         var_pos := 0;
    end;
    Begin     
         select sum(nvl(amount,0)) into var_neg
         from EMPLOYEE_TRANSACTI
         where ((TYPE>7 and TYPE<16)
              or (TYPE >34 and TYPE <43)
              or (TYPE=7)
              or (TYPE=18)
              or (type=21)
              or (type=24)
              or (type= 81)
              or (type=82) )
         and fk_vouchervalue_da<from_date
         and fk_vouchervalue_da>= trunc(from_date,'year')
         and FK_EMPLOYEENUMBER0=emp_code;
         balance :=nvl(beg_bal,0) + nvl(var_pos,0) - nvl(var_neg,0);
         return(true);
    EXCEPTION
         WHEN NO_DATA_FOUND THEN
         balance :=nvl(beg_bal,0) + nvl(var_pos,0) - nvl(var_neg,0);
              RETURN (TRUE);
    end;
    RETURN NULL; end;
    function total_balanceformula(total_balance in number, TYPE in number, negative_amount in number, postive_amount in number, amount in number) return number is
    begin
         if total_balance is null then
         if ((TYPE>7 and TYPE<16)
              or (TYPE >34 and TYPE <43)
              or (TYPE=7)or (TYPE=18)
              or (type=21) or (type=24)
              or (type= 81)
              or (type=82))
         then
              return(balance-negative_amount);
         elsif ((TYPE>26 and TYPE<35) or (TYPE=17))
              then
                   return(balance+postive_amount);
              elsif (type=70 or type=72 or type=73 or type=74
    or type=60) and (amount >=0) then
                   return(balance+postive_amount);
              elsif (type=70 or type=72 or type=73 or type=74
    or type=60) and (amount <0) then
                   return(balance-negative_amount);
         end if;
         else
         if ((TYPE>7 and TYPE<16)
              or (TYPE >34 and TYPE <43)
              or (TYPE=7)or (TYPE=18)
              or (type=21) or (type=24)
              or (type= 81)
              or (type=82))
         then
              return(total_balance-negative_amount);
         elsif ((TYPE>26 and TYPE<35) or (TYPE=17))
              then
                   return(total_balance+postive_amount);
              elsif (type=70 or type=72 or type=73 or type=74
    or type=60) and (amount >=0) then
                   return(total_balance+postive_amount);
              elsif (type=70 or type=72 or type=73 or type=74
    or type=60) and (amount <0) then
                   return(total_balance-negative_amount);
         end if;
         end if ;
    RETURN NULL; end;
    Functions to refer Oracle report placeholders
    Function balance_p return number is
         Begin
         return balance;
         END;
    END Accnt101 ;

  • Where clause "where 1=1" help with SQL tuning

    Hello Tuning experts,
    Is it helpful to use "where 1=1" and then put all the joins and conditions in the "AND" statements of the SQL when writing SQL queries. I would like to know if it helps with query performance to write SQL queirs that way.
    Thanks in advance.
    Edited by: oracle_developer on Oct 8, 2012 10:41 AM

    You can see here that "where 1 = 1" is gone from the predicate info in the explain plan.
    The optimizer simply discarded it.
    SQL> explain plan for
      2  select *
      3  from emp
      4  where 1 = 1
      5  and job = 'SALESMAN';
    Explained.
    PLAN_TABLE_OUTPUT
    Plan hash value: 3956160932
    | Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |      |     3 |   114 |     3   (0)| 00:00:01 |
    |*  1 |  TABLE ACCESS FULL| EMP  |     3 |   114 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - filter("JOB"='SALESMAN')
    13 rows selected.

  • Help with SQL Server 2005 http Endpoint

    I am trying to use mx:webservice to directly connect to a SQL
    Server 2005 HTTP Endpoint. Is this possible. Is there going to be a
    problem with crossdomain issues? If the Endpoint is actively
    listening on port 80 then IIS cannot. So I cannot place
    crossdomain.xml in webserver, how will I overcome this crossdomain
    problem? Am I making this more complicated than it is? If anyone
    has an example it would be appreciated. All I want is a flex2 app
    talking directly to sql server. Seems possible.

    Kent, I see that many others have reported that error (doing
    a google search), but I see no ready answers. I saw something that
    reminded me of a connection string value that I've seen answer some
    problems. May be worth a shot for you: try adding this string to
    the connection string (in "advanced options") for your datasource:
    AuthenticationMethod=Type2
    If it doesn't solve it, remove it. But keep it handy in case
    it ever may help with some other problem.
    Here's one other possible answer for you:
    http://www.webmasterkb.com/Uwe/Forum.aspx/coldfusion-server/3206/SQL-Server-2000-Windows-A uth
    Sorry I can't be more clear for you.

  • Need Help With SQL GROUP BY and DISTINCT

    I am working on a project and need to display the total of each order based on the order id. For instance I want to display the order id, customer id, order date, and then the extension price (ol_quantity * inv_price).
    I would then like a total displayed for order # 1 and then move on to order #2.
    Here is my SQL code :
    SELECT DISTINCT orders.o_id, customer.c_id, inv_price * ol_quantity
    FROM orders, customer, inventory, order_line
    GROUP BY orders.o_id, customer.c_id, inv_price, ol_quantity
    ORDER BY orders.o_id;
    When my code is run it displays the order id, customer id and inv_price * quantity (extension price) but no order total for the order number and a new group is not started when a new order number is started....they are all clumped together.
    Any help is greatly appreciated!!

    Hi,
    user12036843 wrote:
    I am working on a project and need to display the total of each order based on the order id. For instance I want to display the order id, customer id, order date, and then the extension price (ol_quantity * inv_price).
    I would then like a total displayed for order # 1 and then move on to order #2.
    Here is my SQL code :
    SELECT DISTINCT orders.o_id, customer.c_id, inv_price * ol_quantity
    FROM orders, customer, inventory, order_line
    GROUP BY orders.o_id, customer.c_id, inv_price, ol_quantity
    ORDER BY orders.o_id;
    When my code is run it displays the order id, customer id and inv_price * quantity (extension price) but no order total for the order number and a new group is not started when a new order number is started....they are all clumped together.
    Any help is greatly appreciated!!Sorry, it's unclear what you want.
    Whenever you post a question, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say what version of Oracle you're using.
    Do you want the output to contain one row for each row in the table, plus an extra row for each distinct order, showing something about the order as a whole (e.g., total inv_price or average extension_price)? If so, you need GROUP BY ROLLUP or GROUP BY GROUPING SETS .
    If you want one row of output for each row of the table, but you want to include something that reflects the group as a whole (again, e.g, total inv_prive or average extension_pcie), then you can us analytic functions. (Most of the aggregate functions, such as SUM and AVG have analytic counterparts that can get the same results without collapsing the result set down to one row per group.)
    Here's an example of how to use GROUP BY GROUPING SETS.
    Way we're interested in employees' salary and commission from the scott.emp table:
    SELECT       deptno
    ,       ename
    ,       sal
    ,       comm
    FROM       scott.emp
    ORDER BY  deptno
    ,            ename
    ;Output:
    `   DEPTNO ENAME             SAL       COMM
            10 CLARK            2450
            10 KING             5000
            10 MILLER           1300
            20 ADAMS            1100
            20 FORD             3000
            20 JONES            2975
            20 SCOTT            3000
            20 SMITH             800
            30 ALLEN            1600        300
            30 BLAKE            2850
            30 JAMES             950
            30 MARTIN           1250       1400
            30 TURNER           1500          0
            30 WARD             1250        500Now say we want to add the total income (sal + comm, or just sal if there is no comm) to each row, and also to add a row for each department showing the total sal, comm and income in that department, like this:
    `   DEPTNO ENAME             SAL       COMM     INCOME
            10 CLARK            2450                  2450
            10 KING             5000                  5000
            10 MILLER           1300                  1300
            10                  8750                  8750
            20 ADAMS            1100                  1100
            20 FORD             3000                  3000
            20 JONES            2975                  2975
            20 SCOTT            3000                  3000
            20 SMITH             800                   800
            20                 10875                 10875
            30 ALLEN            1600        300       1900
            30 BLAKE            2850                  2850
            30 JAMES             950                   950
            30 MARTIN           1250       1400       2650
            30 TURNER           1500          0       1500
            30 WARD             1250        500       1750
            30                  9400       2200      11600(This relies on the fact that ename is unique.) Getting those results is pretty easy, using GROUPING SETS:
    SELECT       deptno
    ,       ename
    ,       SUM (sal)          AS sal
    ,       SUM (comm)          AS comm
    ,       SUM ( sal
               + NVL (comm, 0)
               )               AS income
    FROM       scott.emp
    GROUP BY  GROUPING SETS ( (deptno)
                             , (deptno, ename)
    ORDER BY  deptno
    ,            ename
    ;Notice that we're displaying SUM (sal) on each row. Most of the rows in the output are "groups" consisting of only one row from the table, so the SUM (sa) for that goup will be the sal for the one row in the group.
    Edited by: Frank Kulash on Nov 23, 2011 2:03 PM
    Added GROUPING SET example

  • Help Required With SQL Subquery Across DB Link - Takes Long Time

    Hi,
    Apologies if this is not the correct forum but I am implementing this through HTMLDB.
    I am trying to run a SQL query over a DB link with a sub query on tables in my HTMLDB workspace.
    The SQL query over the database link takes 1.23 seconds to run on it's own:
    SELECT D.EMAIL_ADDRESS,
    D.COL2,
    D.COL3,
    D.COL4,
    D.COL5,
    D.COL6,
    T.COL1
    FROM SCHEMA.TABLE1@DATABASELINK D,
    SCHEMA.TABLE2@DATABASELINK T
    WHERE D.TABLE_JOIN = T.TABLE_JOIN
    AND T.COL1 = '1111111'
    AND UPPER(D.COL2) IN ('XXXXXX','YYYYYY')
    The SQL query based on HTMLDB workspace tables takes 0.01 seconds to run on it's own:
    SELECT UPPER(A.EMAIL_ADDRESS)
    FROM HTMLDBTABLE1 M, HTMLDBTABLE2 A
    WHERE M.TABLE_JOIN = A.TABLE_JOIN
    AND M.ID = 222
    However when I try and run these together the results take 280 seconds to complete:
    SELECT D.EMAIL_ADDRESS,
    D.COL2,
    D.COL3,
    D.COL4,
    D.COL5,
    D.COL6,
    T.COL1
    FROM SCHEMA.TABLE1@DATABASELINK D,
    SCHEMA.TABLE2@DATABASELINK T
    WHERE D.TABLE_JOIN = T.TABLE_JOIN
    AND T.COL1 = '1111111'
    AND UPPER(D.COL2) IN ('XXXXXX','YYYYYY')
    AND NOT EXISTS
    (SELECT UPPER(A.EMAIL_ADDRESS)
    FROM HTMLDBTABLE1 M, HTMLDBTABLE2 A
    WHERE M.TABLE_JOIN = A.TABLE_JOIN
    AND UPPER(A.EMAIL_ADDRESS) = UPPER(D.EMAIL_ADDRESS)
    AND M.ID = 222)
    Does anyone have any idea why this query is taking so long?
    Please let me know if you require additional information.
    Many thanks,
    Richard.

    I've updated my profile to show my email address, so go ahead and email me the strace output (compressed please). Maximum attachment size for emails to Oracle is 10MB (encoded), so split the strace output in 5MB chunks if necessary.
    poll() is not normally used by the Oracle network layer for client-server connections. So this may be related to an OS network service, such as DNS or NIS. The strace should make this clear (to me anyway).
    Edited by: herb on Aug 14, 2009 10:25 AM

  • Immediate help with regards to grouping and decoding

    Hi all
    I have got a problem recently where I was asked whether this can be done using a single SQL statement.
    The table data is from a flat file like this.
    SITE TOOL PROD TOOLPROD
    ABC DEN_01 15 DEN_01
    ABC DEN_01 15 DEN_01|01
    ABC DEN_01 15 DEN_01|02
    ABC DEN_01 15 DEN_01|03
    DEF DE_03 17 DE_03
    DEF DE_03 17 DE_03|07
    DEF DE_03 17 DE_03|08
    and the sumarized result set should look like this from above info i.e grouped by site,tool,prod columns and the last columns toolprod concatenated as shown below. There is lot of data like this and hardcoding cannot be done since there are millions of rows like this.
    ABC DEN_01 15 DEN_01|DEN_01|01|DEN_01|02|DEN_01|03
    DEF DE_03 17 DE_03|DE_03|07|DE_03|08
    Appreciate your help
    Thanx in advance
    Kris

    Sys_connect_by_path is a 9i feature that provides the path from the root to the node in a hierarchical query. For an 8i workaround you can use the folloing hiearchy package by Solomon Yakobson. I know the package works in 8i, because that is what it was designed for and I used it in 8i, but I do not know if it will work in conjunction with the rest of the code, as I do not have 8i to test with anymore, and there were some restrictions as to what you could do with hierarchical queries in 8i. You may have to add some additional nesting of inline views or some such thing.
    scott@ORA92> -- hierarchy package with branch function by Solomon Yacobson
    scott@ORA92> CREATE OR REPLACE
      2   PACKAGE Hierarchy
      3    IS
      4            TYPE BranchTableType IS TABLE OF VARCHAR2(4000)
      5              INDEX BY BINARY_INTEGER;
      6            BranchTable BranchTableType;
      7            FUNCTION Branch(vLevel          IN NUMBER,
      8                      vValue          IN VARCHAR2,
      9                      vDelimiter      IN VARCHAR2 DEFAULT CHR(0))
    10                      RETURN VARCHAR2;
    11            PRAGMA RESTRICT_REFERENCES(Branch,WNDS);
    12  END Hierarchy;
    13  /
    Package created.
    scott@ORA92> CREATE OR REPLACE
      2   PACKAGE BODY Hierarchy
      3    IS
      4            ReturnValue VARCHAR2(4000);
      5    FUNCTION Branch(vLevel          IN NUMBER,
      6                   vValue          IN VARCHAR2,
      7                   vDelimiter    IN VARCHAR2 DEFAULT CHR(0))
      8                   RETURN VARCHAR2
      9       IS
    10       BEGIN
    11            BranchTable(vLevel) := vValue;
    12            ReturnValue := vValue;
    13            FOR I IN REVERSE 1..vLevel - 1 LOOP
    14              ReturnValue := BranchTable(I)|| vDelimiter || ReturnValue;
    15            END LOOP;
    16            RETURN ReturnValue;
    17    END Branch;
    18  END Hierarchy;
    19  /
    Package body created.
    scott@ORA92> select site, tool, prod,
      2           replace (max (hierarchy.branch (level, toolprod)), ',', '|')
      3             as toolprods
      4  from   (select site, tool, prod, toolprod,
      5                row_number () over
      6                  (partition by site, tool, prod
      7                   order by toolprod) as curr,
      8                row_number () over
      9                  (partition by site, tool, prod
    10                   order by toolprod) - 1 as prev
    11            from   your_table)
    12  group  by site, tool, prod
    13  start  with curr = 1
    14  connect by prior curr = prev
    15            and prior site = site
    16            and prior tool = tool
    17            and prior prod = prod
    18  /
    SITE TOOL         PROD TOOLPRODS
    ABC  DEN_01         15 DEN_01 DEN_01|01 DEN_01|02 DEN_01|03
    DEF  DE_03          17 DEN_03 DEN_03|07 DEN_03|08The second solution that I provided, using Tom Kyte's stragg user-defined aggregate function also requires 9i. The third solution with a function specific to the situation should work in 8i though. The following is an addiitional generic option for 8i.
    scott@ORA92> CREATE OR REPLACE FUNCTION concatenate
      2    (p_key_name      IN VARCHAR2,
      3       p_key_value      IN VARCHAR2,
      4       p_col_to_concat  IN VARCHAR2,
      5       p_table_name      IN VARCHAR2,
      6       p_separator      IN VARCHAR2 DEFAULT '|')
      7    RETURN              VARCHAR2
      8  AS
      9    TYPE weak_ref_cur IS REF CURSOR;
    10    v_string          VARCHAR2 (4000);
    11    v_separator         VARCHAR2 (      3) := NULL;
    12    v_value              VARCHAR2 (4000);
    13    v_cur              weak_ref_cur;
    14  BEGIN
    15    OPEN v_cur FOR
    16          'SELECT ' || p_col_to_concat
    17    || ' FROM '   || p_table_name
    18    || ' WHERE '  || p_key_name || ' = :b_key_name'
    19    || ' ORDER BY :b_col_to_concat'
    20    USING p_key_value, p_col_to_concat;
    21    LOOP
    22        FETCH v_cur INTO v_value;
    23        EXIT WHEN v_cur%NOTFOUND;
    24          v_string := v_string || v_separator || v_value;
    25          v_separator := p_separator;
    26    END LOOP;
    27    CLOSE v_cur;
    28    RETURN v_string;
    29  END concatenate;
    30  /
    Function created.
    scott@ORA92> select site, tool, prod,
      2           concatenate ('site || tool || prod',
      3                  site || tool || prod,
      4                  'toolprod', 'your_table') toolprods
      5  from  your_table
      6  group by site, tool, prod
      7  /
    SITE TOOL         PROD TOOLPRODS
    ABC  DEN_01         15 DEN_01|DEN_01|01|DEN_01|02|DEN_01|03
    DEF  DE_03          17 DEN_03|DEN_03|07|DEN_03|08
    scott@ORA92>

  • Can Someone help with SQL for update ?

    Hi,
    can someone help me with this code
    2 tables.
    table 1 = User_master
    table 2 = update_users
    I need to update user_master like so...
    update user_master
    set status = 'I'
    where user_id IN ()
    problem is I have to over 10k user_id to update.
    So created new table called update_users and imported all user_id's into that table.
    How can I read all user_id's from that table, then update user_master status column for all
    users id's found in update_users ?
    I already tried this...
    update p.user_id from user_master p
    set status = 'I'
    where user_id = (select user_id from update_users where p.user_id=user_id)
    It did not work -
    ERROR at line 2:
    ORA-01427: single-row subquery returns more than one row
    Thanks,

    There are no duplicates. Each user_id is unique.Are you sure? the error message indicates otherwise. You might see if the following query returns any rows;
    select user_id, count(*)
    from update_users
    group by user_id
    having count(*) > 1;Also, you might want to post the exact statement that you used to generate the error. The statement that you posted raises an error de to the syntax;
    update p.user_id from user_master p
    set status = 'I'
    where user_id = (select user_id
                     from update_users
                     where p.user_id = user_id)
    ORA-00971: missing SET keywordPerhaps you ran something like;
    select * from user_master;
       USER_ID STATUS
             1 A
             2 A
             3 A
    select * from update_users;
       USER_ID
             1
             2
    update user_master p
    set status = 'I'
    where user_id = (select user_id
                     from update_users
                     where p.user_id = user_id);
    2 rows updated
    select * from user_master;
       USER_ID STATUS
             1 I
             2 I
             3 A

  • Help with SQL code

    Hi having a slight problem with some SQL code -
    We store a number of actions they get given a date_done, a Y if we Met_Customer, a Y if we had an Upsell_Apps , a Y if we Upsell_Other, a Y if there was a reference and a Y if there was an issue. The action must have a date, but can have none to any of the Y's
    We want SQL to report back the number of actions (so the count) broken down into the months of the date_done - so Aug 07, Sep 07 etc etc. And this again broken down for Met_customer, Upsell_apps, upsell_other, reference and issue.
    We want it to look something like this...
    Action Type-------------------- Oct06 | Nov06 | Dec06 | Jan07
    Met Customer--------------------12--------8-----------4----------2
    Upsell App-------------------------21--------0-----------1----------3
    Upsell Other-----------------------0---------1-----------3----------1
    Reference---------------------------2---------6----------7----------3
    Issue---------------------------------0----------0----------1----------0
    So if an action on 12-Oc-06 had a Y in Met_customer and Y in Upsell_app it would be counted twice in the above - whereas below it does not work like that...
    At the moment the code is producing something like the following...
    MET_CUST | USPELL_APP | UPSELL_OTHER | REFERENCE | ISSUE | Oct06 | Nov06
    ------Y------------------------------------------------------------------------------------------------------12--------2
    ------Y-------------------Y---------------------------------------------------------------------------------11--------0
    ---------------------------Y----------------------------------------------------------------------------------1---------3
    ------------------------------------------------------Y-------------------------------------------Y----------6---------0
    --------------------------------------------------------------------------------Y-----------------------------2---------1
    ---------------------------------------------------------------------------------------------------Y----------0----------1
    ---------------------------------------------------------------------------------------------------------------1---------1
    This is the code we're using
    SELECT
    ACTION_MET_CUSTOMER,
    ACTION_UPSELL_APPS,
    ACTION_UPSELL_OTHER,
    ACTION_REFERENCE,
    ACTION_ISSUE,
    SUM ( decode( substr(DATE_DONE,-3,1), '-', cnt, null ) ) TOTAL,
    SUM ( decode( substr(DATE_DONE,-6,6), 'OCT-06', cnt, null ) ) OCT06,
    SUM ( decode( substr(DATE_DONE,-6,6), 'NOV-06', cnt, null ) ) NOV06,
    SUM ( decode( substr(DATE_DONE,-6,6), 'DEC-06', cnt, null ) ) DEC06,
    SUM ( decode( substr(DATE_DONE,-6,6), 'JAN-07', cnt, null ) ) JAN07,
    SUM ( decode( substr(DATE_DONE,-6,6), 'FEB-07', cnt, null ) ) FEB07,
    SUM ( decode( substr(DATE_DONE,-6,6), 'MAR-07', cnt, null ) ) MAR07,
    SUM ( decode( substr(DATE_DONE,-6,6), 'APR-07', cnt, null ) ) APR07,
    SUM ( decode( substr(DATE_DONE,-6,6), 'MAY-07', cnt, null ) ) MAY07,
    SUM ( decode( substr(DATE_DONE,-6,6), 'JUN-07', cnt, null ) ) JUN07,
    SUM ( decode( substr(DATE_DONE,-6,6), 'JUL-07', cnt, null ) ) JUL07,
    SUM ( decode( substr(DATE_DONE,-6,6), 'AUG-07', cnt, null ) ) AUG07,
    SUM ( decode( substr(DATE_DONE,-6,6), 'SEP-07', cnt, null ) ) SEP07,
    SUM ( decode( substr(DATE_DONE,-6,6), 'OCT-07', cnt, null ) ) OCT07,
    SUM ( decode( substr(DATE_DONE,-6,6), 'NOV-07', cnt, null ) ) NOV07,
    SUM ( decode( substr(DATE_DONE,-6,6), 'DEC-07', cnt, null ) ) DEC07,
    SUM ( decode( substr(DATE_DONE,-6,6), 'JAN-08', cnt, null ) ) JAN08,
    SUM ( decode( substr(DATE_DONE,-6,6), 'FEB-08', cnt, null ) ) FEB08,
    SUM ( decode( substr(DATE_DONE,-6,6), 'MAR-08', cnt, null ) ) MAR08,
    SUM ( decode( substr(DATE_DONE,-6,6), 'APR-08', cnt, null ) ) APR08,
    SUM ( decode( substr(DATE_DONE,-6,6), 'MAY-08', cnt, null ) ) MAY08
    FROM
    (SELECT ACTION_MET_CUSTOMER, ACTION_UPSELL_APPS, ACTION_UPSELL_OTHER, ACTION_REFERENCE, ACTION_ISSUE, DATE_DONE, COUNT(*) CNT FROM ACTIONS, EMPLOYEE
    WHERE ACTION_OWNER = NAME
    GROUP BY ACTION_MET_CUSTOMER, ACTION_UPSELL_APPS, ACTION_UPSELL_OTHER, ACTION_REFERENCE, ACTION_ISSUE, DATE_DONE)
    GROUP BY
    ACTION_MET_CUSTOMER, ACTION_UPSELL_APPS, ACTION_UPSELL_OTHER, ACTION_REFERENCE, ACTION_ISSUE
    Any ideas to get it looking how id ideally like it?
    Cheers, would be a great help
    S

    select 'Met Customer' action_type,
    to_char(date_done,'MON-YY') date_done,
    action_owner,
    COUNT(1)
    from ff_actions
    where action_met_customer = 'Y'
    group by action_met_customer
    UNION
    select 'Upsell Apps' action_type,
    to_char(date_done,'MON-YY') date_done,
    action_owner,
    COUNT(1)
    from ff_actions
    where action_upsell_apps = 'Y'
    group by action_upsell_apps
    UNION
    select 'Upsell Other' action_type,
    to_char(date_done,'MON-YY') date_done,
    action_owner,
    COUNT(1)
    from ff_actions
    where action_upsell_other = 'Y'
    group by action_upsell_other
    UNION
    select 'Reference' action_type,
    to_char(date_done,'MON-YY') date_done,
    action_owner,
    COUNT(1)
    from ff_actions
    where action_reference = 'Y'
    group by action_reference
    UNION
    select 'Issue' action_type,
    to_char(date_done,'MON-YY') date_done,
    action_owner,
    COUNT(1)
    from ff_actions
    where action_issue = 'Y'
    group by action_issue
    now error...
    ORA-00979: not a GROUP BY expression

Maybe you are looking for

  • Is it possible to retrieve the data from maintainance view?

    Hi experts, Am facing one problem. Is it possible to retrieve the data from Maintainance View ,If yes how? IF it is not possible then Y? While am trying to retrieve data from maintainance view it's showing message like "it is not a database view or t

  • Submit button wont align

    Hi Ive tried to work this out for myself (and my friend Google), and spent all day without getting anywhere. I am trying to get the submit button, which I have made an image, align nicely under the right hand side of the above input box. ie. the righ

  • Prepared Statement Flooding

    Hi Friends, Need your help to fix this prolonging problem in one of our applications. We observe that the following queries are declared as prepared statements but have dynamic value ROWID in each. SELECT ROWID, C. * FROM Table1 C WHERE C.VENDORLOGIN

  • Non-deductible tax

    Dear all In my service entry sheet, NAVM-Non deductible tax is getting added with the base price. Gross value of unit is 10, but net value incl tax is Rs 10.14. How can i make the system to calculate Gross value is equal to Net value incl of tax? I d

  • Web service API

    Hi, I'm trying to access the sample application mentioned in a few different places at [https://boc.sdn.sap.com/betas/crdcapi] However, this just redirects to the general beta page. Is it out of beta? Is it available anywhere else? Many thanks Matt