SQL Query re-write assistance requested

I am needing to know the best way to go about re-writing a bad query at my workplace that needs to run at TOP performance due to very large amounts of data that will be run through it.
I have simplified the data and table to the following mock example:
ID SEQ_N IND
1 1 Y
1 2 N
2 1 N
2 2 N
3 1 N
I need a query that returns each ID, as well as the maximum SEQ_N for each ID. The tricky part is that if there is a "Y" in the indicator (IND) column, then use the maximum SEQ_N for those. If there is no "Y" indicator, then use the maximum SEQ_N for the "N" indicator column. So given the above example data, the query executed would return the following results:
ID MAX(SEQ_N)
1 1
2 2
3 1
I hope that makes sense.. The query we have running currently creates a string and gets the maximum from that. The inner part of the query looks like the following:
select id, max(decode(IND,'Y','1',0') || to_char(SEQ_N, '0000000009')) from table
And the outer query selects from this (using a substring and to_number) to get the sequence number back.. So we have a decode, to_char, substr, and to_number in order to get the job done - this is very expensive; there must be a better way!
Thanks in advance!

Or:
SQL> with t as (select 1 as id, 1 as seq_n, 'Y' ind from dual union all
  2    select 1 as id, 2 as seq_n, 'N' as ind from dual union all
  3    select 2 as id, 1 as seq_n, 'N' as ind from dual union all
  4    select 2 as id, 2 as seq_n, 'N' as ind from dual union all
  5    select 3 as id, 2 as seq_n, 'N'from dual)
  6  select id,max(seq_n) keep(dense_rank first order by ind desc,seq_n desc) seq_n
  7  from t
  8  group by id;
        ID      SEQ_N
         1          1
         2          2
         3          2                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • Need sql query to get OIM request pending approval details for one user

    HI OIM Guru,
    It would be great help if someone can provide me sql query by which i can find out how many requests are pending for approval for one user ?

    1. Below query will give you status of all the request.
    SELECT REQ.REQUEST_ID , REQ.REQUEST_STATUS FROM REQUEST REQ
    2. You can have following status
    Obtaining Operation Approval
    Obtaining Template Approval
    Operation Approval Approved
    Operation Approval Rejected
    Post Operation Processing Initiated
    Request Approval Rejected
    Request Closed
    Request Completed
    Request Created
    Request Failed
    Request Withdrawn
    Template Approval Rejected
    3. Now prepare the query from above sapmle, the requset status string should not contains foloowing values.
    Rejected
    Failed
    Closed
    Withdrawn
    Completed
    The builded query will give you the desired result for 11g
    for 10 G
    Get the OST_STATUS from Req table, and do you logic above stated
    -Kuldeep
    Edited by: Kuldeep on May 22, 2012 1:04 AM

  • Pass jstl sql query result to jsp

    Hi I have the following code which works perfectly
    <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <sql:setDataSource dataSource="jdbc/dbtest"/>
    <sql:query var="items" sql="SELECT * FROM homepagesubscriptions">
    </sql:query>
    <table border="0" align="center" valign="top">
    <c:forEach var="row" items="${items.rows}" begin = "0" end="10" >
                   <tr>
                   <td>
                        <img src="${row.imgurl}" width="100" height = "100"></a>
                   </td>
                   <tr>
    </c:forEach>
    </table>   Now what I want is to perform the query in one page and then display the data in another, as such
    index.jsp
    <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
    <sql:setDataSource dataSource="jdbc/dbtest"/>
    <sql:query var="items" sql="SELECT * FROM homepagesubscriptions">
    </sql:query>
    <!-- NOT SURE WHAT TO DO HERE
    <jsp:useBean id="resultBean" scope="request"
         class="javax.servlet.jsp.jstl.sql.ResultSupport" />
    <jsp:setProperty name="rs" property="rs" />
    <jsp:forward page="test.jsp" />
    -->
        test.jsp
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <c:set var="items" value="${resultBean}" />
    <table border="0" align="center" valign="top">
    <c:forEach var="row" items="${items.rows}" begin = "0" end="10" >
                   <tr>
                   <td>
                        <img src="${row.imgurl}" width="100" height = "100"></a>
                   </td>
                   <tr>
    </c:forEach>
    </table>   I know in index.jsp I can use jsp forward and usebean but am not sure how to? What type is the result from the query? thanks

    Take a look at the "scope" attribute of the <sql:query> tag.
    query.jsp:
    <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
    <sql:setDataSource dataSource="jdbc/dbtest"/>
    <sql:query var="items" scope="request" sql="SELECT * FROM homepagesubscriptions"/>
    <jsp:forward page="test.jsp" />and then test.jsp:
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
    <table border="0" align="center" valign="top">
    <c:forEach var="row" items="${items.rows}" begin = "0" end="10" >
                   <tr>
                   <td>
                        <img src="${row.imgurl}" width="100" height = "100"></a>
                   </td>
                   <tr>
    </c:forEach>
    </table>  

  • Java Web Analyzer security hole in SQL Query Spreadsheet using JDBC-ODBC bridge

    Hi,<BR><BR>I use Hyperion Analyzer 7.0.1 on Windows 2003 and relation database DB2 v8.2.<BR><BR>I did:<BR>1. log in to Java Web Analyzer<BR>2. button New<BR>3. Select Layout: Custom Report<BR>4. from toolbar pull down to desktop "SQL Spreadsheet" option<BR>5. "Enter SQL Query" window opens, from JDBC Driver drop down window select "JDBC-ODBC Bridge"<BR>6. in "JDBC Connection String" window replace "db1" string with database name<BR>7. leave JDBC Username and JDBC Password empty (this is default)<BR>8. click on "Test Connection" button.<BR>9. "Test Connection" window opens with message "Connection Succeded"!!! So connection to database without password succeeded.<BR>10. in "SQL Query window" write any SQL you wish and Database will execute the SQL.<BR><BR><b>Conclusion: Connecting Analyzer with SQL Spreadsheet option to relation database DB2 is possible without password.</b><BR><BR>Question: Is there any way to prevent users from executing "SQL Spreedsheet" option?<BR><BR>Thanks,<BR>Grofaty

    try
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection(dsn,"guest","guest");
    OR DriverManager.getConnection(dsn);
    System.out.println("Conection's opened");
    catch(ClassNotFoundException cnfe)
    System.err.println(cnfe);
    catch(SQLException sqle)
    System.err.println(sqle);
    try that code and double check you DSN Name . it's a good practice to greate a system DSN.
    i hope that helps.
    FEEL FREE TO ASK. WON'T BITE U
    ABDUL

  • SQL query a Static LOV

    Hey everyone
    I'm trying to create a pivot report using a technique I'm reading on Ask Tom. In order to get it working I need to return the display values from a static LOV in a sub select statement without using the column attributes functionality available on page 422 of Apex.
    My static LOV has the following structure
    Display Return
    Monitorable 5
    Pay modifier/enabler 4
    Paid now and later 3
    Paid later 2
    Paid now 1
    My sub query has the following SQL where PAID_ID is equal to the return value of my Static LOV.
    select
    SCA.SCORE_ID AS "SCORE_ID",
    (SELECT MM1.TITLE FROM MET_METRICS MM1 WHERE MM1.MET_ID = SCA.MET_ID) AS "METRIC",
    (SELECT BU1.BU
    FROM MET_BU BU1,
    MET_SCORECARD MS1
    WHERE MS1.BU_ID = BU1.BU_ID
    AND MS1.SCORECARD_ID = SCA.SCORECARD_ID) AS "BUSINESS UNIT",
    SCA.PAID_ID AS "PAID_ID"
    from MET_SCORECARD_ALLOC SCA
    WHERE SCA.DELETED_BY IS NULL
    I'd like to replace PAID_ID with the display value of my LOV WITHOUT using the Column Attributes functionality available of page 422 of Apex.
    Is anyone able to advise whether it's possible to perform a join on the LOV directly in my sql query?
    Any assistance would be very much appreciated :)
    Dave

    Create a view for you LOV in de database :
    create or replace view v_display_return
    as
    select 'Monitorable' d, 5 v from dual
    union all
    select 'Pay modifier/enabler' d, 4 v from dual
    union all
    select 'Paid now and later' d, 3  v from dual
    union all
    select 'Paid later' d, 2  v from dual
    union all
    select 'Paid now' d, 1  v from dual
    ;Then you can use the view as the source of your LOV AND join it in your query.

  • 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

  • How to write a SQL query in SAP B1 2007 B with input parameters?

    How to write a SQL query in SAP B1 2007 B with input parameters, on execution of which will ask for some input value from the user and the values will be selected from a list such as item list?

    The syntax like
    SELECT * FROM OITM T0 WHERE T0.ItemCode = '[%0\]'
    Thanks,
    Gordon

  • How to write sql query with many parameter in ireport

    hai,
    i'm a new user in ireport.how to write sql query with many parameters in ireport's report query?i already know to create a parameter like(select * from payment where entity=$P{entity}.
    but i don't know to create query if more than 1 parameter.i also have parameter such as
    $P{entity},$P{id},$P{ic}.please help me for this.
    thanks

    You are in the wrong place. The ireport support forum may be found here
    http://www.jasperforge.org/index.php?option=com_joomlaboard&Itemid=215&func=showcat&catid=9

  • "SQL Query in HTTP Request" (5474:0)

    Hi,
    The IDS signature "SQL Query in HTTP Request" (5474:0) does not recognize all malicious SQL selects. Currently, the reg exp looks like [%]20|[=]|[+])[Ss][Ee][Ll][Ee][Cc][Tt]([%]20|[+])[^\r\n\x00-\x19\x7F-\xFF]+([%]20|[+])[Ff][Rr][Oo][Mm]([%]20|[+] . We noticed that subselects does not trigger the signature. For example, "...(select%20something%20from%20somethingmore%20where%20variable%20=%20(select%20....." which could be malicious. Is there any possibility to include "(" in the regexp to detect subselects?
    Regards,
    /Ola

    hmmm...That should actually match just fine. Let's break it down:
    ([%]20|[=]|[+]) <--"%20","=",or "+"
    [Ss][Ee][Ll][Ee][Cc][Tt] <-- "SELECT"
    ([%]20|[+]) <--"%20" or "+"
    [^\r\n\x00-\x19\x7F-\xFF]+ <-- NOT one or more ascii control or extended chars
    ([%]20|[+]) <-- "%20" or "+"
    [Ff][Rr][Oo][Mm] <-- "FROM"
    ([%]20|[+]) <-- "%20" or "+"
    The only reason I can think that it wouldn't match is if there some funky characters between the first SELECT and the first FROM (i.e. carriage return/line feed, etc). Also remember that a %20 or = or + must precede the SELECT and that a %20 or + must follow the FROM.

  • Write sql query to a file

    I have a sql query:
    select * from XXWFS_CUSTOMER_EXT t2 where t2.rowid > (SELECT min(t1.rowid)
    FROM XXWFS_CUSTOMER_EXT t1
    WHERE t1.PARTY_ID=t2.PARTY_ID);
    I want to put this in a stored procedure and write it to a file to see what all the records i am getting in prod. How can we do this
    Thanks

    user10873676 wrote:
    I have a sql query:
    select * from XXWFS_CUSTOMER_EXT t2 where t2.rowid > (SELECT min(t1.rowid)
    FROM XXWFS_CUSTOMER_EXT t1
    WHERE t1.PARTY_ID=t2.PARTY_ID);
    I want to put this in a stored procedure and write it to a file to see what all the records i am getting in prod. How can we do this
    UTL_FILE can produce output text file.
    when all else fails, Read The Fine Manual
    http://www.oracle.com/pls/db112/search?remark=quick_search&word=utl_file&partno=
    Handle:     user10873676
    Status Level:     Newbie (10)
    Registered:     Jan 15, 2011
    Total Posts:     345
    Total Questions:     184 (133 unresolved)
    I extend my condolences to you since you rarely get answers to your questions here.

  • SQ01 DIsplay Problem (Can v write abap code ) Sql Query

    Hi
    Need help in SQL Query
    I generated one sql query which has the following output in general .
    Customer   name   description   amount
    asrq1  sharekhan      Amount payed      10
    asrq1  sharekhan     Amount Advance     20
    asrq1  sharekhan    Amount due             30
    but i need the output in the following way
    Customer  name  AMount payed     Amount  Advance                  Amount Due
    asrq1   sharekhan  10    20     30
    and iam new this sql query but came to know we can write code ..but iam unable to initiliaze to write
    a peace of code as i dont know what are the select-options defined ..i saw in the include but didnt got it
    % comes prefix of select-options,and iam unable to get he internal table which is displayed in the query .
    can anyone help me in this answers will be awarded points.

    First, I will suggest to go for ABAP report for this kinda requirement.
    If you really want to go for it through SQ01, even then you will have to write some ABAP to display the records in one row. You will need to create three custom fields.
    I will give Psudo for one field:
    Field Name := ZAmountPayed
    Select Amount_Payed into varAmountPayed from Table Where Emp# = '12345'
    ZAmountPayed := varAmountPayed
    Convert the above into relative ABAP code and create 2 more similar fields, and you should be all set.
    You have to know the table names and any other calculations to get the right data.

  • Is it possible to write an abap code be SAP SQL query.(ECC 6)

    hello guys,
    Is it possible to write an abap code be SAP SQL query.
    Scenario : table A has a field say f1 of length 10 and table B has a field say s1 of lenght 20. in sap sql i am able to link all the other tables but i am not able to link
    table Af1 --->Table Bs1. as the length doesnot match. so is it possibel that using abap code I can pick 10 characters from table A field f1 adjust it to 20 characters using abap and map it to field s1 of table B.
    Please let me know how to accomplish this if possible.
    thanks in advance!!

    Herm,
    Adding code is done in the infoset.
    Please do following:
    > Goto SQ02
    > Type in the infoset that the basis for your query, <change>
    > Press <code> OR <shift><f8>
    > Tou'll see 4 tabs: Extras, Selections, Code, Enhancements.
    > GoTo tab Code
    > Choose the coding section (<f4> gives you an overview)
    > Enter the code.
    You may set a breakpoint to see what the query in SQ01 will do with it.
    Succes!
    Frank

  • How to write SQL query and apply aggregate functions on it

    Hello experts,
    Iu2019ve a task to write SQL query on tree tables and do inner join on them. Iu2019ve accomplish this task by using T-CODE SQVI. However now I need to write a query and apply SQL functions on it i.e. Add, Count, Max and Min etc. Please can someone tell me how I can write SQL query with aggregate functions in SAP?
    Thanks a lot in advance

    HI Mr. Cool
    you can see the below code for using aggregate functions.
    where ARTIST and SEATSOCCU are the field names for which you want to perform these functions.
    DATA: TOTAL_ENTRIES TYPE I,
          TOTAL_ATT TYPE I,
          MAX_ATT TYPE I,
          AVG_ATT TYPE I.
    SELECT COUNT( DISTINCT ARTIST )
           SUM( SEATSOCCU )
           MAX( SEATSOCCU )
           AVG( SEATSOCCU ) FROM YCONCERT INTO (TOTAL_ENTRIES, TOTAL_ATT,
    MAX_ATT, AVG_ATT).
    Thanks
    Lalit Gupta

  • How to write sql query for counting pairs from below table??

    Below is my SQL table structure.
    user_id | Name | join_side | left_leg | right_leg | Parent_id
    100001 Tinku Left 100002 100003 0
    100002 Harish Left 100004 100005 100001
    100003 Gorav Right 100006 100007 100001
    100004 Prince Left 100008 NULL 100002
    100005 Ajay Right NULL NULL 100002
    100006 Simran Left NULL NULL 100003
    100007 Raman Right NULL NULL 100003
    100008 Vijay Left NULL NULL 100004
    It is a binary table structure.. Every user has to add two per id under him, one is left_leg and second is right_leg... Parent_id is under which user current user is added.. Hope you will be understand..
    I have to write sql query for counting pairs under id "100001". i know there will be important role of parent_id for counting pairs. * what is pair( suppose if any user contains  both left_leg and right_leg id, then it is called pair.)
    I know there are three pairs under id "100001" :-
    1.  100002 and 100003
    2.  100004 and 100005
    3.  100006 and 100007
        100008 will not be counted as pair because it does not have right leg..
     But i dont know how to write sql query for this... Any help will be appreciated... This is my college project... And tommorow is the last date of submission.... Hope anyone will help me...
    Suppose i have to count pair for id '100002'. Then there is only one pair under id '100002'. i.e 100004 and 100005

    Sounds like this to me
    DECLARE @ID int
    SET @ID = 100001--your passed value
    SELECT left_leg,right_leg
    FROM table
    WHERE (user_id = @ID
    OR parent_id = @ID)
    AND left_leg IS NOT NULL
    AND right_leg IS NOT NULL
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • SQL query requested to pull one field out of multiple records

    Post Author: ralph.devlin
    CA Forum: Data Connectivity and SQL
    We use Track IT to manage our ticket base. We have parent work orders and child assignments that I am trying to report on. What I want to do is create a view, or even if this can be done in a formula, is pull data from the main work order, which in our scnerio and accorindg to the database diagrapm is WORKORDERTYPEID = 0, It will pull the TASKS.RESPONS field from that WO. Then it will compare the TASKS.PARETNWOID to WOID and if WORKORDERTYPEID = 1 then it needs to return the TASKS/RESPONS field of that record, and there may be three records or so. Then What I may need it to do is organize it maybe into seperate columns so I can add each one to Crystal keeping in mind that it will need to link those records to main WOID of the parent so it will display on one line. Any ideas
    Ralph

    Post Author: ralph.devlin
    CA Forum: Data Connectivity and SQL
    Ok I tried that and it seemed to work fine, here is an aexample of the data returned
    168458
    Lane, Carrie
    Ralph Devlin
    Ralph Devlin
    168458
    PHX - Training Room
    SM - 8th Fl Conf Room
    NULL
    NULL
    168458
    6/20/2008 3:30:00 PM
    Video Conference
    0
    168458
    Lane, Carrie
    Ralph Devlin
    Luis Estrada
    168458
    PHX - Training Room
    SM - 8th Fl Conf Room
    NULL
    NULL
    168458
    6/20/2008 3:30:00 PM
    Video Conference
    1
    Using the last column which is the workordertypeid, I was able to elimate the first row of data, which is the parent work order, but see how it is returning the technician name twice, where the second row returns me as the primary and then the technician on the assignment WO as well, which I want. In Crystal I have it only selecting the rows with the 1 is the last column, since those rows have the data arranged how I want them to be.
    Once issue that just arose, is what if we only had one work order that we wanted to report on in the subreport. since the WO will get a 0 in the last column, it will never be selected in the report. Is there a way to either us a statement that selects it if it is the only WO listed compared by the WOID field, or if there is a way in SQL, to get what is showing in row 2 to be the only row returned back so I can then show all work orders regardless if they are an assignment
    Here is my current SQL query
    SELECT     T1.WOID, T1.REQUEST, T1.RESPONS, T2.RESPONS AS Addtech, T2.PARENTWOID, T1.LOOKUP2, T1.TaskLookup3, T1.TaskLookup4, T1.TaskLookup5,                       T1.WO_NUM, T1.DUEDATE, T1.WOTYPE3, T2.WorkOrderTypeIdFROM         dbo.TASKS AS T1 LEFT OUTER JOIN                      dbo.TASKS AS T2 ON T2.PARENTWOID = T1.WOID

Maybe you are looking for

  • OS wont start up, PRAM reset not working :(

    Hey all, I came home one day to my dual 1.8 power mac frozen and fans blowing on high. I shut it down, and when starting up...I just got thegray screen with the apple logo, nothing else. I read through the support advice and after multiple combinatio

  • Ping Status Monitor doesn't create any alert

    Hello, for Windows Server you have the Ping Status Monitor testing connection to the servers. We have the problem, that if a server is not reachable the alert does not occure. We test it with one server - disebled the network card and the monitor doe

  • Session Variables Not Sticking

    We are having issue with Session variables sticking from page to page in our Admin area of our website. You can login, but as soon as you click on another link (or anything) they drop.   It's not a code issue because we have the same code on 2 other

  • Getting files off zip disks??

    Anyone know how to connect an old SCSI device to my new iMac? Trying to salvage old files on zip disk. Data recovery companies charging $30/disk, would like to do myself if possible. TIA.

  • How to get Mac Address of Remote Computer

    Hi All, I tried to find out a solution for finding Mac Address of a remote system, then first i tried with finding it with local address using the following code it works fine for me. public class MacAddressFinder {      public static void main(Strin