LESS a matter of query logic

I need to archive records based on multiple rules. I got this resolved with the exception of a rule. Here's the scenario.

With the help of Oracle database 11 g 2.

create table tab
(   id                  number  primary key
  , status_id           number
  , supplier_id         number
  , supplier_type_id    number
  , dt_eff_from         date
)
/

insert into tab
values(10,2,234000,84,sysdate-10)
/

insert into tab
values(15,2,234000,84,sysdate-15)
/


insert into tab
values(20,1,234000,84,sysdate-20)
/

insert into tab
values(30,1,234000,84,sysdate-30)
/

insert into tab
values(40,2,234000,84,sysdate-40)
/

insert into tab
values(50,1,234000,84,sysdate-50)
/

insert into tab
values(60,2,999999,25,sysdate-10)
/

insert into tab
values(70,2,999999,25,sysdate-15)
/

insert into tab
values(80,2,999999,25,sysdate-20)
/

insert into tab
values(90,1,777777,33,sysdate-10)
/


insert into tab
values(100,2,777777,33,sysdate-20)
/


insert into tab
values(110,2,777777,33,sysdate-30)
/

commit ;

        ID  STATUS_ID SUPPLIER_ID SUPPLIER_TYPE_ID DT_EFF_FROM
---------- ---------- ----------- ---------------- --------------------
        10          2      234000               84 17-APR-2015 
        15          2      234000               84 12-APR-2015 
        20          1      234000               84 07-APR-2015 
        30          1      234000               84 28-MAR-2015 
        40          2      234000               84 18-MAR-2015
        50          1      234000               84 08-MAR-2015 
        60          2      999999               25 17-APR-2015 
        70          2      999999               25 12-APR-2015 
        80          2      999999               25 07-APR-2015 
        90          1      777777               33 17-APR-2015 
       100          2      777777               33 07-APR-2015
       110          2      777777               33 28-MAR-2015 

Batch: 1 approved =, 2 = rejected

Records are analyzed on the basis supplier_id + supplier_type_id

Rule 1: When batch = 2 dt_eff_from is greater than dt_eff_from for records with batch = 1

We need to keep (not archives) the most recent registration rejected

We just need to keep the most recent rejected (batch = 2) record when there is none

approved (batch = 1) record.

When batch = 1 has a greater dt_eff_from than the batch = 2 records, then we can archive

all the batch = 2 files, but we have to keep (not archives) the batch = 1 sheet

select id from tab -- initially all records are candidates to be archived
MINUS
select id from tab
where <logic for rule 1 goes here>


ID 
---
15
20
30
40
50
70
80
100
110

Based on rule 1, all the files get archived except ID = 10 ID = 60 and ID = 90

Any thoughts?

SELECT * FROM)

SELECT T.*

MAX (batch) OVER (PARTITION BY SUPPLIER_ID, SUPPLIER_TYPE_ID) last_status_id KEEP(DENSE_RANK LAST ORDER BY DT_EFF_FROM,ID)

ROW_NUMBER() over (PARTITION OF SUPPLIER_ID, SUPPLIER_TYPE_ID ORDER BY DT_EFF_FROM DESC, ID DESC) rn

T tab

)

WHERE (last_status_id = 2 AND rn = 1) OR (last_status_id = 1 AND batch = 1);

Tags: Database

Similar Questions

  • Reg: query logic.

    Hi Experts,

    I have a requirement of query which am not able to achieve correctly-

    2 tables like this:

    WITH t1 AS)

    SELECT the 1 id, cm_dt of TO_DATE('04.04.2014','dd.mm.yyyy') OF double UNION ALL

    SELECT 2 id, TO_DATE('01.11.2013','dd.mm.yyyy') cm_dt FROM dual UNION ALL

    SELECT 2 id, TO_DATE('29.09.2013','dd.mm.yyyy') cm_dt FROM dual UNION ALL

    Select 3 id, to_date('17.05.2013','dd.mm.yyyy') cm_dt of the double

    )

    t2 AS)

    SELECT the 1 id, TO_DATE('04.05.2014','dd.mm.yyyy') fh_dt, ov 'b', 'a' double UNION ALL nv

    SELECT 1 id, TO_DATE('21.05.2014','dd.mm.yyyy'), 'y', 'x' FROM dual UNION ALL

    SELECT 2 id, TO_DATE('01.10.2013','dd.mm.yyyy'), 'r', 'e' FROM dual UNION ALL

    SELECT the id 2, TO_DATE('15.10.2013','dd.mm.yyyy'), 'x', 'q' FROM dual UNION ALL

    SELECT 2 id, TO_DATE('29.03.2014','dd.mm.yyyy'), 'f', 'b' FROM dual

    )

    My requirement is :


    Check - 1

    For each ID of "t1", need to check in 't2' If a record exists. If the 'id' doesn't exist, you need to select another table called "table_y". Here, T1.ID = 3

    Check the box - 2

    If the ID exists, for each 'id' and T1. CM_DT - is any record in T2 where (T1.id = T2.id and T1. CM_DT < T2. Take FH_DT) then the OV (old value) of the last record.

    Otherwise, if no such folder i.e. all have T1. CM_DT > T2. FH_DT - take NV (new value) of the first record.

    Expected results :

    1 04.04.2014 b

    2 01.11.2013 q

    2 29.09.2013 r

    3 17.05.2013 < some value from another table >

    My try and try again...

    WITH t1 AS)

    SELECT the 1 id, cm_dt of TO_DATE('04.04.2014','dd.mm.yyyy') OF double UNION ALL

    SELECT 2 id, TO_DATE('01.11.2013','dd.mm.yyyy') cm_dt FROM dual UNION ALL

    SELECT 2 id, TO_DATE('29.09.2013','dd.mm.yyyy') cm_dt FROM dual UNION ALL

    Select 3 id, to_date('17.05.2013','dd.mm.yyyy') cm_dt of the double

    )

    t2 AS)

    SELECT the 1 id, TO_DATE('04.05.2014','dd.mm.yyyy') fh_dt, ov 'b', 'a' double UNION ALL nv

    SELECT 1 id, TO_DATE('21.05.2014','dd.mm.yyyy'), 'y', 'x' FROM dual UNION ALL

    SELECT 2 id, TO_DATE('01.10.2013','dd.mm.yyyy'), 'r', 'e' FROM dual UNION ALL

    SELECT the id 2, TO_DATE('15.10.2013','dd.mm.yyyy'), 'x', 'q' FROM dual UNION ALL

    SELECT 2 id, TO_DATE('29.03.2014','dd.mm.yyyy'), 'f', 'b' FROM dual

    )

    ------

    x AS

    (SELECT

    T1.ID, t1.cm_dt, t2.fh_dt, nv, ov,

    ROW_NUMBER() over (PARTITION BY t2.id ORDER BY fh_dt asc) Clotilde,

    MIN (T2.fh_dt) on min_dt (PARTITION BY t2.id),

    Max (T2.fh_dt) on max_dt (PARTITION BY t2.id)

    T1 LEFT JOIN t2 ON (t1.id = t2.id)

    )

    --------

    SELECT distinct

    x.ID, x.cm_dt, x.fh_dt,

    (CASE WHEN cm_dt < = min_dt THEN)

    (SELECT t2.ov FROM t2 WHERE t2.id = AND t2.fh_dt x.id = x.min_dt)

    ON THE OTHER

    (SELECT t2.ov FROM t2 WHERE t2.id = AND t2.fh_dt x.id = x.min_dt)

    Chk1 END)

    X

    ORDER BY id, cm_dt

    Please give some guidance. Help much appreciated.

    -Nordine

    (on Oracle 11.2.0.3.0)

    I think it's something like what you are looking for (if you had provided details of the 'other' table you want to get the values of, then I could have tried integrate this logic in this query, rather than do something using the double table!):

    WITH t1 AS (SELECT 1 id, TO_DATE('04.04.2014','dd.mm.yyyy') cm_dt FROM dual UNION ALL
                SELECT 2 id, TO_DATE('01.11.2013','dd.mm.yyyy') cm_dt FROM dual UNION ALL
                SELECT 2 id, TO_DATE('29.09.2013','dd.mm.yyyy') cm_dt FROM dual UNION ALL
                select 3 id, to_date('17.05.2013','dd.mm.yyyy') cm_dt from dual),
         t2 AS (SELECT 1 id, TO_DATE('04.05.2014','dd.mm.yyyy') fh_dt, 'a' nv,'b' ov FROM dual UNION ALL
                SELECT 1 id, TO_DATE('21.05.2014','dd.mm.yyyy') , 'x','y' FROM dual UNION ALL
                SELECT 2 id, TO_DATE('01.10.2013','dd.mm.yyyy') , 'e','r'  FROM dual UNION ALL
                SELECT 2 id, TO_DATE('15.10.2013','dd.mm.yyyy') , 'q','x' FROM dual UNION ALL
                SELECT 2 id, TO_DATE('29.03.2014','dd.mm.yyyy') , 'b','f' FROM dual),
        res as (select t1.id,
                       t1.cm_dt,
                       t2.fh_dt,
                       t2.nv,
                       t2.ov,
                       min(case when t2.fh_dt > t1.cm_dt then t2.fh_dt end) over (partition by t2.id, t1.cm_dt) min_t2_fh_dt_past_cm_dt,
                       max(case when t2.fh_dt < t1.cm_dt then t2.fh_dt end) over (partition by t2.id, t1.cm_dt) max_t2_fh_dt_pre_cm_dt,
                       coalesce(max(case when t2.fh_dt < t1.cm_dt then t2.fh_dt end) over (partition by t2.id, t1.cm_dt),
                                min(case when t2.fh_dt > t1.cm_dt then t2.fh_dt end) over (partition by t2.id, t1.cm_dt)) comparison_dt
                from   t1,
                       t2
                where  t1.id = t2.id (+))
    select id,
           cm_dt,
           case when comparison_dt is null then (select 'zzz' from dual)
                when comparison_dt > cm_dt then ov
                when comparison_dt < cm_dt then nv
           end replacement_value
    from   res
    where  comparison_dt is null
    or     comparison_dt = fh_dt;
    
            ID CM_DT      REPLACEMENT_VALUE
    ---------- ---------- --------------------------------
             1 04/04/2014 b
             2 29/09/2013 r
             2 01/11/2013 q
             3 17/05/2013 zzz
    
  • Not able to understand the query logic

    Hello

    Please, help me to understand the logic of the query below.


    I have an emp table having 2 emp_id and mgr_id column.

    data from table.

    emp_id mgr_id
    1
    2 2
    3 3
    4 5
    5
    6 5
    6 of 7
    6 of 8
    9 7

    I run the query below...

    Select * from emp where emp_id not in (select mgr_id from emp);

    Query giving no line.

    I need to know the logic of the query.

    Thank you
    HIMS

    Because there are some NULL values in the column so 'IN' mgr_id would fail to compare values such as 1,4,8,9 which are not there in mgr_id with these NULL values.

    Use NVL like below to get the desired results...

     
    
    with t as
    ( select 1 emp_id,  null mgr_id from dual union all
      select 2,2 from dual union all
      select 3,3 from dual union all
      select 4,5 from dual union all
      select 5,null  from dual union all
      select 6,5  from dual union all
      select 7,6  from dual union all
      select 8,6  from dual union all
      select 9,7  from dual
    )
    SELECT *
      FROM t
     WHERE emp_id NOT IN (SELECT nvl(mgr_id,0) from t );
    

    Concerning
    Arun

  • SQL Query logic-based price calculation

    Hi Experts,

    Here are my records in the table,
    SHIPMENT_ID     SHIP_PRICE     SHIP_ADDT_PRICE     PRODUCT_ID     PRODUCT_QTY
    1000          3.95          1          12          2
    1000          0          0          17          1
    1000          6.95          2          11          4
    1001          0          0          17          1
    1001          12.95          1          12          2
    1001          12.95          2          11          4
    1002          0          0          17          1
    1002          20.95          1          12          2
    1002          20.95          2          11          4
    For each consignment:
    I need to get maximum shipprice (no need to examine the product and quantity).
    then to manipulate as follows existing such as specimen
    SHIPMENT_ID     SHIP_PRICE     
    1000          (1*6.95)+(4-1*2)     -- Maximum Price Calculation for particular shipment
    1000          (1*0)               -- Other product calculation for same shipment
    1000          (4*2)               -- Other product calculation for same shipment
    1001          (1*12.95)+(4-1*2)     -- Maximum Price Calculation for particular shipment
    1001          (1*0)               -- Other product calculation for same shipment
    1001          (4*2)               -- Other product calculation for same shipment
    1002          (1*20.95)+(4-1*2)     -- Maximum Price Calculation for particular shipment
    1002          (1*0)               -- Other product calculation for same shipment
    1002          (4*2)               -- Other product calculation for same shipment
    Max Shipprice line for each shipment
    (SHIP_PRICE) + (remaining PRODUCT_QTY if PRODUCT_QTY > 1 + SHIP_ADDT_PRICE)

    Other than Max shipprice for each shipment
    (PRODUCT_QTY + SHIP_ADDT_PRICE)

    I am struggling here with logic how to proceed, any suggestions in connection with that?

    Thank you
    with ship as (
    select 1000 SHIPMENT_ID,3.95 SHIP_PRICE,1 SHIP_ADDT_PRICE,12 PRODUCT_ID,2  PRODUCT_QTY from dual union all
    select 1000,            0,              0,                17,           1 from dual union all
    select 1000,            6.95,            2,                 11 ,           4 from dual union all
    select 1001,             0,               0,                 17,            1 from dual union all
    select 1001,             12.95 ,          1 ,                12,            2 from dual union all
    select 1001,             12.95,           2 ,                11,            4 from dual union all
    select 1002,             0 ,              0 ,                17,            1 from dual union all
    select 1002,             20.95 ,          1,                 12 ,           2 from dual union all
    select 1002,             20.95,           2,                 11,            4 from dual )
    
    select shipment_id
          ,
          case when (max_ship = ship_price and max_qty = product_qty) then
          (1* max_ship)+ ((max_qty - min_qty )* max_ship_aat_price)
          else
           (s.PRODUCT_QTY * s.SHIP_ADDT_PRICE)
          end max_price
    from
    (select max(ship_price) over (partition by shipment_id order by shipment_id desc) max_ship,
            max(product_qty) over (partition by shipment_id order by shipment_id desc) max_qty,
            min(product_qty) over (partition by shipment_id order by shipment_id desc) min_qty,
            max(ship_addt_price) over (partition by shipment_id order by shipment_id desc) max_ship_aat_price,
            s.shipment_id,s.SHIP_PRICE,s.SHIP_ADDT_PRICE,s.PRODUCT_ID,s.PRODUCT_QTY
        from ship s)s
    order by 1,2 desc   
    

    What do you expect?

  • Query logic

    TABLE A

    ========

    Q_ID

    1

    2

    3

    4

    5

    6

    TABLE B

    =======

    Q_ID Q_NAME

    1 INS

    2 LED

    UPD 3

    INS 4

    5 LED

    UPD 66

    44 INS

    55 LED

    UPD 66

    Result

    ======

    Need to update the Table A Qid WITH Max Q_ID in table B.

    Basically to maximize A QID of table based on the Table B Q_ID

    TABLE A

    ========

    Q_ID

    44

    55

    66

    44

    55

    66

    update from table_a a

    set q_id =)

    with t as)

    Select b.q_id,

    Max (b.Q_ID) on max_q_id (b.q_name score)

    of table_b b

    When status = 'A '.

    )

    Select t.max_q_id

    t

    where t.q_id = a.q_id

    )

    where q_id in)

    Select b.q_id

    of table_b b

    When status = 'A '.

    )

    /

    SY.

  • Need help with the query logic

    I have 2 tables.

    Table Tb1:
    THE PLAN_ID PARENT_PLAN_ID ARGUMENT
    Value null P1
    P1 P2
    P3 P2
    P4 P1

    Table tb2:
    THE PLAN_ID ACTIVITY_ID PICKING ARGUMENT
    P2 A1 5000
    P2 A2 5000
    P2 A3 5000
    P3 A1 10000
    P3 A2 10000
    P4 A1 4000


    I need to find the sum of the value of reduction of the workforce for each PLAN_ID which is parent root. In the case above, this is the argument PLAN_ID P1 (WHERE PARENT_PLAN_ID IS NULL). Please note that the value of the downsizing is repeated in the tb2 table. For example, the PLAN_ID P2 argument, the value of the downsizing is 5000 and not 5000 + 5000 + 5000.

    The result of the output for the above data must be
    THE ARGUMENT PLAN_ID DRAWDOWN
    P1 19000

    Published by: user10566312 on October 30, 2012 12:30
    with t as
    (   select t1.plan_id,t1.parent_plan_id,max(t2.DRAWDOWN) DRAWDOWN
        from tb1 t1,tb2 t2
        where t1.plan_id = t2.plan_id(+)
        group by  t1.plan_id,t1.parent_plan_id
    )
    select plan_id,sum(drawdown) drawdown
    from(
          select  connect_by_root plan_id as plan_id,
                  nvl(DRAWDOWN,0) DRAWDOWN
          from t
          start with parent_plan_id is null
          connect by parent_plan_id  = prior plan_id
        )
    group by plan_id  ; 
    
    PLAN_ID DRAWDOWN
    ------- --------
    P1         19000 
    

    Published by: JAC on October 30, 2012 13:23

  • Query Sub behavior strange when using Expressions regular Oracle

    I met a strange "inconsistent" when you use an Expression regular Oracle with subqueries in SQL. Here are some details on how to reproduce what I have observed. We managed to find a solution to this "problem" using a database index; I'm writing this case hoping to better understand why Regular Expressions Oracle do not seem to work in the same way that the older, standard functions integrated as INSTR, SUBSTR, AS, etc..

    Environment settings:
    This test has been done using Oracle XE (GR 11, 2) on 32-bit Windows operating system. For my test, I used the HR schema (which is delivered pre-completed with the installation of this product) with some modifications of my own.

    Make the Test objects:
    create table hr.emp_test as
    select to_char(employee_id) as emp_id_char, employee_id as emp_id,
    first_name, last_name, hire_date
    from hr.employees;
    To illustrate my test, I inserted mixed alphanumeric values and a null value in the column of my emp_id_char for good measure:
    insert into hr.emp_test (emp_id_char, first_name, last_name, hire_date)
    values ('XKCD123','TEST','LASTNAME',sysdate);
    insert into hr.emp_test (emp_id_char, first_name, last_name, hire_date)
    values (null,'TEST1','LASTNAME2',sysdate);
    commit;
    * (1) this request fails once a nonnumeric value is inserted into the emp_test table.*
    with
       sub1 as ( select to_number(emp_id_char) as emp_id, first_name, last_name, hire_date 
          from hr.emp_test  )
    select * from sub1
    where emp_id between 100 and 110
    * (2) this query works OK.*
    with
       sub1 as ( select to_number(emp_id_char) as emp_id, first_name, last_name, hire_date 
          from hr.emp_test where emp_id_char not like 'X%'  )
    select * from sub1
    where emp_id between 100 and 110
    * (3) this query works OK.*
    with
       sub1 as ( select to_number(emp_id_char) as emp_id, first_name, last_name, hire_date 
          from hr.emp_test where instr(emp_id_char,'X',1) = 0 )
    select * from sub1
    where emp_id between 100 and 110
    * (4) this query Fails.*
    with
       sub1 as ( select emp_id_char, first_name, last_name, hire_date
                   from hr.emp_test
                  where regexp_instr(emp_id_char, '[^[:digit:]]') = 0 ),
       sub2 as ( select to_number(emp_id_char) as emp_id, first_name, last_name, hire_date
                  from sub1 )
    select *
    from sub2
    where emp_id between 100 and 110
    
    ERROR:
    ORA-01722: invalid number
    * (5) even down the results of the rational expression of 3rd under the query in sequential processing order also FAILS *.
    with
       sub1 as ( select emp_id_char, first_name, last_name, hire_date
                   from hr.emp_test
                  where regexp_instr(emp_id_char, '[^[:digit:]]') = 0 ),
       sub2 as ( select to_number(emp_id_char) as emp_id, first_name, last_name, hire_date
                  from sub1 ),
       sub3 as ( select emp_id, first_name, last_name, hire_date from sub2 )
    select *
    from sub3
    where emp_id between 100 and 110
    
    ERROR:
    ORA-01722: invalid number
    * (6) that it does not like previous query as well *.
    with
       sub1 as ( select to_number(emp_id_char) as emp_id, first_name, last_name, hire_date,
           regexp_instr(emp_id_char, '[^[:digit:]]') as reg_x 
           from hr.emp_test 
           where reg_x = 0),
       sub2 as ( select emp_id, first_name, last_name, hire_date, reg_x
          from sub1 where reg_x = 0 )
    select * from sub2
    where emp_id between 100 and 110
    
    ERROR:
    ORA-00904: "REG_X": invalid identifier
    Our Solution...
    Add a hint to the query of sup that 'hiding' the result of sub1 in memory. That did the trick. This suspicion resembles only viable workaround for this behavior. Other old built-in functions (INSTR, AS, etc.) an they were automatically following the execution plan (results of cache memory) that he had to use a 'hint' to force with the function of the regular expression.

    The conclusion, which is what I would like to help to understand or explain is that:
    If you create a series of queries/sup queries or inline views, values depend on "regular expression" type built-in sql functions do not seem to stick or maintain when implemented in complex query logic.

    Any idea is appreciated!
    Thank you!

    Published by: 870810 on July 6, 2011 15:47

    870810 wrote:
    I met a strange "inconsistent" when you use an Expression regular Oracle with subqueries in SQL.

    This is the expected behavior and has nothing to do with regular expressions - much less directly (I'll explain later). Main rule: there is no WHERE clause predicate order. Even if you use views, views online, subquery factoring, optimizer etc. can extend your display, display online, a subquery factoring. And it's Optimizer who decides the order of execution predicate unless you use the ORDERED_PREDICATES key. Now, I can explain. Regular expressions are powerful enough but also everywhere in life to pay for it with the higher cost of execution. That's why optimizer decides to apply emp_id between 100 and 110 first and regexp_instr (emp_id_char, "[^ [: digit:]]'") = 0 later.

    explain plan for
    with
    sub1 as ( select emp_id_char, first_name, last_name, hire_date
    from emp_test
    where regexp_instr(emp_id_char, '[^[:digit:]]') = 0 ),
    sub2 as ( select to_number(emp_id_char) as emp_id, first_name, last_name, hire_date
    from sub1 )
    select *
    from sub2
    where emp_id between 100 and 110;
    
    SQL> @?\rdbms\admin\utlxpls
    
    PLAN_TABLE_OUTPUT
    -------------------------------------------------------------------------------------
    Plan hash value: 3124080142
    
    ------------------------------------------------------------------------------
    | Id  | Operation         | Name     | Rows  | Bytes | Cost (%CPU)| Time     |
    ------------------------------------------------------------------------------
    |   0 | SELECT STATEMENT  |          |     1 |    57 |     3   (0)| 00:00:01 |
    |*  1 |  TABLE ACCESS FULL| EMP_TEST |     1 |    57 |     3   (0)| 00:00:01 |
    ------------------------------------------------------------------------------
    
    Predicate Information (identified by operation id):
    ---------------------------------------------------
    
    PLAN_TABLE_OUTPUT
    -------------------------------------------------------------------------------------
    
       1 - filter(TO_NUMBER("EMP_ID_CHAR")>=100 AND
                  TO_NUMBER("EMP_ID_CHAR")<=110 AND  REGEXP_INSTR
                  ("EMP_ID_CHAR",'[^[:digit:]]')=0)
    
    15 rows selected.
    
    SQL> 
    

    As you can see, optimizer uses a FULL SCAN to read data from the table and apply emp_id between 100 and 110 which translates TO_NUMBER ("EMP_ID_CHAR") > = 100 AND TO_NUMBER ("EMP_ID_CHAR")<=110. and="" obviously="" it="" fails="" trying="" to="" convert="" xkcd123="" to="" number.="" now="" cost="" of="" instr(emp_id_char,'x',1)="0" is="" lower="" and="" optimizer="" decides="" to="" apply="" instr="" first.="" therefore="" xkcd123="" is="" filtered="" out="" before="" to_number="" is="">

    SQL> explain plan for
      2  with
      3  sub1 as ( select emp_id_char, first_name, last_name, hire_date
      4  from emp_test
      5  where instr(emp_id_char, 'X') = 0 ),
      6  sub2 as ( select to_number(emp_id_char) as emp_id, first_name, last_name, hire_date
      7  from sub1 )
      8  select *
      9  from sub2
     10  where emp_id between 100 and 110;
    
    Explained.
    
    SQL> @?\rdbms\admin\utlxpls
    
    PLAN_TABLE_OUTPUT
    -----------------------------------------------------------------------------------------------
    Plan hash value: 3124080142
    
    ------------------------------------------------------------------------------
    | Id  | Operation         | Name     | Rows  | Bytes | Cost (%CPU)| Time     |
    ------------------------------------------------------------------------------
    |   0 | SELECT STATEMENT  |          |     1 |    57 |     3   (0)| 00:00:01 |
    |*  1 |  TABLE ACCESS FULL| EMP_TEST |     1 |    57 |     3   (0)| 00:00:01 |
    ------------------------------------------------------------------------------
    
    Predicate Information (identified by operation id):
    ---------------------------------------------------
    
    PLAN_TABLE_OUTPUT
    -----------------------------------------------------------------------------------------------
    
       1 - filter(INSTR("EMP_ID_CHAR",'X')=0 AND
                  TO_NUMBER("EMP_ID_CHAR")>=100 AND TO_NUMBER("EMP_ID_CHAR")<=110)
    
    14 rows selected.
    
    SQL> 
    

    The bottom LINE: With the help of strings to store non-chaine (numeric in your case) is never a good idea and shows design problems.

    SY.

  • Is what logic this correct?


    Hi gurus

    I need your advice to the monitoring scenario.

    Creating the table

    CREATE TABLE GROUP_TEST
    (
    GROUP_ID NUMBER (5));

    CREATE TABLE GROUP_TEST_DTL
    (
    GROUP_ID NUMBER (5),
    GROUP_TEST_DTL_ID NUMBER (5),
    DATE OF EFFECTIVE_DATE
    );

    Insertion

    INSERT INTO GROUP_TEST
    (
    100 SELECT FROM DUAL
    );

    INSERT INTO GROUP_TEST_DTL
    (
    SELECT GROUP_ID, 100, 1, 1 JANUARY 2014 "OF THE DOUBLE
    UNION ALL
    SELECT GROUP_ID 100, 2, 2 JANUARY 2014 ' FROM DUAL
    UNION ALL
    SELECT GROUP_ID, 100, 3, 3 JANUARY 2014 ' FROM DUAL
    );
    COMMIT;

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

    Query on table

    SELECT * FROM GROUP_TEST_DTL;

    The query result

    group_id group_test_dtl_id effective_date

    100                     1                             01-JAN-14

    100                     2                             02-JAN-14

    100                     3                             03-JAN-14

    Now I need the following output

    Output

    Group_id Min_effective_dt

    100 1 JANUARY 14

    I use the below 2 queries for this result.

    1st request

    SELECT GROUP_ID, MIN (EFFECTIVE_DATE)

    OF GROUP_TEST_DTL

    GROUP BY GROUP_ID;

    2nd request

    SEPARATE GROUP_ID, SELECT (SELECT MIN (EFFECTIVE_DATE) OF GROUP_TEST_DTL A

    WHERE A.GROUP_ID = B.GROUP_ID) MIN_DT

    OF GROUP_TEST_DTL B;

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

    My question is one that is more efficient query (I think 1st)?

    My other question is that I have my package consist of approximately 5 000 lines of code and I'm using plain effective_date in all my sliders as (select effective_date from group_test_dtl) and now my requirement has changed and the need to get/make min (effective_date) instead of plain effective_date, but in order to get the Effective_date Min, I have to use text-to-speech function Min as my 1st query and then we must consolidate all columns that exist in the select statement, but I have to change all my queries sliders, so I came to the idea of the 2nd query logic.

    Now I wonder, I did wrong and use query of query not 2nd logic 1.

    Please guide me what I need to keep my 1st query logic or the 2nd. Really appreciate your answers. Thank you

    I can tell only you should test it yourself or to consider their use quite heavy within this forum (check the difference tabibitosan/fixed, the function names...?.)

    Analytical functions Analytic Functions - the next best thing after selection according to Tom Kyte - are usually extremely efficient, despite the selection somehow inevitable within the selection because they run last (just before the order by clause).

    Concerning

    Etbin

  • Order LUN matter?

    If you have joined a LUN to multiple hosts, no matter if the logic unit number number is the same for all hosts? By LUN number, I mean ID SCSI, not the UID.

    I would recommend you keep things simple and present the LUNS to all hosts with the same unit logic-ID number. As mentioned previously, using different IDS may not be important with VMFS data warehouses, but could cause problems with RDM (see the link in my previous post).

    André

  • A query need to check whether the database should any recovery media...

    Hello

    I'm at the stage of editing a database and still be opened.at this point no matter what query is available or in any other way is there to check whether the database should any recovery media or Instance recovery... ?

    My goal is before opening the database, I make sure it's compatible or incompatible, and any form of recovery is necessary.

    Thank you and best regards,
    Rameau

    Published by: ragu.dba.in on 6 March 2013 12:57 AM

    Hi Lila,

    Use these queries, YVERT should match... no fuzzy file, don't check for recovering files in v$ recover_file... spend sufficient archives & realize the audits before open reset-logs

    set line 900
    set pages 900
    set echo on
    alter session set nls_date_format='dd-mon-yyyy hh24:mi:ss';
    set numwidth 13
    col CHECKPOINT_CHANGE# for 9999999999999999
    col CHANGE# for 9999999999999999
    column error format a10
    column member format a60
    show parameter db_recover
    select * from v$recover_file;
    select file#, status from v$datafile;
    select file#, checkpoint_change#, checkpoint_time, error from v$datafile_header;
    select distinct status from v$backup;
    select distinct  checkpoint_change#  from v$datafile_header;
    select hxfil file_id, fhscn scn, fhthr thread, fhrba_seq sequence, fhsta status from x$kcvfh;
    select distinct fhscn from x$kcvfh;
    select hxfil file_id, fhtnm tablespace_name from x$kcvfh;
    ##### Fuzzy Check ####
    alter session set nls_date_format = 'DD-MON-YYYY HH24:MI:SS';
    set feedback on
    set heading on
    set pagesize 1000
    set linesize 175
    column checkpoint_change# format 999999999999999999999
    select status, checkpoint_change#, fuzzy,
    to_char(checkpoint_time, 'DD-MON-YYYY HH24:MI:SS') as checkpoint_time,
    count(*)
    from v$datafile_header
    group by status, checkpoint_change#, fuzzy, checkpoint_time
    order by status, checkpoint_change#, fuzzy, checkpoint_time;
    

    Thank you
    Ajay more
    http://www.moreajays.com

  • Change the query to a Count (*)

    SELECT oh1.partner 'Dealer,'
    OD.sales_code 'merchant sales Code. "
    OH1. external_order_number 'Original merchant order number. "
    OH1. Region,
    Cust. billing_account_number "BAN."
    DSL.n_order 'DSL OrderNo. "
    DSL.tn_or_ftn "TN DSL."
    DSL.activation_date DSL"Activation", ".
    Telco.TN "ACCESS_TN"
    TO_CHAR (oh1.created_ts, "YYYY-MM-DD") "Date of the original order.
    Pack1.display_name 'original Description of the order. "
    Pack1.price 'Price Plan',
    uname. USER_FIRST_NAME 'Agent First Name. "
    uname. USER_LAST_NAME 'Agent Last Name',
    uname.User_Name "Agent ID",
    -to_char (dh.timestamp, ' yyyy-mm-dd hh: mi ') "USCS Button Pressed",
    TO_CHAR (oh2.created_ts, 'YYYY-MM-DD') 'USCS Order Date. "
    Pack2.display_name "USCS - order Description."
    CASE
    WHEN cd.state IN ('1 ', ' 15') THEN "RECEIVED".
    WHEN cd.state IN ('2') THEN 'TRANSFORMATION '.
    WHEN cd.state IN ('3', '8', ' 16', ' 18') THEN 'FINISH '.
    WHEN cd.state IN ('4 ', '9', ' 17') THEN 'CANCELLED '.
    WHEN cd.state ('6', '10', ' 13', ' 14') THEN 'PENDING '.
    WHEN cd.state IN ('7') THEN 'INCOMPLETE '.
    WHEN cd.state IN ('12', ' 19', ' 20') THEN 'PRESENTED '.
    ANOTHER 'OTHER '.
    END AS state_desc,
    Pack2.price "USCS - Plan price."
    Pack2.price - pack1.price "Net change"
    INA.first_name,
    INA.last_name,
    INA.add_line_1,
    Ina.City,
    INA. STATE,
    INA.zip

    OF ain.impl_oh_order_header oh1
    INNER JOIN ain.impl_oh_order_header ON oh1.external_order_number = oh2.external_order_number oh2
    INNER JOIN ain.impl_order_data ON oh1.transaction_id = od.transaction_id od
    INNER JOIN ain.impl_package ON oh1.transaction_id = pack1.transaction_id pack1
    INNER JOIN ain.impl_package ON oh2.transaction_id = pack2.transaction_id pack2
    INNER JOIN ain.impl_name_address ON oh1.transaction_id = ina.transaction_id ina
    INNER JOIN ain.impl_customer ON oh2.transaction_id = cust.transaction_id cust
    LEFT OUTER JOIN ain.impl_dsl ON oh2.transaction_id = dsl.transaction_id dsl
    LEFT OUTER JOIN ain.impl_access ON oh2.transaction_id = telco.transaction_id telco
    INNER JOIN ain.sncr_order_curr_disp ON cd.transaction_id = oh2.transaction_id cd
    INNER JOIN AIN.sncr_order_disp_head ON oh1.transaction_id = dh.transaction_id dh
    INNER JOIN ain.sncr_order_disposition ON dh.disp_transaction_id = disp.disp_transaction_id disp
    INNER JOIN ain.sncr_ssm_principal ON uname.user_id = dh.user_id uname

    WHERE the oh2.created_ts BETWEEN to_date (' 01/03/2012 00:00:00 "," mm/dd/yyyy hh24:mi:ss') AND to_date (' 31/03/2012 23:59 ',' dd/mm/yyyy hh24:mi:ss')
    AND oh1.uscs = 0 AND oh2.uscs = 1
    AND oh1.external_order_number NOT LIKE '% PROD_TEST % '.
    AND oh2.external_order_number NOT LIKE '% PROD_TEST % '.
    AND oh1.order_type = 'COMMAND '.
    AND oh2.order_type = 'COMMAND '.
    AND pack1.product_type = 'COMMAND '.
    AND pack2.product_type = 'COMMAND '.
    AND disp.category = 110 AND disp.state = 5
    AND disp.trx_seq = (SELECT MAX (trx_seq)
    Ain.sncr_order_disposition sod, ain.sncr_order_disp_head pink
    WHERE sodh.disp_transaction_id = sod.disp_transaction_id
    AND sodh.transaction_id = oh1.transaction_id
    AND sod.category = 110 AND sod.state = 5)
    AND pack1.offer_id IS NOT NULL
    AND pack2.offer_id IS NOT NULL
    AND ina.type = 'SERVICE '.
    AND cd.category = 100

    ORDER BY to_char (oh2.created_ts, ' YYYY-MM-DD "")

    Do you understand the technique that gave you yesterday? Just because your query has been modified, the response has not. For any question, you can always do

    SELECT COUNT(*)
      FROM (<>)
    

    It doesn't matter what query you have, you can always wrap up with a COUNT (*) SELECT to count the number.

    Justin

  • query to retrieve a next valid record

    Hi all

    I have a strange obligation to write a query/logic to achieve the following objectives. I have a table that has a column of date and a field that indicates whether it is a valid date or not

    Valid date
    01/11/2010 Y
    01/12/2010 N
    N 13/01/2010
    2010-02-17 Y
    2010-03-15 N
    04/11/2010 Y
    21/06/2010 Y
    2010-08-18 N
    2010-09-14 N
    2010-10-17 Y

    If a specific date is not valid, I need to go out the next valid date. So, something like

    Valid date of valid date
    01/11/2010 Y 01/11/2010
    01/12/2010 N 17/02/2010
    13/01/2010 N 17/02/2010
    17/02/2010 2010-02-17 Y
    15/03/2010 N 04/11/2010
    04/11/2010 04/11/2010 Y
    21/06/2010 Y 21/06/2010
    18/08/2010 N 17/10/2010
    14/09/2010 N 17/10/2010
    17/10/2010 Y 10/17/2010

    Is it possible in a single query?


    Thank you

    Birdy
    with t as (
               select to_date('11/01/2010','dd/mm/yyyy') dt,'Y' valid from dual union all
               select to_date('12/01/2010','dd/mm/yyyy'),'N' from dual union all
               select to_date('13/01/2010','dd/mm/yyyy'),'N' from dual union all
               select to_date('17/02/2010','dd/mm/yyyy'),'Y' from dual union all
               select to_date('15/03/2010','dd/mm/yyyy'),'N' from dual union all
               select to_date('11/04/2010','dd/mm/yyyy'),'Y' from dual union all
               select to_date('21/06/2010','dd/mm/yyyy'),'Y' from dual union all
               select to_date('18/08/2010','dd/mm/yyyy'),'N' from dual union all
               select to_date('14/09/2010','dd/mm/yyyy'),'N' from dual union all
               select to_date('17/10/2010','dd/mm/yyyy'),'Y' from dual
              )
    select  dt,
            valid,
            min(
                case valid
                  when 'Y' then dt
                end
               ) over(order by dt rows between current row and unbounded following) valid_dt
      from  t
      order by dt
    /
    
    DT         V VALID_DT
    ---------- - ----------
    11/01/2010 Y 11/01/2010
    12/01/2010 N 17/02/2010
    13/01/2010 N 17/02/2010
    17/02/2010 Y 17/02/2010
    15/03/2010 N 11/04/2010
    11/04/2010 Y 11/04/2010
    21/06/2010 Y 21/06/2010
    18/08/2010 N 17/10/2010
    14/09/2010 N 17/10/2010
    17/10/2010 Y 17/10/2010
    
    10 rows selected.
    
    SQL> 
    

    SY.

  • A delicate sql query

    Hello

    I have data like this...

    table tab1 has only a single column col1 and it contains nearly 3000 lines and all are numeric values.

    tab2 has 3 columns col1, col2.col3

    I want to generate a sql statement select with every four rows from tab1 values similar to the following.

    Now say in the following example, after that only three rows of row value 8 are there in tab1, then the select statement includes only these three values.

    Select * from tab1

    col1
    ------
    1
    2
    3
    4 select col1, col2 from tab2 where col3 in (1,2,3,4)
    5
    6
    7
    8 select col1, col2 from tab2 where col3 in (5,6,7,8)
    9
    10
    11 select col1, col2 from tab2 where col3 in (9,10,11)

    I tried in sql, but do what can you with case that it's lift error row subquery returns error a lot of lines. In pl/sql, it is possible, but how can I do this in sql?

    Thanks in advance.

    Can you please explain this somewhat unusual query logic

    Extract is very well documented ;)

    The"/ / text()" portion is an xpath function that extracts the entire text within the xml tags, that is.

     xmltype('uvwx').extract('//text()')  =>  uvwx
    

    HTH.

  • Can I make reference to a column of summary in my sql query?

    Basically, the object asking all this. I have a report very complex which has many queries of data related to the "main" request One of these queries of linked data has a subquery that it contains that references the primary key of the main request. I can't do the data binding (I can, but it's useless) using this field, because it is a subquery that has the link and this particular link. I tried to create a summary column that gives me the 'first' (and the only one, so it is safe) to reference it in the SQL block, but no go. I think that it is not still possible? Anyone have any ideas? At the moment I'm referencing that I have in a PL/SQL block (: CS_PK), but it is just considered as a parameter that never happened. Does not read the analytical column. Hmmm... I'm stuck.

    Try it with the datalink 'column-less ". Lets say query one is named Q1 with his group G1 and query is named two Q2 with the Group G2. Now create a data link between G1 and G2 do not drag a column of G1 in G2, but dragging the group header of the G1 to G2 od group header.

    Now, the detail query must be executed once for each master and you should be able to reference the value master directly in your auxiliary request.

    I hope this helps.

  • Noob in SQL Tuning seeking help

    I am learning SQL Tuning and operation of it. I know that the first step is probably explain the sql statement execution plan? My problem is that I do not understand what am I suppose to collect from the execution plan.
    SQL> set autotrace traceonly explain
    SQL> select * from employees A
         where A.last_employed =
         ( SELECT TO_CHAR(MAX(TO_DATE(PAY_DATE,'MMRR')),'MMYY')
           FROM PAYROLL_VW1 B
           WHERE B.SSN = A.SSN AND B.PAY_TYPE_CODE IN ('02','12','22','32')
          AND STATUS = 'ACTIVE' AND A.BRANCH=B.BRANCH
         );
    Execution Plan
    ----------------------------------------------------------
       0      SELECT STATEMENT Optimizer=ALL_ROWS (Cost=47427 Card=1 Bytes
              =180)
    
       1    0   FILTER
       2    1     TABLE ACCESS (FULL) OF 'EMPLOYEES' (TABLE) (Cost=1618 Card
              =297964 Bytes=53633520)
    
       3    1     SORT (AGGREGATE)
       4    3       VIEW OF 'PAYROLL_VW1' (VIEW) (Cost=2290 Card=2 Bytes=
              46)
    
       5    4         SORT (UNIQUE) (Cost=2290 Card=2 Bytes=217)
       6    5           UNION-ALL
       7    6             FILTER
       8    7               TABLE ACCESS (FULL) OF 'PAYROLL2012' (TABLE) (C
              ost=2284 Card=1 Bytes=105)
    
       9    6             FILTER
      10    9               TABLE ACCESS (BY INDEX ROWID) OF 'PAYROLL2011'
              (TABLE) (Cost=4 Card=1 Bytes=112)
    
      11   10                 INDEX (RANGE SCAN) OF 'PAYROLL2011_IDX1' (IND
              EX) (Cost=3 Card=29)
    Then what should I do with the execution plan? What else should I check on it? How to grant the request?

    Edited by: apex_disco may 1, 2012 05:57

    I don't know how the licenses work. There is a difference between EM and Grid Control. I think that if you have just one instance, Enterprise Manager is installed, and if nothing is free I think it would be. Now, how much diagnosis is free? Who knows.

    But it may not be important. If you simply play "learning SQL Tuning" say, at home on a Linux machine, you can install anything you want and play with him.

    If adding an accelerated things index (in your re-written query logic now) then you must have had a considerable amount of documents in one of these tables not indexed. If you look at the plan to explain it now, it will probably show the indexes used, fewer files searched, less costly, etc as the other plan.

    But maybe I missed your point of departure. You want to learn how to set up queries in general or you try to resolve this particular application? I took the first for my previous answers.

    As for your results, your statistics say at least high level info. Becomes coherent and physical readings went down WAY.

    Initial statistics
    ----------------------------------------------------------
    0 recursive calls
    0 db block Gets
    1172490142 compatible Gets
    4914 physical reads
    Redo 191496 size

    2340 bytes sent via SQL * Net to client
    329 bytes received via SQL * Net from client
    1 SQL * Net back and forth to and from the client
    115881 sorts (memory)
    0 sorts (disk)
    0 rows processed

    on these tables and below are my stats. I think this is a major improvement. Elapsed time was reduced significantly to 00:00:00.65

    To listen statistics
    ----------------------------------------------------------
    352 recursive calls
    0 db block Gets
    31498 compatible Gets
    1101 physical reads
    0 redo size

    2340 bytes sent via SQL * Net to client
    329 bytes received via SQL * Net from client
    1 SQL * Net back and forth to and from the client
    13 sorts (memory)
    0 sorts (disk)
    0 rows processed

    Published by: gaffe on May 1, 2012 13:18

Maybe you are looking for

  • NFC and free freestyle

    I want to connect a free freestyle on an iphone. Free freestyle is a bloodsugarlevel counter that connect to a phone using NFC. SAmsung has allowed for their phones. As for Apple?

  • DVD drive only read some DVD

    Symptom: after installing and played Dragon Age Origins for 2 days, the disk may suddenly no longer be read. Hardware: LG drive DVD Super-Multi GSA-H42L (1) I tried to uninstall the device driver and let Windows reinstall it-no luck.(2) modified the

  • What is this 'STAR '?

    Can someone tell me what is this star that appears after the upgrade LOLLIPOP! Thank you very much...

  • Issue of Windows 7 SP1 OEM System Builder Pack

    I recently bought the Pack Windows 7 SP1 OEM System Builder and I don't know if I bought the right product. I had to replace my HARD drive (old one crashed) and I felt it was time to leave the world of XP. It will be installed on an existing computer

  • X7.2 update failed

    Hi all. I have several improvements behind me, X 4 - something and until X7.1, with little or no problems before my last attempt to upgrade to X7.2. I followed the procedure of upgrading X7.2 as advised, which has no change of procedure X7.1, but som