Max SQL statement

Hello

I want to select the most recent record in the data below using the max (dat) and to return all registration-related values, see test script and SQL below:

create table test
(number of references,
number of Seq,
VARCHAR2 (10) UserID.
DAT date);


Insert test values (' 0067, 1, 'ABCD', January 31, 1999 ");
Insert test values (' 0067, 1, ' ABDF ", February 28, 2006 ');
Insert test values (' 0067, 2, 'JHKO', January 31, 1999 ");
Insert test values (0067, 2, 'SARAH', 1 May 2001 ');
Insert test values (0067, 3, 'JUNIOR', January 1, 2000 "");

Select * test tt,.
(select refs, max (dat) dat
of the test
Group of refs) t
where tt.dat = t.dat
and tt.refs = t.refs

Is there a better method to return the last disk as the above query, but without using an inline view?

Hello

sliderrules wrote:

Hello

I want to select the most recent record in the data below using the max (dat) and to return all registration-related values, see test script and SQL below:

create table test
(number of references,
number of Seq,
VARCHAR2 (10) UserID.
DAT date);

Insert test values (' 0067, 1, 'ABCD', January 31, 1999 ");
Insert test values (' 0067, 1, ' ABDF ", February 28, 2006 ');
Insert test values (' 0067, 2, 'JHKO', January 31, 1999 ");
Insert test values (0067, 2, 'SARAH', 1 May 2001 ');
Insert test values (0067, 3, 'JUNIOR', January 1, 2000 "");

Select * test tt,.
(select refs, max (dat) dat
of the test
Group of refs) t
where tt.dat = t.dat
and tt.refs = t.refs

Is there a better method to return the last disk as the above query, but without using an inline view?

Thanks for posting the CREATE TABLE and INSERT statements; This is really useful!

Do not attempt to insert the strings (as on 31 October 1999 ') in a DATE (such as dat) column.  TO_DATE to create a DATE from a string.

You should never use a posting online.  What you can do with a view online, you can also do it by using a WITH clause.  But what is the problem with a view online?

You can use a subquery IN or EXISTS, but all that prevents you from using a view a line might prevent you from using one of them.

You can use the function sum LAST (or FIRST) to get all the data of the last line (or first) from each group.  However, like all aggregate functions, that return exactly 1 row of output for each group.  The query you posted returns several production lines for the same value of the refs if there is a link to the most recent DAT.  Is this right?  (It seems that the arbiters of combination + dat is not unique in your sample data.)

There are many other ways to get the desired results using queries in one form or another.  I can't think of who are significantly better than what you have posted.

You could try the analytical function of MAX instead of the aggreate MAX, like this:

WITH got_max_dat AS

(

SELECT test. *- or display the columns that you want to

MAX (dat) OVER (PARTITION BY refs) AS max_dat

OF the test

-WHERE - if you need any filtering, it's where to put

)

SELECT *- or display the columns that you want to

OF got_max_dat

WHERE the dat = max_dat

;

I don't know if this will work better than what you have posted (it could, you can try it), but I like it because it can easily be adapted if your needs change, for example, if you want 3 DATS past, not just the 1 last.

Tags: Database

Similar Questions

  • Question of SQL statement

    I have this PreExpression at a stage of SQL statement:

    Locals.SQL_LatestResult = "SELECT UUT_RESULT.ID, UUT_RESULT. UUT_SERIAL_NUMBER, UUT_RESULT. START_DATE_TIME UUT_RESULT WHERE (((UUT_RESULT. UUT_SERIAL_NUMBER) =------"' + Locals.serial + ' \ ') AND ((UUT_RESULT." START_DATE_TIME) = (SELECT MAX (UUT_RESULT2. START_DATE_TIME) OF UUT_RESULT AS UUT_RESULT2 WHERE UUT_RESULT. UUT_SERIAL_NUMBER = UUT_RESULT2. UUT_SERIAL_NUMBER))); »

    Locals.SQL_LatestResult has this value after the PreExpression:

    SELECT UUT_RESULT.ID, UUT_RESULT. UUT_SERIAL_NUMBER, UUT_RESULT. START_DATE_TIME UUT_RESULT WHERE (((UUT_RESULT. UUT_SERIAL_NUMBER) = "15514011") AND ((UUT_RESULT. START_DATE_TIME) = (SELECT MAX (UUT_RESULT2. START_DATE_TIME) OF UUT_RESULT AS UUT_RESULT2 WHERE UUT_RESULT. UUT_SERIAL_NUMBER = UUT_RESULT2. UUT_SERIAL_NUMBER)));

    I get the number of records = 0, if I run the sequence.

    If I copy the exact same SQL query in access I get what I want to know a record.

    If I remove that part of the query:

    ((UUT_RESULT. UUT_SERIAL_NUMBER) =------"" + Locals.serial + "\") "

    I get 388 records which is correct and it run directly in access.

    What's not here?

    I was too fast for this post... it's my fault, the database link was wrong, so data were there...

    Statements are very good!

  • Identify the SQL statements that are executed frequently

    I would like to identify SQL statements that are executed may times (e.g., > 1000 times) during an interval AWR.

    I am aware of coloring a SQL_ID with exec ('...') dbms_workload_repository.add_colored_sql; but then the SQL ID must be known.

    Is it also possible to do the same for the (not yet known) SQL statements that are executed > 1000 times? I think that the SQL statements that run very quickly (for example 1 s <) won't be captured automatically in a CWA even if those statements are frequently performed.

    Version 11.2.0.4 on SLES11

    Try this...

    fixed lines 155

    execs from collar to 999 999 999

    Col min_etime to 999,999.99

    Col max_etime to 999,999.99

    Col avg_etime to 999,999.999

    Col avg_lio to 999,999,999.9

    Col norm_stddev to 999,999.9999

    Col begin_interval_time to a30

    node of col to 99999

    break on plan_hash_value on startup_time skip 1

    Select * from)

    Select sql_id, sum (execs), min (avg_etime) min_etime, max (avg_etime) max_etime stddev_etime/min (avg_etime) norm_stddev

    de)

    Select sql_id, execs, plan_hash_value, avg_etime,

    StdDev (avg_etime) on stddev_etime (sql_id partition)

    de)

    Select sql_id, plan_hash_value,.

    Sum (NVL(executions_delta,0)) execs,

    (sum (elapsed_time_delta) /decode (sum (nvl(executions_delta,0)), 0.1, sum (executions_delta)) / 1000000) avg_etime

    -sum ((buffer_gets_delta/decode (nvl(buffer_gets_delta,0), 0.1, executions_delta))) avg_lio

    DBA_HIST_SQLSTAT s, DBA_HIST_SNAPSHOT SS

    where ss.snap_id = S.snap_id

    and ss.instance_number = S.instance_number

    and executions_delta > 0

    Group of sql_id, plan_hash_value

    )

    )

    Group of sql_id, stddev_etime

    )

    where norm_stddev > nvl (to_number('&min_stddev'), 2)

    and max_etime > nvl (to_number('&min_etime'),.1)

    order of norm_stddev

    /

  • Vo SQL statement will not use aliases

    Hello!

    When I tried to enter the following code in the SQL statement in my definition of VO, it gave me an error in column ambiguously defined:

    SELECT a.PERSON_ID,

    a.EFFECTIVE_START_DATE,

    a.EFFECTIVE_END_DATE,

    a.EFFECTIVE_START_DATE,

    a.EFFECTIVE_END_DATE,

    a.EMPLOYEE_NUMBER,

    a.FULL_NAME

    OF PER_ALL_PEOPLE_F one

    I need to put an alias because I need to refer to one of its columns inside the place where the condition. What is supposed to be the right way to set it?

    Thank you.

    whatever the dynamic where clause you add with setwhereclause, it is added on top of the query you mentioned in the original Version, so your alias doesn't work

    Now if you look at the care of error fully you can see you are querying VO got closed in support () and another alias has been given by the framework (OAF) so all adding the whereclause by setwherelcause dynamically delete pls the 'a'., of the Sub statement

    setWhereClause ("a.employee_number =: 1 and a.effective_end_date = (select max (effective_end_date) in the per_all_people_f where employee_number = a.employee_number) '");

    ratther write like

    setWhereClause ("employee_number =: 1 and effective_end_date = (select max (effective_end_date) in the per_all_people_f b where b.employee_number =: 2)" ");

    setWhereClauseParams (null); Always reset

    setWhereClauseParam (0, EmpNumber);

    setWhereClauseParam (1, EmpNumber);

    I hope that is clear, if not please let me know.

    Kind regards

    Hemant

  • How to execute a SQL statement that is stored within a SQL Table

    Hello

    If someone please help me with the following problem I would be eternally grateful

    I have a SQL statement that is stored inside a certain SQL table, I want to use this SQL statement inside my PL/SQL procedure.

    Thought a simple solution was to get the SQL statement in a table, and then run it, but how could I do so exactly with PL/SQL? I only started to play with PL/SQL in the last days.

    Thanks in advance!

    This is what it looks like more or less:

    Display result for:

    ---------------------

    SELECT TRIM (OBJ_VALU_TXT)

    OF OBJ_VALU_DOC

    WHERE TYPE_OBJET = 'FLD '.

    AND OBJECT_CODE = 15443

    AND OBJ_VALU_CD = 'CAB '.

    ORDER BYDOC_SEQ_NO

    00001

    ------------------------------------------------------------------

    SELECT

    VALUE (MAX (RECEIPT_NO) + 1,: OUT-COMP-FACTOR)

    THE FRONT DESK

    WHERE (RECEIPT_NO BETWEEN

    (: OUT-COMP-FACTOR AND: OUT TO A NUMBER) OR

    (RECEIPT_NO >: OUT-COMP-FACTOR AND)

    (: OUT-TO-NUMBER = 0)

    Here's a demo of your condition.

    create table t (col1 varchar2 (200));

    table created

    insert into values t ('select * from double ');

    1 row inserted

    declare
    v_col varchar2 (200);
    v_val varchar2 (200);
    Start

    Select col1 in t v_col;

    run immediately v_col in v_val;
    dbms_output.put_line (v_val);
    end;

    -----
    X

    Use in the clause, you can use as many variables as needed. But the basic approach remains the same.

    But storage in DB SQL is not an efficient design.

    Ishan

  • Help with a SQL statement...

    Hello...

    I have tried to find a way to write a SQL statement and may not seem to produce something that works. What I need is a set of results that returns each month that a given task is in an open State. The only columns that I have in my work table with are TASK_NM, OPEN_DT and CLOSED_DT.

    So if I have a line containing the following: TASK_NM = 'task one', OPEN_DT = April 18, 10 ' and CLOSED_DT = 14 October 10 '... I would like to see as a result set that looks like:

    TASK_NM YEAR JAN FEB MAR APR MAY JUNE JULY AUG SEP OCT NOV DEC
    the task of a 2010 0 0 0 1 1 1 1 1 1 1 0 0

    Is it still possible?

    Thanks in advance,
    David.

    Published by: user13027968 on March 10, 2011 14:19

    Published by: user13027968 on March 10, 2011 15:13

    Hello

    Welcome to the Forum!

    Whenever you have a question. Please post a small example of data (CREATE TABLE and INSERT statements) and the results desired from these data.
    For example, the sample data may be:

    CREATE TABLE     table_x
    (       task_nm          VARCHAR2 (10)
    ,     open_dt          DATE
    ,     closed_dt     DATE
    );
    
    INSERT INTO table_x (task_nm, open_dt, closed_dt) VALUES ('task a', DATE '2010-04-18', DATE '2010-10-14');
    INSERT INTO table_x (task_nm, open_dt, closed_dt) VALUES ('foo',    DATE '2010-10-31', DATE '2011-01-01');
    INSERT INTO table_x (task_nm, open_dt, closed_dt) VALUES ('foo',    DATE '2010-12-01', DATE '2011-02-21');
    INSERT INTO table_x (task_nm, open_dt, closed_dt) VALUES ('foo',    DATE '2011-04-01', DATE '2011-04-30');
    INSERT INTO table_x (task_nm, open_dt, closed_dt) VALUES ('bar',    DATE '2010-01-01', DATE '2010-01-01');
    

    From this data, you may want these results:

    TASK_NM     YEAR JAN FEB MAR APR MAY JUN JUL AUG SEP OVT NOV DEC
    ---------- ----- --- --- --- --- --- --- --- --- --- --- --- ---
    bar         2010   1   0   0   0   0   0   0   0   0   0   0   0
    foo         2010   0   0   0   0   0   0   0   0   0   1   1   1
    foo         2011   1   1   0   1   0   0   0   0   0   0   0   0
    task a      2010   0   0   0   1   1   1   1   1   1   1   0   0
    

    I'm not sure eactly how you plan to use it. Are there lines that overlap for the name of the task? You always want the same number of columns? What version of Oracle are you using?
    I think you want something like this:

    WITH     got_month_cnt          AS
    (
         SELECT  task_nm
         ,     TRUNC (open_dt, 'MONTH')     AS first_month
         ,     1 + MONTHS_BETWEEN ( TRUNC (closed_dt, 'MONTH')
                             , TRUNC (open_dt,   'MONTH')
                           )          AS month_cnt
         FROM    table_x
    --     WHERE     ...     -- If you want any filtering, put it here
    )
    ,     cntr     AS
    (
         SELECT     LEVEL     AS n
         FROM     (
                   SELECT  MAX (month_cnt)     AS max_month_cnt
                   FROM     got_month_cnt
              )
         CONNECT BY     LEVEL     <= max_month_cnt
    )
    ,     all_months     AS
    (
         SELECT     m.task_nm
         ,     ADD_MONTHS ( m.first_month
                      , c.n - 1
                      )          AS open_month
         FROM     got_month_cnt     m
         JOIN     cntr          c  ON     c.n     <= m.month_cnt
    )
    SELECT       task_nm
    ,       EXTRACT (YEAR FROM open_month)                         AS year
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Jan' THEN 1 ELSE 0 END)     AS jan
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Feb' THEN 1 ELSE 0 END)     AS feb
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Mar' THEN 1 ELSE 0 END)     AS mar
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Apr' THEN 1 ELSE 0 END)     AS apr
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'May' THEN 1 ELSE 0 END)     AS may
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Jun' THEN 1 ELSE 0 END)     AS jun
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Jul' THEN 1 ELSE 0 END)     AS jul
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Aug' THEN 1 ELSE 0 END)     AS aug
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Sep' THEN 1 ELSE 0 END)     AS sep
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Oct' THEN 1 ELSE 0 END)     AS ovt
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Nov' THEN 1 ELSE 0 END)     AS nov
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Dec' THEN 1 ELSE 0 END)     AS dec
    FROM       all_months
    GROUP BY  task_nm
    ,       EXTRACT (YEAR FROM open_month)
    ORDER BY  task_nm
    ,            year
    ;
    

    This will work in Orfacle 9 (and), but from Oracle 11, you could simplify it a little bit by using SELECT... Function PIVOT.

    Published by: Frank Kulash, March 10, 2011 16:51

  • FIFO in the sql statement...

    Hello
    Suppose we have two tables:
    (1) deliveries of items according to a contract
    create the table contracted_dlv
    (item_id number (2),)
    date of contracted_date,
    number of contracted_qty);

    (2) actual delivery of items in the warehouses of the customer
    create the table real_dlv
    (item_id number (2),)
    date of dlv_date,
    number of dlv_qty);

    As the two tables can be connected to each other completely... because there is not
    the information in the real_dlv table that delivery of X in the warehouse takes place in
    conformity of the delivery as contracted, the FIFO algorithm must be used as:
    The first quantity delivered (table real_dlv) is made in order to accomplish the first
    quantity (table contracted_dlv) required / contract, until the first contracted
    amount would come true. Then the second contract qty... etc

    For example: item_id: 10
    insert into contracted_dlv (item_id, contracted_date, contracted_qty)
    values(10,'03/01/2011',6);
    insert into contracted_dlv (item_id, contracted_date, contracted_qty)
    values(10,'03/02/2011',15);

    insert into real_dlv (item_id, dlv_date, dlv_qty)
    values(10,'7/01/2011',3);
    insert into real_dlv (item_id, dlv_date, dlv_qty)
    values(10,'17/01/2011',2);
    insert into real_dlv (item_id, dlv_date, dlv_qty)
    values(10,'23/01/2011',5);
    insert into real_dlv (item_id, dlv_date, dlv_qty)
    values(10,'23/02/2011',4);
    insert into real_dlv (item_id, dlv_date, dlv_qty)
    values(10,'27/02/2011',6);
    insert into real_dlv (item_id, dlv_date, dlv_qty)
    values(10,'02/03/2011',5);

    Now I want in sql statement (even using a pl/sql function that can be used in sql)
    an output such as:

    item_id contracted_date contracted_qty dlv_qty
    03/01/2011 10, 6 6 (1 *)
    03/02/2011 10, 15 19 (2 *)

    (1 *) the dlv_qty arises as the result of what follows (3 + 2 + (5-4)) to fill the 6pieces of
    the first delivery as contracted.
    (2 *) the dlv_qty arises as the result of what follows (4 + 4 + 6 + 5) to fill the 15pieces of
    the second delivery under contracted (note that for this second contract delivery the 4pieces)
    the issue of the third actual delivery is used).

    How I write a sql stmt to achieve the above...?

    Notes:
    (1) for simplicity, I wrote only two main tables and columns in them.
    (2) if the sum (contracted_qty) < sum (dlv_qty) then you should consider that deliveries carry out
    then contracted quantity (as has happened in some examples of data that I posted above).
    (3) it must be by point so many records there are in the contracted_dlv table.
    (4) I use DB 10 g v.2

    Thank you
    SIM

    Hello

    That's what you asked for:

    WITH     contracted_rt     AS
    (
         SELECT     item_id, contracted_date, contracted_qty
         ,     SUM (contracted_qty) OVER ( PARTITION BY  item_id
                                 ORDER BY       contracted_date
                               )     AS total_qty
         FROM     contracted_dlv
    )
    ,     real_rt          AS
    (
         SELECT     item_id, dlv_date, dlv_qty
         ,     SUM (dlv_qty) OVER  ( PARTITION BY  item_id
                              ORDER BY        dlv_date
                            )     AS total_qty
         FROM     real_dlv
    )
    ,     real_final     AS
    (
         SELECT       item_id
         ,       SUM (dlv_qty)          AS total_qty
         ,       MAX (dlv_date)     AS dlv_date
         FROM       real_dlv
         GROUP BY  item_id
    )
    SELECT     c.item_id
    ,     c.contracted_date
    ,     c.contracted_qty
    ,     CASE
              WHEN  f.total_qty IS NULL
                   THEN  0
              WHEN  c.total_qty <= r.total_qty
                   THEN  c.contracted_qty
                   ELSE  GREATEST ( f.total_qty - (c.total_qty - c.contracted_qty)
                               , 0
                               )
         END     AS dlv_qty
    ,     CASE
              WHEN  c.total_qty < r.total_qty
                   THEN  (
                        SELECT  MIN (dlv_date)
                        FROM     real_rt
                        WHERE     item_id       = c.item_id
                        AND     total_qty > c.total_qty - c.contracted_qty
                         )
              WHEN  c.total_qty = r.total_qty
                   THEN  r.dlv_date
              WHEN  f.total_qty > c.total_qty - c.contracted_qty
                   THEN  f.dlv_date
         END     AS dlv_date
    FROM          contracted_rt     c
    LEFT OUTER JOIN     real_rt          r  ON     c.item_id     = r.item_id
                           AND     c.total_qty     BETWEEN     r.total_qty - r.dlv_qty
                                       AND     r.total_qty
    LEFT OUTER JOIN real_final     f  ON     c.item_id     = f.item_id
    ORDER BY  c.item_id
    ,       c.contracted_date
    ;
    

    Sorry, I don't have time for an explanation now. I'll post one tomorrow, if I can.

  • GETTING AN ERROR - slider 'P_REFCUR' cannot be used in the OPEN dynamic SQL stat

    DECLARE
    create or replace procedure partial_single (p_fileid in NUMBER, p_filename IN VARCHAR2 (2000), p_temptablename IN VARCHAR2 (2000), p_temppartialtablename IN VARCHAR2 (2000), p_retval ON the NUMBER)
    --)

    p_fileid NUMBER;
    p_filename VARCHAR2 (2000);
    p_temptablename VARCHAR2 (2000);
    p_temppartialtablename VARCHAR2 (2000);
    p_retval NUMBER;
    p_refcur types_pkg.return_cur;
    v_strquery varchar2 (4000);

    BEGIN

    p_fileid: = 5080;
    p_filename: = "TAGSUR1HM2011013111160838654.000019265";
    -p_temptablename: = "TEMP_RECORDS_MED_0004";
    p_temptablename: = 'TEMP_RECORDS_MED_DATE ';
    p_temppartialtablename: = 'TEMP_MED_PARTIAL_RECORDS_0002 ';
    p_retval: = 0;


    v_strquery: = 'SELECT imsi, connectedcallingnumber, callstart MIN (calleventstarttimestamp), SUM (calleventduration), MAX (sequence_number) sequencenumber, msisdn, max (callreleasetime) callreleasetime period';
    v_strquery: = v_strquery | ' A ' | p_temppartialtablename | ' GROUP BY connectedcallingnumber, imsi, msisdn';

    OPEN p_refcur - GETTING AN ERROR - slider 'P_REFCUR' cannot be used in a dynamic OPEN SQL statement
    FOR v_strquery;

    FOR CC IN (SELECT imsi,
    connectedcallingnumber,
    Callstart MIN (calleventstarttimestamp),
    Duration of the SUM (calleventduration),
    SequenceNumber MAX (sequence_number),
    MSISDN,
    Max (callreleasetime) callreleasetime
    OF TEMP_MED_PARTIAL_RECORDS_0002
    GROUP BY connectedcallingnumber, imsi, msisdn)

    LOOP

    UPDATE TEMP_RECORDS_MED_DATE
    SET calleventstarttimestamp = cc.callstart,
    calleventduration = calleventduration + cc.duration
    WHERE connectedcallingnumber = cc.connectedcallingnumber
    AND imsi = cc.imsi
    AND sequencenumber = cc.sequencenumber + 1
    AND msisdn = cc.msisdn
    AND calleventstarttimestamp = cc.callreleasetime;


    IF SQL % ROWCOUNT > 0
    THEN
    UPDATE TEMP_MED_PARTIAL_RECORDS_0002
    SET isprocessed = 1
    WHERE connectedcallingnumber = cc.connectedcallingnumber
    AND imsi = cc.imsi
    AND msisdn = cc.msisdn;
    - AND callreleasetime = cc.callreleasetime;

    ON THE OTHER

    UPDATE TEMP_MED_PARTIAL_RECORDS_0002
    SET calleventduration = calleventduration + cc.duration
    IMSI WHERE = cc.imsi
    AND msisdn = cc.msisdn
    AND callreleasetime = cc.callreleasetime
    AND calleventduration! = cc.duration;


    END IF;

    END LOOP;


    REMOVE FROM TEMP_MED_PARTIAL_RECORDS_0002
    WHERE isprocessed = 1;


    p_retval: = 0;

    -VALIDATION;
    / * EXCEPTION
    WHILE OTHERS
    THEN
    -RESTORATION;
    p_retval: = 1;
    p3_errorlog ("partial" p_fileid, SQLERRM, |) ':' || p_filename);
    COMMIT;
    */
    END;

    Is - what your refcursor has a return type? In this case you can not open it with dynamic SQL. Change the Refcursor as a weakly typed cursor and give it a try.

  • highest average maxtemp in a sql statement

    Hi have a table like this-

    WANT-

    CREATE TABLE INSERT_TABLE
    (
    STATE VARCHAR2 (50 BYTE),
    CITY VARCHAR2 (50 BYTE),
    MINTEMP INTEGER,
    MAXTEMP INTEGER
    )

    CITY STATE MINTEMP MAXTEMP
    NEW JERSEY JERSEY CITY 40 80
    NEWARK NJ 60 90
    NEW YORK NEW YORK 40 78
    NY 20 65 BUFFALLO

    I want to get the State with the highest average maxtemp in a sql statement.

    CGH
    In this case, the result should be--
    AVGTEMP STATE
    NJ 85

    I can do using subqueries, but I was wondering if there is a way I can achieve using analytical functions?

    Published by: girija_pathak on April 28, 2010 10:05

    Hello

    girija_pathak wrote:
    Hi Frank,.
    I'm sorry that I have not tried the two of you suggestions

    The first request was just to show what is in the table scott.emp. It has nothing to do with your problem; It lights up only on the second query and its results.

    the second qry viz.

    SELECT MIN (State) DUNGEON (DENSE_RANK LAST ORDER BY AVG (MAXTEMP)) AS deptno_of_max
    MAX (AVG (MAXTEMP)) AS max_avg_sal
    OF the test
    State of GROUP BY
    ;

    result-
    DEPTNO_OF_MAX | MAX_AVG_SAL
    NJ | 85

    is perfect.

    Can you explain a bit how it works?

    When you use a nested aggregate functions (such as MAX (AVG (maxtemp))) the internal functions are evaluated first, by using the GROUP BY clause (and SEEN, when it exists); then the external functions are evaluated, composed a GROUP BY clause. In other words, the nested aggregate query I posted Gets the same results as:

    WITH     inner_aggregates     as
    (
         SELECT    deptno
         ,       AVG (sal)     AS avg_sal
         FROM       scott.emp
         GROUP BY  deptno
    )
    SELECT  MIN (deptno) KEEP (DENSE_RANK LAST ORDER BY avg_sal)     AS deptno_of_max
    ,     MAX (avg_sal)                                             AS max_avg_sal
    FROM     inner_aggregates
    ;
    

    The LAST function is described in the manual of the SQL language:
    http://download.Oracle.com/docs/CD/B28359_01/server.111/b28286/functions076.htm#sthref1540

  • SQL statement - display expected results

    I have this SQL statement:
     SELECT DISTINCT ch.ch_status,cu.customer_id FROM contract co, contract_history ch, customer cu
          WHERE co.co_id = ch.co_id
          AND co.customer_id = cu.customer_id
          AND (cu.passportno= 'S1234567A' ) 
          AND cu.customer_id != 12345
          AND ch.ch_seqno in (SELECT MAX(ch_seqno) FROM contract_history WHERE co_id = co.co_id) 
          and co.co_id IN (SELECT co_id FROM contract_history 
          GROUP BY co_id HAVING(SUM(CASE WHEN ch_status = 'a' AND (ch_status = 'd' or ch_status = 's' or ch_status = 'o') THEN 1 
                                    WHEN ch_status = 'a' THEN 1
                                    ELSE 0
                                    END) > 0))
          ORDER BY decode(ch.ch_status,'d',1,'a',2,'s',3,'o',4)ASC;
    With the following results:
    CH_STATUS     CUSTOMER_ID
       d                           100
       d                           200
       d                           300
       a                           100
       a                           200
    How am I suppose to change my SQL statement in such a way, the results appear only that?

    Expected results
    CH_STATUS     CUSTOMER_ID
       d                       300
       a                       100
       a                       200
    Only the ch_status 'a' is displayed even if it has the status was "too. However, if customer_id has only a status was ', it will be displayed.

    I don't get what you're trying to do...

    Once you have the slider you can use the cursor... y u still need with clause,...

    But yes its possible

    QL>
    SQL> Declare
      2   Cursor c1 Is
      3   With t As
      4  (
      5  Select 'd' CH_STATUS ,129 CUSTOMER_ID  From dual Union All
      6  Select 'd'           ,62031            From dual Union All
      7  Select 'd'           ,858347           From dual Union All
      8  Select 'a'           ,129              From dual Union All
      9  Select 'a'           ,62031            From dual
     10  ) Select ch_status,customer_id
     11    From
     12  (
     13   Select ch_status, customer_id,
     14          Case When ch_status = 'd' And lag(ch_status) over (Partition By customer_id Order By ch_status) = 'a' Then 0 Else 1 End  new_status
     15   From t
     16   ) Where new_status = 1;
     17
     18   r1 c1%Rowtype;
     19  Begin
     20  Open c1;
     21  Loop
     22  Fetch c1 Into r1;
     23  Exit When c1%Notfound;
     24   dbms_output.put_line(r1.CH_STATUS);
     25  End Loop;
     26  End;
     27  /
    
    a
    a
    d
    
    PL/SQL procedure successfully completed
    
    SQL> 
    
  • With the help of a number variable in a SQL statement

    Hello

    I am trying to use a variable in a sql statement, and I ran into problems when the variable is a number. The following line of code works if the variable is a string, but not if it is a number.

    "SELECT PAGE 1 UUT_STATUS OF UNIT_UUT_RESULT WHERE UnitID = '" + Locals.LocalUnitID + "' ORDER BY DESC START_DATE_TIME.

    Is there a difference in the use of single and double quotes and the sign for numbers variables +?

    Thank you

    Stuart

    Jervin is almost correct in the post above.

    While it is correct that numbers in SQL are not enclosed in single quotes ('), we still need the entire expression to a string.  If Locals.LocalUnitID is stored as a number to TestStand, you will need to cast to a string so that the string concatination works properly.

    I believe that the correct form is as follows:

    "SELECT PAGE 1 UUT_STATUS OF UNIT_UUT_RESULT WHERE UnitID ="+ Str (Locals.LocalUnitID) + 'ORDER BY DESC START_DATE_TIME'

  • Game of demand does not pick up the good period open to active fixed from the SQL statement

    Hello

    We have a demand that could kick off the simultaneous application of the value: Ixr: list of asset by period and Ixr: reserve book report.


    ON overall demand, we set the parameter: default period based on a SQL = select period_name from FA_DEPRN_PERIODS where book_type_code = 'PER2011' and period_close_date is null


    The query runs with the good period, until we open the new period, the game application will still come closed period.

    When I run this script on the database, it gives the correct name of the open period.


    Why all the demand does not pick up the open period?


    Rock


    Hello

    When planning, the parameter values that you gave when planning will not change.

    For the test, for a simultaneous program, I create a parameter and has given the value 100 tank and default type sql statement and the value as below.

    Select to_char (sysdate, 'dd-mon-yyyy hh24:mi:ss') of double

    If, at the time of the program, it shows a default value such as the date and time with seconds. Then I planned it for every minute.

    When you check in for each race it is seen the first time only, it does not.

    so in your case, you must plan its new after change of period.

    Hope this will help you...

  • What are these SQL statements?

    Hello!

    We are our applications running on Windows Server 2003 where it works fine, using Oracle via OCI 12.1.

    Now, we have the application installed on Windows Server 2012 and it works very slowly.

    When comparing these two environments trace files came a surprise: Oracle generates a lot of SQL statements when run on Windows Server 2012!  By operating on Windows2003 it only executes the SQL from the applicaton instructions.  These additional SQL statements must be the reason for the slowness, but why Oracle it generates them and how could we get arrested?

    An example:

    PARSING IN CURSOR #46985062096816 len = 210 dep = 2 uid = 0 oct = cover 3 = 0 tim = hv 1439277877325893 = ad 864012087 = "4db599f28" sqlid = "96g93hntrzjtr."

    Select / * + rule * / bucket_cnt, row_cnt, cache_cnt, null_cnt, timestamp #, sample_size, minimum, maximum, distcnt, lowval, hival, density, col #, spare1, spare2, hist_head avgcln $ where obj #=: 1 and intcol #=: 2

    END OF STMT

    ANALYSIS #46985062096816:c = 1000, e = 456, p = 0, cr = 0, cu = 0, put = 1, r = 0, dep = 2, og = 3, plh = 0, tim = 1439277877325890

    EXEC #46985062096816:c = 0, e = 498, p = 0, cr = 0, cu = 0, put = 1, r = 0, dep = 2, og = 3, plh = 2239883476, tim = 1439277877326455

    FETCH #46985062096816:c = 0, e = 56, p = 0, cr = 3, cu = 0, set = 0, r = 1, dep = 2, og = 3, plh = 2239883476, tim = 1439277877326533

    STAT #46985062096816 id = 1 cnt = 1 pid = 0 obj = op 411 = pos = 1 "TABLE ACCESS BY INDEX ROWID HIST_HEAD$ (cr = 3 pr = 0 pw = time 0 = 55 US)"

    "STAT #46985062096816 id = 2 cnt = 1 pid = 1 pos = 1 obj = op 413 ='INDEX RANGE SCAN I_HH_OBJ #_INTCOL # (cr = 2 pr = 0 pw = time 0 = 32 US)"

    OUTCOME #46985062096816:c = 0, e = 37, dep = 2, type = 3, tim = 1439277877326601

    EXEC #46985062096816:c = 0, e = 23, p = 0, cr = 0, cu = 0, set = 0, r = 0, dep = 2, og = 3, plh = 2239883476, tim = 1439277877326702

    FETCH #46985062096816:c = 0, e = 18, p = 0, cr = 3, cu = 0, set = 0, r = 1, dep = 2, og = 3, plh = 2239883476, tim = 1439277877326738

    OUTCOME #46985062096816:c = 0, e = 8, dep = 2, type = 3, tim = 1439277877326765

    EXEC #46985062096816:c = 0, e = 19, p = 0, cr = 0, cu = 0, set = 0, r = 0, dep = 2, og = 3, plh = 2239883476, tim = 1439277877326837

    FETCH #46985062096816:c = 0, e = 21, p = 0, cr = 3, cu = 0, set = 0, r = 1, dep = 2, og = 3, plh = 2239883476, tim = 1439277877326923

    OUTCOME #46985062096816:c = 0, e = 10, dep = 2, type = 3, tim = 1439277877326954

    Thank you very much in advance!

    Best regards

    Jaakko Terhonen

    Thank you all for the reply!  This time, the reason was a problem in network traffic (TCP protocol): a lot of retransmissions for a still unknown reason.  If it had nothing to do with Oracle after all.

    I cried for help here because as a common application programmer, I wasn't familiar with the Interior details of SQL analysis and after seeing it in the trace, I assumed that these strange SQL statements - which, for some reason, is appeared only in W2012-trace - were the reason for the slowness.

    Thank you, I'm a little wiser now - and I hope that many others find this thread before asking the same question!

    Best regards

    Jaakko Terhonen

  • How can I pass a condition of the table in the sql statement?

    For example, in the table in the COND Varchar2 column (200) there is the value ' VAR > 10'.

    | COND |

    |' VAR > 10' |

    where VAR is the name of the table column. I would like to make statement CASE WHEN VAR > 10 AND 0... I tried with as subquery

    WHEN BOX (SELECT COND FROM TABLE WHERE...) THEN 0, but it does not work.

    Hello

    You can do this by using dynamic SQL.

    that is to say:

    declare
      v_stm      varchar2(4000);
      v_cond      varchar2(100);
      v_result    integer;
    begin
      select cond
        into v_cond
        from yourtable
      where a=1;
    
      v_stm := 'select case when '||v_cond||' then 0 ...';
    
      -- dynamic sql
      execute immediate v_stm
        into v_result;
    
    end;
    /
    

    Remember that, in general, dynamic SQL has a performance degradation that SQL static and should be avoided when possible.

    Storage condition or the SQL statements in the tables is not a good practice.

    Kind regards.

    Alberto

  • Get the SQL statement error programmatically

    Hello

    error SQL in the FORMS, you can display the erroneous SQL statement pressing (shift) (Ctrl) E on the screen. Is there a way to get the text of the SQL statement in a PL/SQL function for logging purposes?

    I get the error using SQLERRM, it's not a problem. But how can I get the SQL text of the statement?

    Thanks and regards,

    Sascha

    Sascha,

    You should be able to use the: SYSTEM. System LAST_QUERY variable forms.

    Craig...

Maybe you are looking for

  • 403 error

    How can I fix it

  • XP Pro cannot update error 0 x 80245003

    Win XP Pro cannot be updated.  Get error 0 x 80245003.  I followed the steps listed in http://support.microsoft.com/kb/919749 without success.  In addition, I just reinstalled XP w / SP2 delivered after a complete reformat of the HARD drive.  Additio

  • Configuration of RADIUS and accounting AAA + PIX-515E

    Dear All; I want to put the accounting of PIX. Here is the composition of the equipment. ACS SE: 4.1.1.23.5 PIX 515E: 7.0 (6) PIX of setting is as follows. GANYMEDE + Protocol Ganymede + AAA-server AAA-server GANYMEDE + host xx.xx.xx.xx key xxxxx ord

  • Renewal of the license of Adobe Muse

    In the past, I had a subscription per month at adobe muse.Once Muse opening, I was invited yesterday that I need to renew my license by clicking on membership Manager.Once on the page, I saw that on my adobe profile, the information was correct and I

  • I PAYD MY ORDER BUT IT WILL NOT BE SAVED

    It is said that it will be fixed in a view minutes but that takes more than an hour already.