Sql query ..need idea to write complex query

Hi there,
I have assigned the task to write a sql query to get the output as the below stored proc does.
In the proc conditions are given with IF statements. I really dont know how to give all the conditions for the period in a single sql query as I'm not much used to sql quries.
Is anyone could help me?
Any suggestions pls . writing complicated query is nightmare. no idea . if possible help me...
create or replace PROCEDURE vpp_station_summary_report (
in_user_id                     IN  VARCHAR2,
in_report_id      IN  NUMBER,
in_time_from                IN      vppstation.avi_status_history.status_eff_date%TYPE,
in_time_to                  IN  vppstation.avi_status_history.status_eff_date%TYPE,
result                               OUT SYS_REFCURSOR)
AS
CURSOR station_loop IS
   SELECT ash.station_id,
          ash.avi_id,
          ash.state_id,
          ash.state_eff_date
   FROM   vppstation.avi_state_history ash
   JOIN   vpproadside.vpp_report_stations
     ON   vpp_report_stations.station_id             = ash.station_id
    AND   vpp_report_stations.vpp_report_seq_number  = in_report_id
   WHERE  ash.state_eff_date BETWEEN in_time_from AND in_time_to
   ORDER BY ash.station_id,
            ash.avi_id,
            ash.state_eff_date,
            ash.ash_id;
-- cursor to find the 'entry state' i.e. the state the AVI was in AT the time of
-- in_time_from
CURSOR entry_state (
          state_station_id vppstation.avi_state_history.station_id%TYPE,
          state_avi_id     vppstation.avi_state_history.avi_id%TYPE,
          state_state_date vppstation.avi_state_history.state_eff_date%TYPE
IS
   SELECT ash.state_id
   FROM   vppstation.avi_state_history ash
   WHERE  ash.station_id = state_station_id
     AND  ash.avi_id = state_avi_id
     AND  ash.state_eff_date < state_state_date
   ORDER BY ash.state_eff_date DESC,
            ash.ash_id DESC;
current_station_id         vppstation.avi_state_history.station_id%TYPE;
current_avi_id             vppstation.avi_state_history.avi_id%TYPE;
current_state_id           vppstation.avi_state_history.state_id%TYPE;
current_state_eff_date     vppstation.avi_state_history.state_eff_date%TYPE;
period_length NUMBER;
next_station_id     vppstation.avi_state_history.station_id%TYPE;
next_avi_id         vppstation.avi_state_history.avi_id%TYPE;
next_state_id       vppstation.avi_state_history.state_id%TYPE;
next_state_eff_date vppstation.avi_state_history.state_eff_date%TYPE;
station_open_total       NUMBER;
station_closed_total     NUMBER;
station_all_report_total NUMBER;
current_station_name vpproadside.vpp_station_summary.station_name%TYPE;
state_open       vppstation.avi_control_state_code.state_id%TYPE;
state_closed     vppstation.avi_control_state_code.state_id%TYPE;
state_all_report vppstation.avi_control_state_code.state_id%TYPE;
BEGIN
SELECT state_id
INTO   state_open
FROM   vppstation.avi_control_state_code
WHERE  state_type = 'E'
AND    state_active_ind = 'A';
SELECT state_id
INTO   state_closed
FROM   vppstation.avi_control_state_code
WHERE  state_type = 'D'
AND    state_active_ind = 'A';
SELECT state_id
INTO   state_all_report
FROM   vppstation.avi_control_state_code
WHERE  state_type = 'S'
AND    state_active_ind = 'A';
current_station_id := -1;
current_avi_id     := -1;
current_state_id   := state_closed;
current_state_eff_date := in_time_from;
station_open_total       := 0.0;
station_closed_total     := 0.0;
station_all_report_total := 0.0;
-- for starters - ensure that there is report data for all requested stations...
INSERT INTO vpproadside.vpp_station_summary
      vpp_report_seq_number,
      station_id,
      station_name,
      ln_number,
      lane_name,
      station_open,
      station_close,
      station_all_report,
      station_total
  SELECT in_report_id,
         vrs.station_id,
         si.station_name,
         l.ln_number,
         l.lane_name,
         0.0,
         0.0,
         0.0,
         0.0
  FROM vpproadside.vpp_report_stations vrs
  LEFT OUTER JOIN  vpproadside.stations_installed si
    ON  si.station_id = vrs.station_id
  LEFT OUTER JOIN vppstation.lane_name l
    ON l.station_id = vrs.station_id
  WHERE vrs.vpp_report_seq_number  = in_report_id;
-- loop over state history and update information for all stations found
OPEN station_loop;
LOOP
  FETCH station_loop
  INTO
        next_station_id,
        next_avi_id,
        next_state_id,
        next_state_eff_date;
  IF station_loop%NOTFOUND THEN
    next_station_id := -1;
    next_avi_id     := -1;
  END IF;
  -- if station/avi has changed take the end of the report period
  IF    (next_station_id <> current_station_id)
     OR (next_avi_id     <> current_avi_id)
  THEN
    period_length := in_time_to - current_state_eff_date;
  ELSE
    -- otherwise the start of the next period marks the end of the current period
    period_length := next_state_eff_date - current_state_eff_date;
  END IF;
  -- if we have a real station id then do some work...
  IF (current_station_id <> -1) THEN
    -- determine which category the period fits to and apply calculation
    IF current_state_id = state_open THEN
      station_open_total := station_open_total + period_length - 1;
    ELSIF current_state_id = state_closed THEN
      station_closed_total := station_closed_total + period_length - 1;
    ELSIF current_state_id = state_all_report THEN
      station_all_report_total := station_all_report_total + period_length - 1;
    ELSE
      RAISE_APPLICATION_ERROR(-20111, 'Error: found unknown state code on avi_state_history - ' || current_state_id );
    END IF;
    -- if the station/avi has changed then commit changes to db
    IF    (next_station_id <> current_station_id)
       OR (next_avi_id     <> current_avi_id)
    THEN
      UPDATE vpproadside.vpp_station_summary
      SET
          station_open       = station_open_total,
          station_close      = station_closed_total,
          station_all_report = station_all_report_total
      WHERE vpp_report_seq_number = in_report_id
      AND   station_id = current_station_id
      AND   ln_number  = current_avi_id;
      -- reset counts
      station_open_total       := 0.0;
      station_closed_total     := 0.0;
      station_all_report_total := 0.0;
    END IF;
  END IF;
  -- if we got past the last record then stop processing
  EXIT WHEN station_loop%NOTFOUND;
  -- if the station/avi is changing, get the state that was 'current' at in_time_from
  IF    (next_station_id <> current_station_id)
     OR (next_avi_id     <> current_avi_id)
  THEN
    current_state_eff_date := in_time_from;
    OPEN entry_state (
           next_station_id,
           next_avi_id,
           in_time_from
    FETCH entry_state
    INTO  current_state_id;
    IF entry_state%NOTFOUND THEN
      current_state_id := state_closed;
    END IF;
    CLOSE entry_state;
    period_length := next_state_eff_date - current_state_eff_date;
    IF current_state_id = state_open THEN
      station_open_total := station_open_total + period_length;
    ELSIF current_state_id = state_closed THEN
      station_closed_total := station_closed_total + period_length;
    ELSIF current_state_id = state_all_report THEN
      station_all_report_total := station_all_report_total + period_length;
    ELSE
        RAISE_APPLICATION_ERROR(-20111, 'Error: found unknown state code on avi_state_history - ' || current_state_id );
    END IF;
  END IF;
  current_state_id       := next_state_id;
  current_state_eff_date := next_state_eff_date;
  current_station_id     := next_station_id;
  current_avi_id         := next_avi_id;
END LOOP;
CLOSE station_loop;
-- update the totals for the percentage calculation
UPDATE vpproadside.vpp_station_summary
SET
       station_total = station_open + station_close+ station_all_report
WHERE   vpp_report_seq_number = in_report_id;
-- 'fix' the totals that are still zero to avoid divide by zero errors...
--       note: all the percentages will still come out as zero since the total
--             was zero
UPDATE vpproadside.vpp_station_summary
SET
       station_total = 1.0
WHERE  vpp_report_seq_number = in_report_id
AND    station_total = 0.0;
OPEN result FOR
SELECT station_name "Site Name",
       lane_name    "Lane Name",
       TO_CHAR((station_open       / station_total) * 100.0, 'FM990.0999') || '%' "Open %",
       TO_CHAR((station_close      / station_total) * 100.0, 'FM990.0999') || '%' "Closed %",
       TO_CHAR((station_all_report / station_total) * 100.0, 'FM990.0999') || '%' "All Report %"
FROM vpproadside.vpp_station_summary
WHERE vpp_report_seq_number = in_report_id
ORDER BY UPPER(station_name),
         UPPER(lane_name);
DELETE FROM vpproadside.vpp_station_summary
WHERE vpp_report_seq_number = in_report_id;
END;Edited by: Indhu Ram on Mar 10, 2010 9:51 AM
Edited by: Indhu Ram on Mar 10, 2010 9:56 AM
Edited by: Indhu Ram on Mar 10, 2010 10:58 AM
Edited by: Indhu Ram on Mar 10, 2010 11:12 AM

Exactly dont know what you are asking for but I can suggest you some tips here
- If you want to check the condition in SQL query then you can use CASE statement into select clause i.e.
SELECT CASE when table1.a=table2.b then table1.c else table2.c END, ... more case..., table columns...
FROM table1, table2
WHERE
<some conditions>
- If you want to achive same functionality (SELECT only, not UPDATE/INSERT/DELETE) then you can convert the part of same procedure into function and can use the same function into your query by passing the parameters.
something like this
SELECT function_name(parameter1, parameter2....) from dual
Hope this will help

Similar Messages

  • Need to write SQL query for hierarchy

    Hi Guys,
    I need help to write a query for the below scenario.
    I have one organization, under that I have many branches. when i provide input to query on last branch, i need to display all parents of that branch like below
    Organization   ---parent
      branch 1  ---child
         branch11
         branch 12
        branch 2   ---child
          branch 21
         branch 3 ----child
          branch 31
          branch 32
          branch 33
    here, when i provide input as branch 3, then I need to fetch results branch 2, branch 1 till organization.
    can any one help me on this.
    Thanks in advance!
    Regards,
    LKR

    Hi,
    Is this the same question as
    https://community.oracle.com/thread/2616828
    Please don't post the same question over and over.  Mark this thread as "Answered" right away, and continue in the other thread (if necessary; the other thread has answers.)

  • Need to adjust SQL query for left outer join in Crystal Reports 2008.

    I need to change this SQL 2005 query.....
    SELECT     omnicell_anl.DeviceIDsLastMetricTable.member_id, omnicell_anl.DeviceIDsLastMetricTable.[Device Name],
                          omnicell_anl.DeviceIDsLastMetricTable.Account, omnicell_anl.labeledLastMetrics.PROPERTY_NAME,
                          omnicell_anl.labeledLastMetrics.latest_monitor_value
    FROM         omnicell_anl.DeviceIDsLastMetricTable LEFT OUTER JOIN
                          omnicell_anl.labeledLastMetrics ON omnicell_anl.DeviceIDsLastMetricTable.member_id = omnicell_anl.labeledLastMetrics.member_id
    WHERE
        omnicell_anl.labeledLastMetrics.PROPERTY_NAME = ?MyProperty
    To this query in Crystal Reports Report Writer:
    SELECT     omnicell_anl.DeviceIDsLastMetricTable.member_id, omnicell_anl.DeviceIDsLastMetricTable.[Device Name],
                          omnicell_anl.DeviceIDsLastMetricTable.Account, omnicell_anl.labeledLastMetrics.PROPERTY_NAME,
                          omnicell_anl.labeledLastMetrics.latest_monitor_value
    FROM         omnicell_anl.DeviceIDsLastMetricTable LEFT OUTER JOIN
                          omnicell_anl.labeledLastMetrics ON omnicell_anl.DeviceIDsLastMetricTable.member_id = omnicell_anl.labeledLastMetrics.member_id AND
                          omnicell_anl.labeledLastMetrics.PROPERTY_NAME = ?MyProperty
    I can't seem to get the left outer join function of Crystal Reports to emulate the same SQL query in SQL 2005.  Any ideas on how I can create this same query in Crystal 2008?
    Thanks,
    Dominic
    Edited by: Dominic Carissimi on Oct 28, 2008 7:55 PM
    Edited by: Dominic Carissimi on Oct 28, 2008 7:56 PM

    If you want the list of values for command level parameter then you need to add another command like
    select PropertyField from table
    and delete the links between this command and the existing command.
    Now go to field explorer and edit the command level parameter and make it as dynamic and add the property field from newly added command.
    Hope this helps!
    Raghavendra

  • XML Generation using a sql query in an efficient way -Help needed urgently

    Hi
    I am facing the following issue while generating xml using an sql query. I get the below given table using a query.
         CODE      ID      MARK
    ==================================
    1 4 2331 809
    2 4 1772 802
    3 4 2331 845
    4 5 2331 804
    5 5 2331 800
    6 5 2210 801
    I need to generate the below given xml using a query
    <data>
    <CODE>4</CODE>
    <IDS>
    <ID>2331</ID>
    <ID>1772</ID>
    </IDS>
    <MARKS>
    <MARK>809</MARK>
    <MARK>802</MARK>
    <MARK>845</MARK>
    </MARKS>
    </data>
    <data>
    <CODE>5</CODE>
    <IDS>
    <ID>2331</ID>
    <ID>2210</ID>
    </IDS>
    <MARKS>
    <MARK>804</MARK>
    <MARK>800</MARK>
    <MARK>801</MARK>
    </MARKS>
    </data>
    Can anyone help me with some idea to generate the above given CLOB message

    not sure if this is the right way to do it but
    /* Formatted on 10/12/2011 12:52:28 PM (QP5 v5.149.1003.31008) */
    WITH data AS (SELECT 4 code, 2331 id, 809 mark FROM DUAL
                  UNION
                  SELECT 4, 1772, 802 FROM DUAL
                  UNION
                  SELECT 4, 2331, 845 FROM DUAL
                  UNION
                  SELECT 5, 2331, 804 FROM DUAL
                  UNION
                  SELECT 5, 2331, 800 FROM DUAL
                  UNION
                  SELECT 5, 2210, 801 FROM DUAL)
    SELECT TO_CLOB (
                 '<DATA>'
              || listagg (xml, '</DATA><DATA>') WITHIN GROUP (ORDER BY xml)
              || '</DATA>')
              xml
      FROM (  SELECT    '<CODE>'
                     || code
                     || '</CODE><IDS><ID>'
                     || LISTAGG (id, '</ID><ID>') WITHIN GROUP (ORDER BY id)
                     || '</ID><IDS><MARKS><MARK>'
                     || LISTAGG (mark, '</MARK><MARK>') WITHIN GROUP (ORDER BY id)
                     || '</MARK></MARKS>'
                        xml
                FROM data
            GROUP BY code)

  • Need help in Report From SQL Query

    Hi All,
    I am facing a problem with a report. I need your help.
    I am creating a Report From SQL Query (Portal) with some arguments passed at runtime. I am able to view the output, if the query returns few rows ( arount 1000 rows). But for some inputs it needs to generate >15000 records, at this point the page is getting time out (i think!) and showing error page. I am able to execute query from the SQL Plus console ot using TOAD editor. Here the query is not taking more that 2 mins time to show the result.
    If i am executing from Portal i observed that, once i give the appropriate input and hit submit button a new oracle process is getting created for the query on UNIX (I am usign "TOP" command to check processes). The browser page will be shown error page after 5 minutes (i am assuming session time out!) , but on the backend the process will be executed for more than 30 mins.
    I tried also increase the page time out in httpd.conf, but no use.
    The data returned as a result of the query is sized more than 10 MB. Is caching this much data is possible by the browser page? is the returned data is creating any problem here.
    Please help me to find appropriate reasone for the failure?

    user602513 wrote:
    Hi All,
    I am facing a problem with a report. I need your help.
    I am creating a Report From SQL Query (Portal) with some arguments passed at runtime. I am able to view the output, if the query returns few rows ( arount 1000 rows). But for some inputs it needs to generate >15000 records, at this point the page is getting time out (i think!) and showing error page. I am able to execute query from the SQL Plus console ot using TOAD editor. Here the query is not taking more that 2 mins time to show the result.
    If i am executing from Portal i observed that, once i give the appropriate input and hit submit button a new oracle process is getting created for the query on UNIX (I am usign "TOP" command to check processes). The browser page will be shown error page after 5 minutes (i am assuming session time out!) , but on the backend the process will be executed for more than 30 mins.
    I tried also increase the page time out in httpd.conf, but no use.
    The data returned as a result of the query is sized more than 10 MB. Is caching this much data is possible by the browser page? is the returned data is creating any problem here.
    Please help me to find appropriate reasone for the failure?Do you get any errors or warnings or it is just the slow speed which is the issue?
    There could be a variety of reasons for the delayed processing of this report. That includes parameter settings for that page, cache settings, network configurations, etc.
    - explore best optimization for your query;
    - evaluate portal for best performance configuration; you may follow this note (Doc ID: *438794.1* ) for ideas;
    - third: for that particular page carrying that report, you can use caching wisely. browser cache is neither decent for large files, nor practical. instead, explore the page cache settings that portal provides.
    - also look for various log files (application.log and apache logs) if you are getting any warnings reflecting on some kind of processing halt.
    - and last but not the least: if you happen to bring up a portal report with more than 10000 rows for display then think about the usage of the report. Evaluate whether that report is good/useful for anything?
    HTH
    AMN

  • Need Help in SQL Query

    Hi all,
    I have data in the following manner:
    CASE_NUMBER HOURS FLAG
    1000 10 0
    1000 20 0
    1000 30 1
    1000 40 0
    1000 50 1
    Here I need to Calculate the total hours for a Case_number till i see the flag as 1.
    Here the result must be 10+20+30 Hrs
    Another Example
    CASE_NUMBER HOURS FLAG
    2000 10 1
    2000 20 1
    Here the result must be only 10.
    I am struggling to write a SQL query for this.
    Anyones help will be very much greatful
    Thanks in Advance
    Regards,
    Sengathir Subbarayan

    Look up analytical functions.
    something like sum(hours) OVER (PARTITION BY case_number ORDER BY something)
    will give you the sum for all rows.
    Then you probably want to "throw away" those rows after the flag maybe by summing the flag column too, and throw away all those where the flag is greater than 1 and where it is equal to 1 except for the first one.
    I suspect you actually have some other column (other than the number of hours) that define your order - that's what you put in the ORDER BY.
    Jon

  • Help needed in Exporting tables data through SQL query

    Hi All,
    I need to write a shell script(ksh) to take some of the tables data backup.
    The tables list is not static, and those are selecting through dynamic sql
    query.
    Can any body tell help me how to write the export command to export tables
    which are selected dynamically through SQL query.
    I tried like this
    exp ------ tables = query \" select empno from emp where ename\= \'SSS\' \"
    but its throws the following error
    EXP-00035: QUERY parameter valid only for table mode exports
    Thanks in advance,

    Hi,
    You can dynamically generate parameter file for export utility using shell script. This export parameter file can contain any table list you want every time. Then simply run the command
    $ exp parfile=myfile.txt

  • Help needed in framing SQL query.

    Hi,
    I have table having following schema:
    PRODUCT_ID         INT
    DATE                   DATETIME
    ITEMS_SOLD         INT
    This table contains data for a week (sunday to saturday). I want to write an SQL query to get (filter out) PRODUCT_ID of products which has same no. of ITEMS_SOLD for all 7 days. Also for given PRODUCT_ID I need to find the longest period of successive days where the no. of ITEMS_SOLD is same for all days in this period. Eg.(PRODUCT_ID 23 was sold as following along the week in no. of units sold: 4,6,6,6,6,7,4 .So the longest period is *4 days* from Monday to Thursday.) The first condition is special case of second condition where no. of days is 7.
    Any help to get the SQL query will be appreciated.
    Thanks,
    Akshay.

    PRODUCT_ID      DATE           ITEMS_SOLD
    1          10/10/2011     3
    1          11/10/2011     3
    1          12/10/2011     3
    1          13/10/2011     3
    1           16/10/2011     5
    2          10/10/2011     4
    2           11/10/2011     4
    2          12/10/2011     4
    2          13/10/2011     4
    2           14/10/2011     4
    2          15/10/2011     4
    2          16/10/2011     4
    Output:
    PRODUCT_ID ITEMS_SOLD NO_OF_DAYS
    1          3                4     
    2          4               7
    Explanation of results:
    The table to be queried contains data for 1 week: from 10/10/2011(Sunday) to 16/10/2011(Saturday). Now, product with PRODUCT_ID '1' was sold on dates 10,11,12,13,16. Out of these 5 days 3 units were sold on 4 successive days (from 10-13). So output should be like :
    PRODUCT_ID ITEMS_SOLD NO_OF_DAYS
    1          3               4     
    as longest period of successive days is 4 where same no. of units were sold i.e 3 units (other period is of 1 day on 16th ).
    For PRODUCT_ID 2 we have only one period of 7 days where 4 units were sold each day. So we output :
    PRODUCT_ID ITEMS_SOLD NO_OF_DAYS
    2           4               7
    Other case where same PRODUCT_ID have different units sold on each day should be ignored.
    I hope that clarifies the problem more. Let me know in case I have missed out anything which should have been mentioned.
    -Akshay.

  • Need to run a sql query in the background and display the output in HTML

    Hi Guys,
    I have a link in my iprocurement webpage, when i click this link, a query (sql query) should be run and the output should be displayed in a HTML page. Any ideas of how this can be done. Help appreciated.
    We dont have OA Framework and we r using 11.5.7.
    help needed
    thanx

    Read Metalink Note 275880.1 which has the link to developer guide and personalization guide.

  • Need help in improving the performance for the sql query

    Thanks in advance for helping me.
    I was trying to improve the performance of the below query. I tried the following methods used merge instead of update, used bulk collect / Forall update, used ordered hint, created a temp table and upadated the target table using the same. The methods which I used did not improve any performance. The data count which is updated in the target table is 2 million records and the target table has 15 million records.
    Any suggestions or solutions for improving performance are appreciated
    SQL query:
    update targettable tt
    set mnop = 'G',
    where ( x,y,z ) in
    select a.x, a.y,a.z
    from table1 a
    where (a.x, a.y,a.z) not in (
    select b.x,b.y,b.z
    from table2 b
    where 'O' = b.defg
    and mnop = 'P'
    and hijkl = 'UVW';

    987981 wrote:
    I was trying to improve the performance of the below query. I tried the following methods used merge instead of update, used bulk collect / Forall update, used ordered hint, created a temp table and upadated the target table using the same. The methods which I used did not improve any performance. And that meant what? Surely if you spend all that time and effort to try various approaches, it should mean something? Failures are as important teachers as successes. You need to learn from failures too. :-)
    The data count which is updated in the target table is 2 million records and the target table has 15 million records.Tables have rows btw, not records. Database people tend to get upset when rows are called records, as records exist in files and a database is not a mere collection of records and files.
    The failure to find a single faster method with the approaches you tried, points to that you do not know what the actual performance problem is. And without knowing the problem, you still went ahead, guns blazing.
    The very first step in dealing with any software engineering problem, is to identify the problem. Seeing the symptoms (slow performance) is still a long way from problem identification.
    Part of identifying the performance problem, is understanding the workload. Just what does the code task the database to do?
    From your comments, it needs to find 2 million rows from 15 million rows. Change these rows. And then write 2 million rows back to disk.
    That is not a small workload. Simple example. Let's say that the 2 million row find is 1ms/row and the 2 million row write is also 1ms/row. This means a 66 minute workload. Due to the number of rows, an increase in time/row either way, will potentially have 2 million fold impact.
    So where is the performance problem? Time spend finding the 2 million rows (where other tables need to be read, indexes used, etc)? Time spend writing the 2 million rows (where triggers and indexes need to be fired and maintained)? Both?

  • Need a help in SQL query

    Hi,
    I need a help in writing an SQL query . I am actually confused how to write a query. Below is the scenario.
    CREATE TABLE demand_tmp
    ( item_id  NUMBER,
      org_id   NUMBER,
      order_line_id NUMBER,
      quantity NUMBER,
      order_type NUMBER
    CREATE TABLE order_tmp
    ( item_id  NUMBER,
       org_id   NUMBER,
       order_line_id NUMBER,
       open_flag  VARCHAR2(10)
    INSERT INTO demand_tmp
    SELECT 12438,82,821,100,30 FROM dual;
    INSERT INTO demand_tmp
    SELECT 12438,82,849,350,30 FROM dual;
    INSERT INTO demand_tmp
    SELECT 12438,82,NULL,150,29 FROM dual;
    INSERT INTO demand_tmp
    SELECT 12438,82,0,50,-1 FROM dual;
    INSERT INTO order_tmp
    SELECT 12438,82,821,'Y' FROM dual;
    INSERT INTO order_tmp
    SELECT 12438,82,849,'N' FROM dual;
    Demand_tmp:
    Item_id        org_id   order_line_id       quantity       order_type     
    12438     82                 821                 100       30     
    12438     82                 849                 350       30     
    12438     82              NULL                 150       29     
    12438     82                    0                  50       -1     
    Order_tmp :
    Item_id        org_id        order_line_id      open_flag     
    12438     82                  821                Y     
    12438     82                  849                N     I need to fetch the records from demand_tmp table whose order_line_id is present in order_tmp and having open_flag as 'Y' or if order_type in demand_tmp table is 29.
    The below query will give the records whose order line id is present in order_tmp. But, If i need records which are having order_type=29 the below query wont return any records as order_line_id is NULL. If I place outer join I will get other records also (In this example order_type -1 records) . Please help me how can we write a query for this. Expected o/p is below.
    Query :
    Select item_id,org_id,order_line_id,quantity,order_type,open_flag
    from demand_tmp dt , order_tmp ot
    where dt.order_line_id = ot.order_line_id
    AND dt.item_id=ot.item_id
    AND dt.org_id = ot.org_id
    AND ot.open_flag = 'Y';
    Expected Output :                         
    item_id     org_id     order_line_id     quantity     order_type   open_flag
    12438     82                 821               100                    30             Y
    12438     82              NULL               150                29         NULL Thanks in advance,
    Rakesh
    Edited by: Venkat Rakesh on Oct 7, 2012 6:32 PM
    Edited by: Venkat Rakesh on Oct 7, 2012 8:39 PM

    Hi Rakesh,
    the query is not working as you would like ( but IS working as expected ) since your trying to compare null to another value.
    Comparing null always results in FALSE, also if you compare null to null. This is because null means undefined.
    select 1 from dual where null=null results in no data found.
    I would suggest using a non natural key to join the tables.
    For example include a column ID in the master table which is filled with a sequence and include that field as a foreign key in the detail table.
    This way you can easily join master and detail on ID = ID, and you don't have to worry about null values in this column since it's always filled with data.
    Regards,
    Bas
    btw, using the INNER JOIN and OUTER JOIN syntax in your SQL makes it better readable, since you're separating join conditions from the where clause, just a tip ;)

  • SQL Query for members of dynamic group - Need to include Name, Path and Type

    Hello,
    I built a custom dynamic group that has all my SQL databases in it using SCOM 2012 SP1.  The group works fine as I can see the Name(ie, Database name), Health State, Path (ie, hostname/instance) and Types (ie; SQL 2005).  Now I'm trying to
    build a custom report based off this same information using a SQL query.   I'm no DBA and could use some help.  So far this is what i have
    use
    select
    SourceObjectDisplayName as
    'Group Name',
    TargetObjectDisplayName,TargetObjectPath
    from RelationshipGenericView
    where isDeleted=0
    AND SourceObjectDisplayName
    like
    'SQL_Databases_All'
    ORDERBY TargetObjectDisplayName
    This gets me the Group Name (which i really don't care about), database name, and hostname/instance. What I am missing is the Health State and most importantly the Type (ie, SQL Server 2005 DB, SQL Server 2008DB).
    If someone could assist me here I would appreciate it. I believe I need to do some type of INNER JOIN but have no idea where the SQL type info lives or the proper structure to use. Thanks
    OperationsManager

    Here's the updated Query for OpsMan 2012 R2:
    To find all members of a given group (change the group name below):
    select SourceObjectDisplayName as 'Group Name', TargetObjectDisplayName as 'Group Members' 
    from RelationshipGenericView 
    where isDeleted=0 
    AND SourceObjectDisplayName = 'Agent Managed Computer
    Group' 
    ORDER BY TargetObjectDisplayName

  • 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.

  • Complex SQL Query in BPEL DB Adapter

    Hi,
    Is it possbile to write a complex query in BPEL DB Adapter using "Custom SQL Query"?
    I would like to write an IF ELSE condition in the DB Adapter similar what is given below..
    IF((SELECT COUNT(*) FROM F5898001 WHERE CT58SRCNME = 'CA_TEST' AND CTJOBNAME = '12345' AND CTEDBT = 'EDBT' AND CTEDSP = 'B') < 1)
    BEGIN
    insert into f5898001 (CTJOBNAME,CTEDSP,CTEDBT,CT58SRCNME) VALUES (#jobname, #edsp, #edbt, #srcnme)
    END.

    In a single pass no.
    You could use a DB link to perform select and return result to BPEL process variable. Put a switch decision depending on result in variable that calls a DB Adapter to perform the insert.
    Wouldn't be in a single transaction and not very elegant, but might be a way round.

  • Need help pl/sql function body returning SQL query - Reports

    I need help with Grouping by on a report that I developed in my application.
    I have posted my Code in
    Apex.oracle.com
    workspace : c a s e _ m a n a g e m e n t
    User Id : public
    Password : public
    I need help on Page 38 Reports.
    I get blank lines when I do break by first , second and third columns on the reports attribute.
    So I think I have to write "group by " or Distinct in side the SQL query. But not sure how to do it there.
    Thank you

    Is this an APEX question, then try here:
    Oracle Application Express (APEX)
    Is this an Oracle Reports question, then try here:
    Reports
    Is this an SQL question:
    Please provide sample data and expected output. Also please show what you have tried already.

Maybe you are looking for

  • How can I determine which codec to use?

    I'm using PE7 on a PC. I have HD video shot with a Canon. Each video - there are six of them - is less than five minutes. After I finished editing, I uploaded them to youtube and emailed a link to my client, but my client complained that they were ou

  • Transportation module

    I am a FICO consultant and need some information about the transportation module that SAP has. Is there any documentation available for this? Also, when using this, will the shipment cost of raw materials be updated automatically in the PO? Any info

  • (free) Microsoft Project viewer

    Hi, I wonder is there any free Microsoft Project .mpp viewer on OS X? I just need a free viewer and not the full blown project management software. I have installed Microsoft Project running on Parallels but I have to start the whole Windows before I

  • Batch characteristics make mandatory

    Dear All, I have a characteristic for some material where at the time of GRN system is not asking that characteristic as mandatory. Eventhough i have marked it as mandatory(country of origin is the characteristic). How to make it possible???

  • Can't get on my computer

    i have a mini cq10-525dx and when i turn it on, i receive a black screen with a blinking line on it. I can't go any further.