Please Help in query

SELECT PEE2.ASSIGNMENT_ID,--,PEEV2.EFFECTIVE_START_DATE,
PET.ELEMENT_NAME,NVL(MAX(PEEV2.SCREEN_ENTRY_VALUE),0)SALARY
--PEE2.EFFECTIVE_START_DATE PEE_START
FROM PAY_ELEMENT_ENTRIES_F PEE2,PAY_ELEMENT_ENTRY_VALUES_F PEEV2 , PAY_ELEMENT_TYPES_F PET
WHERE PEE2.ELEMENT_TYPE_ID = PET.ELEMENT_TYPE_ID
AND PEE2.ELEMENT_ENTRY_ID=PEEV2.ELEMENT_ENTRY_ID
AND PET.ELEMENT_NAME IN('BASIC_SALARY','AL_CONVEYANCE','AL_TEA','AL_COLA')
AND PEEV2.SCREEN_ENTRY_VALUE IS NOT NULL
AND (PEE2.ASSIGNMENT_ID,PEEV2.EFFECTIVE_START_DATE)=(
SELECT PEE.ASSIGNMENT_ID,MAX(PEEV.EFFECTIVE_START_DATE)
FROM PAY_ELEMENT_ENTRIES_F PEE,PAY_ELEMENT_ENTRY_VALUES_F PEEV
WHERE PEE.ELEMENT_ENTRY_ID=PEEV.ELEMENT_ENTRY_ID
AND PEE.ASSIGNMENT_ID=:ASSIGNMENT_ID
AND PEE.ELEMENT_TYPE_ID = PET.ELEMENT_TYPE_ID
AND PET.ELEMENT_NAME IN('BASIC_SALARY','AL_CONVEYANCE','AL_TEA','AL_COLA')
AND PEEV.SCREEN_ENTRY_VALUE IS NOT NULL
GROUP BY PEE.ASSIGNMENT_ID
)GROUP BY ASSIGNMENT_ID , PET.ELEMENT_TYPE_ID , PET.ELEMENT_NAME
output is
ASSIGNMENT_ID     ELEMENT_NAME     SALARY
117     AL_COLA     650
117     AL_CONVEYANCE     1180
117     AL_TEA     172
117     BASIC_SALARY     7820
but i want the output like this
ASSIGNMENT_ID ------AL_COLA------AL_CONVEYANCE------AL_TEA-------BASIC_SALARY
117---------------------------650-------------------1180----------------------172-----------7820
PLZZ HELP NO HARDCODE PLZZ ONLY DYNAMIC QUERY REQUIRED AND NO PL/SQL USED..
REGARDS
RANCHOO

Hi,
Since you didn't post any tables, I'll use the scott.emp table to show you how to get results like that.
Let's say we're interested in this data:
SELECT       deptno
,       job
,       sal
FROM       scott.emp
ORDER BY  deptno
,     job
    DEPTNO JOB              SAL
        10 CLERK           1300
        10 MANAGER         2450
        10 PRESIDENT       5000
        20 ANALYST         3000
        20 ANALYST         3000
        20 CLERK           1100
        20 CLERK            800
        20 MANAGER         2975
        30 CLERK            950
        30 MANAGER         2850
        30 SALESMAN        1250
        30 SALESMAN        1250
        30 SALESMAN        1600
        30 SALESMAN        1500Let's say we want to get a total sal for each deptno and job, aned present it as a cross-tab, with a row for every deptno and a column for every job. As Karthick pointed out, that requires dynamic SQL, so let's just take the first 4 jobs in alphabetic order. The query below numbers the jobs 1, 2, 3, ... in alphabetic order, then uses that number to consider only a certain job in each column.
WITH     got_jnum    AS
     SELECT       deptno
     ,       job
     ,       sal
     ,       DENSE_RANK () OVER (ORDER BY job)     AS jnum
     FROM       scott.emp
SELECT       deptno
,       TO_CHAR (SUM (CASE WHEN jnum = 1 THEN sal END), '99999999')     AS job_1
,       TO_CHAR (SUM (CASE WHEN jnum = 2 THEN sal END), '99999999')     AS job_2
,       TO_CHAR (SUM (CASE WHEN jnum = 3 THEN sal END), '99999999')     AS job_3
,       TO_CHAR (SUM (CASE WHEN jnum = 4 THEN sal END), '99999999')     AS job_4
FROM       got_jnum
GROUP BY  deptno
    UNION ALL
SELECT       NULL                                   AS deptno
,       MIN (CASE WHEN jnum = 1 THEN LPAD (job, 9) END)     AS job_1
,       MIN (CASE WHEN jnum = 2 THEN LPAD (job, 9) END)     AS job_2
,       MIN (CASE WHEN jnum = 3 THEN LPAD (job, 9) END)     AS job_3
,       MIN (CASE WHEN jnum = 4 THEN LPAD (job, 9) END)     AS job_4
FROM       got_jnum
ORDER BY  deptno     NULLS FIRST
    DEPTNO JOB_1     JOB_2     JOB_3     JOB_4
             ANALYST     CLERK   MANAGER PRESIDENT
        10                1300      2450      5000
        20      6000      1900      2975
        30                 950      2850A lot of the complexity in the query above involves getting the row with the actual job names. If you knew what they were, you could hard-colde them into the query; then you woldn't need the second part of the UNION, and therefore you wouldn't need TO_CHAR.
This is called a Pivot . Search for "Pivot" (or, as Karthick suggested "Rows to Columns") to see more examples and explanations.
If you really want a variable number of columns, then you need dynamic SQL, as Karthick explained. This isn't very hard, as dynamic SQL goes. You just need to have a preliminary query determine what the jobs are, and write an appropriate SUM expression (with column alias) to use in the SELECT clause. See [this thread|http://forums.oracle.com/forums/message.jspa?messageID=3227306] for an example.
Another way to get a variable number of jobs is to use String Aggregation , where all the data about all the jobs is combined in one giant string column. That huge string can be formatted so that it looks like separate columns. [This site|http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php] has a good summary of different String Aggregation techniques.

Similar Messages

  • Please help in query performance

    select bg.billing_group_id,r.rating_result, count(*),rc.source,rc.description
    from rejected_record r,
    result_code@RD rc,
    terminal_device@cust td,
    personal_account_td@cust patd,
    personal_account@cust pa,
    billing_group@cust bg,
    -- tariff_plan@rd tp,
    (select pcs.primary_session_id, pcs.charging_date
    from pcs@umr_interface
    where pcs.range_cdr_file_source not like 'HOT%'
    --and lower(pcs.RANGE_CDR_FILE_SOURCE) not like 'rec%'
    -- and lower(pcs.RANGE_CDR_FILE_SOURCE) not like 'sms%'
    -- and lower(pcs.RANGE_CDR_FILE_SOURCE) not like 'data%'
    -- and pcs.CHARGING_TYPE_ID = 1
    and pcs.charging_date between '20/Aug/2010' and '21/Sep/2010') t
    where r.primary_session_id = t.primary_session_id
    and rc.code (+)= r.rating_result
    and td.terminal_device_id = patd.terminal_device_id
    and patd.personal_account_id = pa.personal_account_id
    and r.calling_party_number_rid = td.msisdn
    and pa.billing_group_id = bg.billing_group_id
    and r.is_precharged=0
    --and td.tariff_plan_id=tp.tariff_plan_id
    and (nvl(td.date_to,'01.01.2000')='01.01.2000')
    and (nvl(pa.date_to,'01.01.2000')='01.01.2000')
    and (nvl(patd.date_to,'01.01.2000')='01.01.2000')
    group by r.rating_result, rc.source, rc.description,bg.billing_group_id
    order by r.rating_result
    SQL> select * from v$version;
    BANNER
    Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production
    PL/SQL Release 9.2.0.8.0 - Production
    CORE     9.2.0.8.0     Production
    TNS for Solaris: Version 9.2.0.8.0 - Production
    NLSRTL Version 9.2.0.8.0 - Production
    SQL>
    Above select query took only 10 mins when those nvl functions where not there..
    but when these nvl fuctions are added this takes lot of time....
    please help to optimce it..
    first i tried with is null.. it took lot of time.. ten i replaced it with nvl function...
    please somebody help to optimize this query

    Check out these links:
    {message:id=1812597}
    {thread:id=863295}

  • Please help with query for 5 lastest opening balance  !!!!!!!!!!!

    Can anyone plese tell me or guide me how to write the query to show the 5 lastest opening balance from the A/R invoice on the specific BP partner?
    Example
    The box to input "BP partner"
    and then show,
    Lastest transaction | Ship date | Invoice number | Balance Amount | Culmulative
    1    
    2
    3
    4
    5
    Your help will be very very appreciated.

    This is very good but I would like to show only the top 5 remaining invoice. I think that I have to combine it with JDT1. I have seen one query that may be able to apply on my case.
    SELECT
    T1.CardCode + '' AS 'BP Code',
    T2.Notes2 AS 'BP Name',
    T0.RefDate,
    CASE
         WHEN T0.TransType = 13 THEN 'IN'
         WHEN T0.TransType = 14 THEN 'CN'
         WHEN T0.TransType = 30 THEN 'JE'
         WHEN T0.TransType = 24 THEN 'RC'
         WHEN T0.TransType = 46 THEN 'PS'
         ELSE 'Error ! ! !'
    END AS 'Doc Type',
    T0.Ref1 'Doc. Number',
    ISNULL(T0.FCCurrency, ' - ') AS 'Ccy',
    (T0.BalFcDeb - T0.BalFcCred) AS 'Bal. F. Ccy',
    (T0.BalDueDeb - T0.BalDueCred) AS 'Bal. Rs',
    ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred WHERE DateDiff(mm, T0.RefDate, '[%1]') <= -1)                     ,0) AS 'Future',
    ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred WHERE DateDiff(mm, T0.RefDate, '[%1]') = 0)                         ,0) AS 'Current Mth',
    ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred WHERE DateDiff(mm, T0.RefDate, '[%1]') = 1)                         ,0) AS '1 Mth Ago',
    ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred WHERE DateDiff(mm, T0.RefDate, '[%1]') = 2)                         ,0) AS '2 Mth Ago',
    ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred WHERE DateDiff(mm, T0.RefDate ,'[%1]') = 3)                         ,0) AS '3 Mth Ago',
    ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred WHERE DateDiff(mm, T0.RefDate, '[%1]') between 4 and 6)    ,0) AS '4 - 6 Mth Ago',
    ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred WHERE DateDiff(mm, T0.RefDate, '[%1]') >= 7)                       ,0) AS '>7 Mth Ago'
    FROM JDT1 T0
    INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
    LEFT OUTER JOIN OCPR T2 ON T1.CardCode = T2.Cardcode
    LEFT OUTER JOIN OJDT T3 ON T0.TransID = T3.TransID
    LEFT OUTER JOIN OINV  T4 ON T3.TransID = T4.TransID
    LEFT OUTER JOIN ORIN  T5 ON T3.TransID = T5.TransID
    WHERE
    T1.CardType = 'C' and Balance != 0
    and (T0.BalDueDeb - T0.BalDueCred) != 0
    but still try to figure it out....

  • Please Help this query should be simple :)

    Here is what I have written so far: Basically I want it to return all the locations like I have specified that do not have DA-REPL in the area_code table but it is just returning everything it seems.
    select l.location_no, l.zone_code, la.area_code
    from move.location l, move.location_area la
    where la.location_no = l.location_no
    and l.zone_code = 'Z-BIN'
    and (l.location_no like '%%-%%-2%%' or l.location_no like '%%-%%-1%%')
    and la.area_code != 'DA-REPL'
    order by 1
    Here is what my results look like:
    60-02-101     Z-BIN     WA-60
    60-02-101     Z-BIN     WA-BIN
    60-02-101     Z-BIN     WA-BINRESV
    60-02-101     Z-BIN     WA-PALLET
    60-02-102     Z-BIN     WA-60
    60-02-102     Z-BIN     WA-BIN
    60-02-102     Z-BIN     WA-BINRESV
    60-02-102     Z-BIN     WA-PALLET
    60-02-201     Z-BIN     WA-60
    60-02-201     Z-BIN     WA-BIN
    60-02-201     Z-BIN     WA-BINRESV
    60-02-201     Z-BIN     WA-PALLET
    Edited by: 906043 on Feb 20, 2012 2:23 PM

    906043 wrote:
    At it's most basic the query would look like this but this gives me 67,834 results I am dealing with a pretty big warehouse with many "la.area_code" entries I am only trying to get the locations in a specific zone('Z-BIN') that do not have 'DA-REPL' as an la.area_code as this would cause that location never to get replenishments when it becomes empty.
    select l.location_no, l.zone_code, la.area_code
    from move.location l, move.location_area la
    where la.location_no = l.location_no
    l.zone_code = 'Z=BIN'
    and la.area_code != 'DA-REPL'
    order by 1
    Not sure if that helps anymore I am at a loss but still plugging away :)A little attention to code formatting could bring some sanity to yourself. Enclosing that formatted code in the code tags on this forum would bring a lot of sanity to those trying to help you:
    select l.location_no
    ,      l.zone_code
    ,      la.area_code
    from move.location l
    ,    move.location_area la
    where la.location_no = l.location_no
          l.zone_code = 'Z=BIN'
    and   la.area_code != 'DA-REPL'
    order by 1And once it is formatted for easier reading by humans, it's easier to see that you are missing an "and" (maybe "or"?) in your WHERE clause.

  • Please help - Recursive Query Restrictions

    Hi All,
    I wanted to know what restrictions are placed on Oracle Recursive Query capability. Any help or links in this regards would be highly appreciated. Waiting to hear from you.
    Thanks,
    Snehal

    Can't think of anything I would term a restriction off the top of my head. There are a few notes in the SQL Reference about precedence that probably aren't obvious.
    Are you having a particular problem with this syntax?
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • Please help with query

    Hello, I'm trying to write a query which is of the form below:
    select (aa.name || bb.name) full_name
    from
    (select * from per_positions where name = 'Igwe') aa,
    (select * from per_positions where name = 'OSHS.Application.Specialist.Head Office') bb
    There are two generated tables aa and bb. Sometimes aa and bb both return a value and sometimes only aa or only bb returns a value. So my question is, in a scenario where only of the inner tables returns a value, is it possible to make the other table return a null or blank value? In my case, when one of the tables doesn't return a value the entire record shows a null value. Thanks.

    user FULL JOIN
    SQL> with t
      2  as
      3  (select 'a' name from dual
      4  union all
      5  select 'b' name from dual
      6  )
      7  select aa.name||bb.name
      8    from (select name from t where name = 'a') aa
      9    full join (select name from t where name = 'b') bb
    10      on 1=1
    11  /
    AA
    ab
    SQL> with t
      2  as
      3  (select 'a' name from dual
      4  union all
      5  select 'b' name from dual
      6  )
      7  select aa.name||bb.name
      8    from (select name from t where name = 'a') aa
      9    full join (select name from t where name = 'x') bb
    10      on 1=1
    11  /
    AA
    a
    SQL> with t
      2  as
      3  (select 'a' name from dual
      4  union all
      5  select 'b' name from dual
      6  )
      7  select aa.name||bb.name
      8    from (select name from t where name = 'x') aa
      9    full join (select name from t where name = 'b') bb
    10      on 1=1
    11  /
    AA
    b

  • Please help -- MySQL Query to Oracle

    I have been trying to convert the following MySQL query to work with Oracle 9i. There seem to be two problems:
    1) Oracle doesn't like the inclusion of the tblpackagegeneral.packageid in the "ON" clause of the "JOIN".
    2) The "GROUP BY" only has the one field, "tblpackagegeneral.packageid", specified; Oracle wants the other two specified as well. When I do that I get a different data set than what MySQL returns for the same tables of data: specifically MySQL returns one row for each packageid but the revised Oracle version returns more than 1 sometimes.
    I would appreciate any assistance possible.
    /* Formatted on 2003/07/07 14:43 (Formatter Plus v4.8.0) */
    SELECT tblpackagegeneral.packageid,
    CASE
    WHEN NVL
    (COUNT (tblpackagelearnerassignment.learnerid),
    COUNT (tbllearnergeneral.learnerid)
    ) > 0
    THEN 'Activity'
    WHEN tbllearnergeneral.subscribetopubliccourse = 'true'
    AND tblpackagegeneral.packageaccess = 'Public'
    THEN 'ActivityAfterSubscribe'
    WHEN ( tbllearnergeneral.subscribetopubliccourse = 'false'
    AND tblpackagegeneral.packageaccess = 'Public'
    THEN 'Subscribe'
    ELSE 'Subscribe'
    END AS "ASSIGNSTATUS"
    FROM tblpackagegeneral, tbllearnergeneral LEFT OUTER JOIN tblpackagelearnerassignment ON ( tblpackagelearnerassignment.packageid =
    tblpackagegeneral.packageid
    AND tblpackagelearnerassignment.learnerid =
    tbllearnergeneral.learnerid
    WHERE tbllearnergeneral.learnerid = '%var'
    AND tblpackagegeneral.packageavailability = 'Available'
    AND TO_CHAR (tblpackagegeneral.dateto, 'YYYYMMDD') >=
    TO_CHAR (CURRENT_TIMESTAMP, 'YYYYMMDD')
    GROUP BY tblpackagegeneral.packageid;
    Sincerely,
    Bill Robinson

    I have been trying to convert the following MySQL query to work with Oracle 9i. There seem to be two problems:
    1) Oracle doesn't like the inclusion of the tblpackagegeneral.packageid in the "ON" clause of the "JOIN".
    2) The "GROUP BY" only has the one field, "tblpackagegeneral.packageid", specified; Oracle wants the other two specified as well. When I do that I get a different data set than what MySQL returns for the same tables of data: specifically MySQL returns one row for each packageid but the revised Oracle version returns more than 1 sometimes.
    I would appreciate any assistance possible.
    /* Formatted on 2003/07/07 14:43 (Formatter Plus v4.8.0) */
    SELECT tblpackagegeneral.packageid,
    CASE
    WHEN NVL
    (COUNT (tblpackagelearnerassignment.learnerid),
    COUNT (tbllearnergeneral.learnerid)
    ) > 0
    THEN 'Activity'
    WHEN tbllearnergeneral.subscribetopubliccourse = 'true'
    AND tblpackagegeneral.packageaccess = 'Public'
    THEN 'ActivityAfterSubscribe'
    WHEN ( tbllearnergeneral.subscribetopubliccourse = 'false'
    AND tblpackagegeneral.packageaccess = 'Public'
    THEN 'Subscribe'
    ELSE 'Subscribe'
    END AS "ASSIGNSTATUS"
    FROM tblpackagegeneral, tbllearnergeneral LEFT OUTER JOIN tblpackagelearnerassignment ON ( tblpackagelearnerassignment.packageid =
    tblpackagegeneral.packageid
    AND tblpackagelearnerassignment.learnerid =
    tbllearnergeneral.learnerid
    WHERE tbllearnergeneral.learnerid = '%var'
    AND tblpackagegeneral.packageavailability = 'Available'
    AND TO_CHAR (tblpackagegeneral.dateto, 'YYYYMMDD') >=
    TO_CHAR (CURRENT_TIMESTAMP, 'YYYYMMDD')
    GROUP BY tblpackagegeneral.packageid;
    Sincerely,
    Bill Robinson

  • Please help, simple query not working

    Have the following script that I would like to run at multiple sites and create table columns if necessary:
    DECLARE
    table_name VARCHAR2 (30) := 'SITE_STATISTICS';
    column_name VARCHAR2 (30) := 'SITE_MONTH';
    column_data_type VARCHAR2 (30) := 'DATE';
    column_count INTEGER;
    dynamic_sql VARCHAR2 (4000);
    BEGIN
    SELECT COUNT (1)
    INTO column_count
    FROM SYS.USER_TAB_COLUMNS utc
    WHERE utc.table_name = table_name AND utc.column_name = column_name AND utc.data_type = column_data_type;
    SYS.DBMS_OUTPUT.ENABLE (4000);
    IF column_count = 0 THEN
    dynamic_sql :=
    ALTER TABLE SITE_STATISTICS ADD (SITE_MONTH DATE);
    EXECUTE IMMEDIATE dynamic_sql;
    ELSE
    DBMS_OUTPUT.put_line ('Not running Dynamic Sql, found ' || column_count || ' corresponding rows in sys.user_tab_columns');
    END IF;
    END;
    EXIT;
    At a given site I do not have the given column, and running the select from sys.user_tab_columns manually returns 0 rows. However, when I run this script it outputs the following:
    Not running Dynamic Sql, found 128 corresponding rows in sys.user_tab_columns
    What's going on!?

    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bit Production
    With the Partitioning, OLAP and Data Mining options
    SQL> create table abc (c1 number(10));
    Table created.
    SQL> DECLARE
      2     table_name1                   VARCHAR2 ( 30 ) := 'ABC';
      3     column_name1                  VARCHAR2 ( 30 ) := 'SITE_MONTH';
      4     column_data_type1             VARCHAR2 ( 30 ) := 'DATE';
      5     column_count                  INTEGER;
      6     dynamic_sql                   VARCHAR2 ( 4000 );
      7  BEGIN
      8     SELECT COUNT ( 1 )
      9       INTO column_count
    10       FROM SYS.user_tab_columns utc
    11      WHERE utc.table_name = table_name1
    12        AND utc.column_name = column_name1
    13        AND utc.data_type = column_data_type1;
    14  
    15     SYS.DBMS_OUTPUT.ENABLE ( 4000 );
    16  
    17     IF column_count = 0 THEN
    18  
    19        dynamic_sql :='ALTER TABLE ABC ADD (SITE_MONTH DATE,SHIP_CONTANK INTEGER,SHIP_CONRAIL INTEGER)';
    20  
    21        EXECUTE IMMEDIATE dynamic_sql;
    22     ELSE
    23        DBMS_OUTPUT.put_line (    'Not running Dynamic Sql, found '
    24                               || column_count
    25                               || ' corresponding rows in sys.user_tab_columns'
    26                             );
    27     END IF;
    28  END;
    29  /
    PL/SQL procedure successfully completed.
    SQL> desc abc
    Name                                      Null?    Type
    C1                                                 NUMBER(10)
    SITE_MONTH                                         DATE
    SHIP_CONTANK                                       NUMBER(38)
    SHIP_CONRAIL                                       NUMBER(38)

  • Please help SQL query

    why this works fine
    SELECT * FROM (
    SELECT ename,deptno,sal ,ROWNUM RN FROM emp)
    WHERE MOD(RN,3)=0
    while
    SELECT rownum FROM employees WHERE MOD(Rownum,3)=0
    wotnh works
    why this happenssssssssssssss

    ROWNUM is dynamically determined on-the-fly during the fetching of results.
    So this works:
    SELECT * FROM table WHERE rownum < 11
    It will return the first 10 rows. The following does not work:
    SELECT * FROM table WHERE rownum between 11 and 20
    As ROWNUM is added as the results are fetched from the database, it can only be used as a stopkey.
    To use ROWNUM as any other column in a predicate, you need to change ROWNUM from a "dynamic on-the-fly" column into a "proper" column. Just as you did with your 1st SELECT.
    E.g.WITH my_results AS(
            SELECT rownum AS RNO, o.* FROM all_objects o WHERE object_type = 'TRIGGER'
    SELECT
            object_id,
            object_name
    FROM    my_results
    WHERE   rno between 11 and 20

  • Help me query tunning

    Hi Guru's
    Can you please help me query tunning.
    Database Version : Oracle 11g - 11.2.0.3
    select  distinct  corporation_name custer_name,
            glog_util.remove_domain(SHIP_BUY.SERVPROV_GID ) SCAC,
            glog_util.remove_domain(ship_buy.shipment_gid) buy_shipment_gid,
            F_Get_SELL_ID_STRING(SHIP_BUY.SHIPMENT_GID) sell_shipment_gid,
            ship_buy.domain_name,    
            F_GET_ORDER_RELEASE_GID('B',SHIP_BUY.SHIPMENT_GID,0) ORDER_RELEASE_GID,
            f_get_refnum_string('SHIPMENT', ship_buy.shipment_gid, 'MBOL_NUMBER_CLEANSED')MBOL_NUMBER,
            F_GET_POD_RECEIVED_DATE (ship_BUY.SHIPMENT_GID) POD_RECEIVED_DATE,
            f_get_exp_accrue_amt(ship_buy.shipment_gid,'SHIPMENT') Total_accrual_amount    
    from shipment ship_buy,
            invoice inv,
            invoice_shipment si,
            --voucher v,
            corporation corp
    where corp.domain_name=ship_buy.domain_name
            and corp.is_domain_master='Y'
          and 1=1
          AND ship_buy.domain_name like 'UPS/CP/DFP/%'
          and F_GET_POD_RECEIVED_DATE (ship_BUY.SHIPMENT_GID)  <= to_char(to_date('31-JUL-2013', 'DD-MON-YYYY'), 'dd-mon-yyyy')
            --and V.INVOICE_GID(+) = inv.invoice_gid
            --and ship_buy.domain_name = 'UPS/CP/VZNB'
            and si.shipment_gid(+) = SHIP_BUY.SHIPMENT_GID
            AND SI.INVOICE_GID = INV.INVOICE_GID(+)
            and SHIP_BUY.INSERT_DATE > '1-JAN-2007'
            and SHIP_BUY.USER_DEFINED1_ICON_GID = 'ACCEPTED'
    UNION        
    select  distinct  corporation_name custer_name,
            glog_util.remove_domain(SHIP_BUY.SERVPROV_GID ) SCAC,
            glog_util.remove_domain(ship_buy.shipment_gid) buy_shipment_gid,
            F_GET_SELL_ID_STRING( SHIP_BUY.SHIPMENT_GID) sell_shipment_gid,
            ship_buy.domain_name,    
            F_GET_ORDER_RELEASE_GID('B',SHIP_BUY.SHIPMENT_GID,0) ORDER_RELEASE_GID,
            f_get_refnum_string('SHIPMENT', ship_buy.shipment_gid, 'MBOL_NUMBER_CLEANSED')MBOL_NUMBER,
            F_GET_POD_RECEIVED_DATE (ship_BUY.SHIPMENT_GID) POD_RECEIVED_DATE,
            f_get_exp_accrue_amt(inv.invoice_gid,'INVOICE') Total_accrual_amount  
    from shipment ship_buy,
            invoice inv,
            invoice_shipment si,
          -- voucher v,
            corporation corp
    where corp.domain_name=ship_buy.domain_name
            and corp.is_domain_master='Y'
            and 1=1
            AND ship_buy.domain_name like 'UPS/CP/DFP/%'
            and F_GET_POD_RECEIVED_DATE (ship_BUY.SHIPMENT_GID)  <= to_char(to_date('31-JUL-2013', 'DD-MON-YYYY'), 'dd-mon-yyyy')
          --AND INV.DOMAIN_NAME = 'UPS/CP/VZNB'
          --and V.INVOICE_GID(+) = inv.invoice_gid
            and si.shipment_gid(+) = SHIP_BUY.SHIPMENT_GID
            AND SI.INVOICE_GID = INV.INVOICE_GID(+)
            and SHIP_BUY.INSERT_DATE > '1-JAN-2007'
            and INV.USER_DEFINED1_ICON_GID = 'ACCEPTED'
    GROUP BY corporation_name,SHIP_BUY.SHIPMENT_GID,SHIP_BUY.SERVPROV_GID,ship_buy.domain_name,inv.invoice_gid
    ORDER BY CUSTER_NAME, BUY_SHIPMENT_GID;
    And I generated the execution plan :
    | Id  | Operation                          | Name                    | Rows  | Bytes | Cost (%CPU)| Time    |
    |  0 | SELECT STATEMENT                  |                        |    3 |  448 |  415  (2)| 00:00:05 |
    |  1 |  SORT UNIQUE                      |                        |    3 |  448 |  414  (87)| 00:00:05 |
    |  2 |  UNION-ALL                        |                        |      |      |            |          |
    |  3 |    NESTED LOOPS OUTER              |                        |    3 |  384 |    57  (0)| 00:00:01 |
    |*  4 |    HASH JOIN                      |                        |    3 |  294 |    54  (0)| 00:00:01 |
    |*  5 |      TABLE ACCESS BY INDEX ROWID  | SHIPMENT                |    3 |  195 |    40  (0)| 00:00:01 |
    |*  6 |      INDEX SKIP SCAN              | IND_SHIP_DOM_ICON      |    54 |      |    25  (0)| 00:00:01 |
    |*  7 |      TABLE ACCESS FULL            | CORPORATION            |    4 |  132 |    14  (0)| 00:00:01 |
    |*  8 |    INDEX RANGE SCAN              | IND_INVOICESHIP_SHP_GID |    1 |    30 |    1  (0)| 00:00:01 |
    |  9 |    HASH GROUP BY                  |                        |    1 |  192 |  356  (1)| 00:00:05 |
    |* 10 |    HASH JOIN                      |                        |    1 |  192 |  354  (1)| 00:00:05 |
    |  11 |      NESTED LOOPS                  |                        |      |      |            |          |
    |  12 |      NESTED LOOPS                |                        |    1 |  159 |  339  (0)| 00:00:05 |
    |  13 |        NESTED LOOPS                |                        |  145 | 13920 |  194  (0)| 00:00:03 |
    |  14 |        TABLE ACCESS BY INDEX ROWID| INVOICE                |  145 |  5220 |    49  (0)| 00:00:01 |
    |* 15 |          INDEX SKIP SCAN          | IDX_INV_TYP_ICON_NAM    |  145 |      |    17  (0)| 00:00:01 |
    |* 16 |        INDEX RANGE SCAN          | UK_INVOICE_SHIPMENT    |    1 |    60 |    1  (0)| 00:00:01 |
    |* 17 |        INDEX UNIQUE SCAN          | PK_SHIPMENT            |    1 |      |    1  (0)| 00:00:01 |
    |* 18 |      TABLE ACCESS BY INDEX ROWID  | SHIPMENT                |    1 |    63 |    1  (0)| 00:00:01 |
    |* 19 |      TABLE ACCESS FULL            | CORPORATION            |    4 |  132 |    14  (0)| 00:00:01 |
    Predicate Information (identified by operation id):
      4 - access("CORP"."DOMAIN_NAME"="SHIP_BUY"."DOMAIN_NAME")
      5 - filter("F_GET_POD_RECEIVED_DATE"("SHIP_BUY"."SHIPMENT_GID")<=TO_DATE(' 2013-07-31 00:00:00',
                  'syyyy-mm-dd hh24:mi:ss') AND "SHIP_BUY"."INSERT_DATE">TO_DATE(' 2007-01-01 00:00:00', 'syyyy-mm-dd
                  hh24:mi:ss'))
      6 - access("SHIP_BUY"."USER_DEFINED1_ICON_GID"='ACCEPTED' AND "SHIP_BUY"."DOMAIN_NAME" LIKE
                  'UPS/CP/DFP/%')
          filter("SHIP_BUY"."DOMAIN_NAME" LIKE 'UPS/CP/DFP/%' AND
                  "SHIP_BUY"."USER_DEFINED1_ICON_GID"='ACCEPTED')
      7 - filter("CORP"."IS_DOMAIN_MASTER"='Y' AND "CORP"."DOMAIN_NAME" LIKE 'UPS/CP/DFP/%')
      8 - access("SI"."SHIPMENT_GID"(+)="SHIP_BUY"."SHIPMENT_GID")
      10 - access("CORP"."DOMAIN_NAME"="SHIP_BUY"."DOMAIN_NAME")
      15 - access("INV"."USER_DEFINED1_ICON_GID"='ACCEPTED')
          filter("INV"."USER_DEFINED1_ICON_GID"='ACCEPTED')
      16 - access("SI"."INVOICE_GID"="INV"."INVOICE_GID")
      17 - access("SI"."SHIPMENT_GID"="SHIP_BUY"."SHIPMENT_GID")
          filter("F_GET_POD_RECEIVED_DATE"("SHIP_BUY"."SHIPMENT_GID")<=TO_DATE(' 2013-07-31 00:00:00',
                  'syyyy-mm-dd hh24:mi:ss'))
      18 - filter("SHIP_BUY"."DOMAIN_NAME" LIKE 'UPS/CP/DFP/%' AND "SHIP_BUY"."INSERT_DATE">TO_DATE('
                  2007-01-01 00:00:00', 'syyyy-mm-dd hh24:mi:ss'))
      19 - filter("CORP"."IS_DOMAIN_MASTER"='Y' AND "CORP"."DOMAIN_NAME" LIKE 'UPS/CP/DFP/%')
    Statistics
        246247  recursive calls
              2  db block gets
        1660067  consistent gets
          13839  physical reads
              0  redo size
        592054  bytes sent via SQL*Net to client
          6024  bytes received via SQL*Net from client
            502  SQL*Net roundtrips to/from client
          15296  sorts (memory)
              0  sorts (disk)
          7513  rows processed

    Hmmm...why does this look familiar?
    F_GET_POD_RECEIVED_DATE (ship_BUY.SHIPMENT_GID)  <= to_char(to_date('31-JUL-2013', 'DD-MON-YYYY'), 'dd-mon-yyyy')
    SHIP_BUY.INSERT_DATE > '1-JAN-2007'
    Like I said in your other thread about this, these two lines need to be fixed and your function needs to be fixed so the return statement doesn't do an implicit date conversion.
    Can't you see what that first line is doing?  You're taking a character string, turning it into a date, then back to a character string.
    If nothing else, these lines should be...
    F_GET_POD_RECEIVED_DATE (ship_BUY.SHIPMENT_GID)  <= to_date('31-JUL-2013', 'DD-MON-YYYY')
    SHIP_BUY.INSERT_DATE > to_date('01-JAN-2007','DD-MON-YYYY')
    (assuming insert_date is a proper date format, fingers crossed)

  • Please help me to solve the issue in my query.

    Hi All,
    Please help me to understand the mistake what i did in below query and help to resolve that.
    Actually i am trying to create a query to filter the records from db based on my input parameter.
       If my input parameter is 1(@showallrecords) then i need to show all the records which has the IsLatest as 1
       If my input parameter is 0(@showallrecords) then i need to show all the records which has the IsLatest as 0
    select * from tabel1 INNER JOIN tabel2    
    ON tabel1.KeyId = tabel2.KeyId 
    and (@showallrecords = 1 and tabel1.IsLatest = 1 )
    and (@showallrecords = 0 and tabel1.IsLatest = 0 )
    when i am executing the above query with the parameter @showallrecords = 1 ,db is returning 0 rows.If i am executing the above query after removed the last line and (@showallrecords = 0 and tabel1.IsLatest = 0 ) then records are coming.
    i understand that 1=0(last line) and the condition is not true.So its affecting the result.
    Please help me to solve this.

    select * from tabel1 INNER JOIN tabel2
    ON tabel1.KeyId = tabel2.KeyId
    WHERE (tabel1.IsLatest = @showallrecords Or @showallrecords=0)

  • Need help with query that can look data back please help.

    hi guys i have a table like such
    CREATE TABLE "FGL"
        "FGL_GRNT_CODE" VARCHAR2(60),
        "FGL_FUND_CODE" VARCHAR2(60),
        "FGL_ACCT_CODE" VARCHAR2(60),
        "FGL_ORGN_CODE" VARCHAR2(60),
        "FGL_PROG_CODE" VARCHAR2(60),
        "FGL_GRNT_YEAR" VARCHAR2(60),
        "FGL_PERIOD"    VARCHAR2(60),
        "FGL_BUDGET"    VARCHAR2(60)
      )and i have a data like such
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7600','4730','02','11','1','400');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7600','4730','02','10','1','100');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7240','4730','02','10','1','0');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7240','4730','02','10','14','200');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7600','4730','02','10','14','100');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7600','4730','02','10','2','100');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7470','4730','02','10','2','200');I bascially need to get the total of the budget column. however its not as simple as it sound(well atleast not for me.) the totals carry over to the new period. youll noticed the you have a period column. basically what im saying is that
    fgl_grant_year 10 period 1 = for account 7600 its $100 and $100 for period 2 you see 100 dollars again this is not to be added this is the carried over balance. which remains $100.
    so im trying to write a query that basically does the following.
    im given a period for the sake of this example lets say period 1 i get nothing else. I have to find the greates grant year grab the amount for period 14(which is the total from the previous year) and add it to the amount of the current period. in this case period 1 grnt_year 11
    so the expected outcome should be $700
    240055     240055     7240     4730     02     10     14     200
    240055     240055     7600     4730     02     10     14     100
    240055     240055     7600     4730     02     11     1     400keep in mind that im not given a year just a period.
    any help that you guys can offer would be immensely appreciated. I have been trying to get this to work for over 3 days now.
    finally broke down and put together this post
    Edited by: mlov83 on Sep 14, 2011 8:48 PM

    Frank
    wondering if you can help me modify this sql statement that you provided me with .
    table values have been modified a bit.
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7600','4730','02','11','00','400');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7240','4730','02','10','1','100');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7240','4730','02','10','1','0');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7600','4730','02','11','1','400');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('360055','360055','7200','4730','02','10','1','400');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('360055','360055','7600','4730','02','10','1','400');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7240','4730','02','10','14','200');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7600','4730','02','10','14','100');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7240','4730','02','10','14','200');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7240','4730','02','10','2','100');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7240','4730','02','11','2','600');i need to take one more thing into consideration. if the greatest year has a value on period 00 i need to ignore the period 14 and the current period total would be
    the current period +(current period - greatest year 00)
    hope that makes sense so in other words with the new data above. if i was querying period two of grant year 11. i would end up with $800
    because the greatest year is 11 it contains a period 0 with amount of $400 so my total should be
    period 2 amount $ 600
    period 0 amount $ 400 - period 2 amount of $600 = 200
    600+200 = $800
    if i query period 1 of grant 360055 i would just end up with 800 of grnt year 10.
    i have tried to modify that query you supplied to me with no luck. I have tried for several day but im embarrased to say i just can get it to do what im trying to do .
    can you please help me out.
    Miguel

  • Can you please help me write below query in efficient way

    Hello-
    I have wrote one query and its very slow to get the data because i am counting the code at every column from the table in from clause.
    SELECT SUM(diag_total) diag_total,
    SUM(diag_complete) diag_complete,
    SUM(diag_remaining) diag_remaining,
    SUM(diag_declined) diag_declined
    FROM (SELECT hpc.dmpc_hicn,(SELECT COUNT(DISTINCT d.msd_icd9_ref)
    FROM d4c_map_suspects_to_diagnosis d
    WHERE trim(d.msd_sd_hicn) = trim(hpc.dmpc_hicn)) diag_total,
    (SELECT COUNT(DISTINCT dd.dspd_icd9)
    FROM d4c_suspect_provider_diagnosis dd
    WHERE dd.dspd_ds_id_ref = 1000
    AND trim(dd.dspd_hicn) = trim(hpc.dmpc_hicn)
    AND trim(dd.dspd_npi) = trim(hpc.dpmc_provider_no)) diag_complete,
    -- AND hpc.dmpc_ss_id_ref = 1020) diag_complete,
    (SELECT COUNT(DISTINCT dd.dspd_icd9)
    FROM d4c_suspect_provider_diagnosis dd
    WHERE dd.dspd_ds_id_ref = 1010
    AND trim(dd.dspd_hicn) = trim(hpc.dmpc_hicn)
    AND trim(dd.dspd_npi) = trim(hpc.dpmc_provider_no)) diag_remaining,
    -- AND hpc.dmpc_ss_id_ref = 1020) diag_remaining,
    (SELECT COUNT(DISTINCT dd.dspd_icd9)
    FROM d4c_suspect_provider_diagnosis dd
    WHERE dd.dspd_ds_id_ref = 1020
    AND trim(dd.dspd_hicn) = trim(hpc.dmpc_hicn)
    AND trim(dd.dspd_npi) = trim(hpc.dpmc_provider_no)) diag_declined
    --AND hpc.dmpc_ss_id_ref = 1020) diag_declined
    FROM d4c_provider_assignment pc, d4c_hicn_provider_claims hpc
    WHERE pc.pa_assignedto = &imrrid
    AND trim(pc.pa_providerid) = trim(hpc.dpmc_provider_no));
    Can you please help me in this?
    Thanks in advance.
    Kind regards,
    Nik

    May be this?
    You dont even need sum as we are doing count for the whole data at a time. Please check the results and let us know if there is any issue.
    SELECT COUNT (DISTINCT d.msd_icd9_ref) diag_total
          ,COUNT (DISTINCT CASE WHEN dd.dspd_ds_id_ref = 1000 THEN dd.dspd_icd9 END) diag_complete
          ,COUNT (DISTINCT CASE WHEN dd.dspd_ds_id_ref = 1010 THEN dd.dspd_icd9 END) diag_remaining
          ,COUNT (DISTINCT CASE WHEN dd.dspd_ds_id_ref = 1020 THEN dd.dspd_icd9 END) diag_declined
      FROM d4c_provider_assignment pc
          ,d4c_hicn_provider_claims hpc
          ,d4c_suspect_provider_diagnosis dd
          ,d4c_map_suspects_to_diagnosis d
    WHERE     pc.pa_assignedto = &imrrid
           AND TRIM (pc.pa_providerid) = TRIM (hpc.dpmc_provider_no)
           AND TRIM (dd.dspd_hicn(+)) = TRIM (hpc.dmpc_hicn)
           AND TRIM (dd.dspd_npi(+)) = TRIM (hpc.dpmc_provider_no)
           AND TRIM (d.msd_sd_hicn(+)) = TRIM (hpc.dmpc_hicn);

  • I need to pass a query in form of string to DBMS_XMLQUERY.GETXML package...the parameters to the query are date and varchar ..please help me..

    I need to pass a query in form of string to DBMS_XMLQUERY.GETXML package...the parameters to the query are date and varchar ..please help me build the string .Below is the query and the out put. ( the string is building fine except the parameters are with out quotes)
    here is the procedure
    create or replace
    procedure temp(
        P_MTR_ID VARCHAR2,
        P_FROM_DATE    IN DATE ,
        P_THROUGH_DATE IN DATE ) AS
        L_XML CLOB;
        l_query VARCHAR2(2000);
    BEGIN
    l_query:=  'SELECT
        a.s_datetime DATETIME,
        a.downdate Ending_date,
        a.downtime Ending_time,
        TO_CHAR(ROUND(a.downusage,3),''9999999.000'') kWh_Usage,
        TO_CHAR(ROUND(a.downcost,2),''$9,999,999.00'') kWh_cost,
        TO_CHAR(ROUND(B.DOWNUSAGE,3),''9999999.000'') KVARH
      FROM
        (SELECT s_datetime + .000011574 s_datetime,
          TO_CHAR(S_DATETIME ,''mm/dd/yyyy'') DOWNDATE,
          DECODE(TO_CHAR(s_datetime+.000011574 ,''hh24:'
          ||'mi''), ''00:'
          ||'00'',''24:'
          ||'00'', TO_CHAR(s_datetime+.000011574,''hh24:'
          ||'mi'')) downtime,
          s_usage downusage,
          s_cost downcost
        FROM summary_qtrhour
        WHERE s_mtrid = '
        ||P_MTR_ID||
       ' AND s_mtrch   = ''1''
        AND s_datetime BETWEEN TO_DATE('
        ||P_FROM_DATE||
        ',''DD-MON-YY'') AND (TO_DATE('
        ||P_THROUGH_DATE||
        ',''DD-MON-YY'') + 1)
        ) a,
        (SELECT s_datetime + .000011574 s_datetime,
          s_usage downusage
        FROM summary_qtrhour
        WHERE s_mtrid = '
        ||P_MTR_ID||
        ' AND s_mtrch   = ''2''
        AND s_datetime BETWEEN TO_DATE('
        ||P_FROM_DATE||
        ',''DD-MON-YY'') AND (TO_DATE('
        ||P_THROUGH_DATE||
        ','' DD-MON-YY'') + 1)
        ) B
      where a.S_DATETIME = B.S_DATETIME(+)';
    SELECT DBMS_XMLQUERY.GETXML('L_QUERY') INTO L_XML   FROM DUAL;
    INSERT INTO NK VALUES (L_XML);
    DBMS_OUTPUT.PUT_LINE('L_QUERY IS :'||L_QUERY);
    END;
    OUTPUT parameters are in bold (the issue is they are coming without single quotes otherwise th equery is fine
    L_QUERY IS :SELECT
        a.s_datetime DATETIME,
        a.downdate Ending_date,
        a.downtime Ending_time,
        TO_CHAR(ROUND(a.downusage,3),'9999999.000') kWh_Usage,
        TO_CHAR(ROUND(a.downcost,2),'$9,999,999.00') kWh_cost,
        TO_CHAR(ROUND(B.DOWNUSAGE,3),'9999999.000') KVARH
      FROM
        (SELECT s_datetime + .000011574 s_datetime,
          TO_CHAR(S_DATETIME ,'mm/dd/yyyy') DOWNDATE,
          DECODE(TO_CHAR(s_datetime+.000011574 ,'hh24:mi'), '00:00','24:00', TO_CHAR(s_datetime+.000011574,'hh24:mi')) downtime,
          s_usage downusage,
          s_cost downcost
        FROM summary_qtrhour
        WHERE s_mtrid = N3165 AND s_mtrch   = '1'
        AND s_datetime BETWEEN TO_DATE(01-JAN-13,'DD-MON-YY') AND (TO_DATE(31-JAN-13,'DD-MON-YY') + 1)
        ) a,
        (SELECT s_datetime + .000011574 s_datetime,
          s_usage downusage
        FROM summary_qtrhour
        WHERE s_mtrid = N3165 AND s_mtrch   = '2'
        AND s_datetime BETWEEN TO_DATE(01-JAN-13,'DD-MON-YY') AND (TO_DATE(31-JAN-13,' DD-MON-YY') + 1)
        ) B
      where a.S_DATETIME = B.S_DATETIME(+)

    The correct way to handle this is to use bind variables.
    And use DBMS_XMLGEN instead of DBMS_XMLQUERY :
    create or replace procedure temp (
      p_mtr_id       in varchar2
    , p_from_date    in date
    , p_through_date in date
    is
      l_xml   CLOB;
      l_query VARCHAR2(2000);
      l_ctx   dbms_xmlgen.ctxHandle;
    begin
      l_query:=  'SELECT
        a.s_datetime DATETIME,
        a.downdate Ending_date,
        a.downtime Ending_time,
        TO_CHAR(ROUND(a.downusage,3),''9999999.000'') kWh_Usage,
        TO_CHAR(ROUND(a.downcost,2),''$9,999,999.00'') kWh_cost,
        TO_CHAR(ROUND(B.DOWNUSAGE,3),''9999999.000'') KVARH
      FROM
        (SELECT s_datetime + .000011574 s_datetime,
          TO_CHAR(S_DATETIME ,''mm/dd/yyyy'') DOWNDATE,
          DECODE(TO_CHAR(s_datetime+.000011574 ,''hh24:'
          ||'mi''), ''00:'
          ||'00'',''24:'
          ||'00'', TO_CHAR(s_datetime+.000011574,''hh24:'
          ||'mi'')) downtime,
          s_usage downusage,
          s_cost downcost
        FROM summary_qtrhour
        WHERE s_mtrid = :P_MTR_ID
        AND s_mtrch   = ''1''
        AND s_datetime BETWEEN TO_DATE(:P_FROM_DATE,''DD-MON-YY'')
                           AND (TO_DATE(:P_THROUGH_DATE,''DD-MON-YY'') + 1)
        ) a,
        (SELECT s_datetime + .000011574 s_datetime,
          s_usage downusage
        FROM summary_qtrhour
        WHERE s_mtrid = :P_MTR_ID
        AND s_mtrch   = ''2''
        AND s_datetime BETWEEN TO_DATE(:P_FROM_DATE,''DD-MON-YY'')
                           AND (TO_DATE(:P_THROUGH_DATE,'' DD-MON-YY'') + 1)
        ) B
      where a.S_DATETIME = B.S_DATETIME(+)';
      l_ctx := dbms_xmlgen.newContext(l_query);
      dbms_xmlgen.setBindValue(l_ctx, 'P_MTR_ID', p_mtr_id);
      dbms_xmlgen.setBindValue(l_ctx, 'P_FROM_DATE', to_char(p_from_date, 'DD-MON-YY'));
      dbms_xmlgen.setBindValue(l_ctx, 'P_THROUGH_DATE', to_char(p_through_date, 'DD-MON-YY'));
      l_xml := dbms_xmlgen.getXML(l_ctx);
      dbms_xmlgen.closeContext(l_ctx);
      insert into nk values (l_xml);
    end;

  • Query Issue in Creating a View....Please help me with this query..

    I would like to create a view on this table with four columns
    1. PN#_EXP_DATE
    2. PN#
    3. PN#_EFF_DATE
    4. PN#
    P_S_C     A_C     P     EXP_DT
    21698     13921     1     5/29/2009 3:15:41 PM     
    21698     13921     1     5/29/2009 3:54:57 PM     
    21698     1716656     4     5/29/2009 3:15:41 PM     
    21698     3217     3     5/29/2009 3:15:40 PM     
    21698     3217     3     5/29/2009 3:54:57 PM     
    21698     60559     2     5/29/2009 3:15:41 PM     
    21698     60559     2     5/29/2009 3:54:57 PM     
    I have a trigger on A, which inserts the DML records into B. (Table A and B structure is the almost the same,
                                       where table B will have one extra column exp_dt)
    NOw Table B can have records with same P_S_C and A_C columns and exp_dt will capture the history.
    for example: from the above sample data, let us take first two records..
    P_S_C     A_C     P     EXP_DT
    21698     13921     1     5/29/2009 3:15:41 PM     --- Record 1
    21698     13921     1     5/29/2009 3:54:57 PM     --- Record 2
    from this..
    Note: 1. Table A and Table C can be joined using A.P_S_C and C.R_C to get the start_date.
    2. PN# comes from table D. It contains numbers for the resp. weeks.
    3. PN#_EFF_DATE is the previous immediate previous date for that record in history table (Table B).
    I wanted the data like..
    ---- this is for the second record in the above..
    PN#_EXP_DATE PN# PN#_EFF_DATE PN#
    5/29/2009 3:54:57 PM     214 5/29/2009 3:15:41 PM     214
    ---- this is for the first record in the above..
    PN#_EXP_DATE PN# PN#_EFF_DATE PN#
    5/29/2009 3:54:41 PM     214 ( for this we should query the table C to get the
                        start_date, for this combinatation of P_S_C and A_C in table B
                             where B.P_S_C = C.A_C
                             and that value should be the EFF_DT for this record)
    Please help me with this....
    Thanks in advance..

    Hi All,
    select d.P# as "PN#_EXP_DATE", exp_date
    from daily_prd d, cbs1_assoc_hist b
    where to_char(d.day_date,'MM/DD/YYYY') = to_char(b.exp_date,'MM/DD/YYYY')
    and d.period_type = 'TIMEREPORT';
    This above query gives the output as follows:
    pn#_exp_date exp_date
    214     5/29/2009 3:15:40 PM
    214     5/29/2009 3:15:41 PM
    214          5/29/2009 3:15:41 PM
    214          5/29/2009 3:15:41 PM
    214          5/29/2009 3:54:57 PM
    214          5/29/2009 3:54:57 PM
    214          5/29/2009 3:54:57 PM
    This below is the data from history table (Table B).
    P_S_C     A_C PLACE EXP_DATE
    21698          3217          3     5/29/2009 3:15:40 PM     
    21698          13921          1     5/29/2009 3:15:41 PM     
    21698          1716656          4     5/29/2009 3:15:41 PM     
    21698          60559          2     5/29/2009 3:15:41 PM     
    21698          13921          1     5/29/2009 3:54:57 PM     
    21698          3217          3     5/29/2009 3:54:57 PM     
    21698          60559          2     5/29/2009 3:54:57 PM     
    I got the pn#_exp_date from the Table 'D', for the given exp_date from Table B.
    My question is again....
    CASE - 1
    from the given records above, I need to look for exp_date for the given same P_S_C and A_C.
    in this case we can take the example...
    P_S_C     A_C PLACE EXP_DATE
    21698          3217          3     5/29/2009 3:15:40 PM
    21698          3217          3     5/29/2009 3:54:57 PM
    In this case, the
    pn#_exp_date exp_date     pn#_eff_date eff_date
    214     5/29/2009 3:15:57 PM     < PN# corresponding to the     5/29/2009 3:15:40 PM
                        eff_date .>
                        <Basically the eff_date is
                        nothing but the exp_date only.
                        we should take the immediate before one.
    In this case, our eff_date is '5/29/2009 3:15:40 PM'.
    but how to get this.
    CASE - 2
    from the above sample data, consider this
    P_S_C     A_C PLACE EXP_DATE
    21698     1716656     4     5/29/2009 3:15:41 PM
    In this case, there is only one record for the P_S_C and A_C combination.
    The expected result :
    pn#_exp_date exp_date               pn#_eff_date eff_date
    214     5/29/2009 3:15:41 PM     < PN# corresponding to the     5/29/2009 3:15:40 PM
                        eff_date .>
                   <Basically the eff_date is
                   nothing but the exp_date only.
                        we should take the immediate before one.
    In this case to get the eff_date, we should query the Table 'C', to get the eff_date, which is START_DT column in this table.
    for this join B.P_S_C and C.R_C.
    Hope I am clear now..
    Thanks in advance.....

Maybe you are looking for

  • Mail w/attachments are received in body of mail

    I have an imac G5, Mac OS X (10.5.8), mail 3.6.  When I send an e-mail with an attachment, either a photo or a document, to a PC user, old or new, the attachment is received and shown in the body of the mail.  There IS NO attachment;  NO paper clip; 

  • How to use rollover function to trigger a video demo

    What I have done so far? Imported a PowerPoint slide and I created a Rollover caption. When exploring the properties for the Rollover, under the Action field:- On Success row, chose Open Another Project  Project row, uploaded the the file abc.cptx th

  • How do I get rid of the question marks in my emails

    I run a business on my computer & I have serveral people tell me that when they get my emails, it has a lot of question marks all thoughout the message. sometimes other symbols as well. It makes me look as if I am really confused when I am sending my

  • How can i put a tracker on my phone after i lost it

    i had lost my phone and i dont have a tracker on it is there any way i can put a tracker on my phone while its lost to find it

  • How to load image in Long Raw column?

    Dear all, I need to upload a jpg image to a Long Raw column in one of our tables. Is there a way or utility so that I can do this thru a PL/SQL code? Please help. Regards, Amit