Need help to write the SQL query

Hello
Please help me to write a query. My requirement is as below.

Hello
I have a table say XYZ in the following format.

product_id local min_order_quntity
========================================
1 en 10
1 ch 10
2 en 20
2 ch 20
3 en 30
3 ch 30
4 en 40
4 NC 10

Now I want to find the product_id where min_order_quantity is different for cn and locale

now I want the result of the following

product_id local min_order_quantity
=============================================
4          en          40
4 ch 10

This is different for local in and cn for product_id 4 min_order_quantity

min_order_quantity should be the same for both the locale(en,ch) for any product_id.

I want to find the product_id where min_order_quantity is different for ch and fr local

Thank you..

Hello

This query should do the job

select * from xyz t1
where exists ( select 1 from xyz t2 where t2.product_id = t1.product_id and
               t2.locale != t1.locale and t2.min_order_quantity != t1.min_order_quantity );

See you soon

Tags: Database

Similar Questions

  • Need help to write a SQL query complex

    I have the source tabe as below

    -> SOURCE_TABLE
    NAME     CUST_ID     SVC_ST_DT     SVC_END_DT 
    TOM        1               31/08/2009      23/03/2011 
    DOCK       2               01/01/2004      31/05/2010 
    HARRY      3               28/02/2007      31/12/2009 
    I want to load as target table below
    -> TARGET_TABLE
    NAME     CUST_ID                     SVC_ST_DT      SVC_END_DT 
    TOM      1           31/08/2009      31/12/2009 
    TOM      1           01/01/2010      31/12/2010 
    TOM      1           01/01/2011      23/03/2011 
    DOCK      2           01/01/2004      31/12/2004 
    DOCK      2           01/01/2005      31/12/2005 
    DOCK      2           01/01/2006      31/12/2006 
    DOCK      2           01/01/2007      31/12/2007 
    DOCK      2           01/01/2008      31/12/2008 
    DOCK      2           01/01/2009      31/12/2009 
    DOCK      2           01/01/2010      31/05/2010 
    HARRY      3           28/02/2007      31/12/2007 
    HARRY      3           01/01/2008      31/12/2008 
    HARRY      3           01/01/2009      31/12/2009 
    Is it possible to write a SQL query that returns the data in the same way above the target table.

    Published by: AChatterjee on April 30, 2012 07:14

    Published by: AChatterjee on April 30, 2012 07:14

    Or like this...

    SQL> ed
    Wrote file afiedt.buf
    
      1  with t as (select 'TOM' as NAME, 1 as CUST_ID, date '2009-08-31' as SVC_ST_DT, date '2011-03-23' as SVC_END_DT from dual union all
      2             select 'DOCK', 2, date '2004-01-01', date '2010-05-31' from dual union all
      3             select 'HARRY', 3, date '2007-02-28', date '2009-12-31' from dual)
      4  --
      5  -- end of test data
      6  --
      7  select name, cust_id, svc_st_dt, svc_end_dt
      8  from (
      9        select name
     10              ,cust_id
     11              ,greatest(svc_st_dt, add_months(trunc(svc_st_dt,'YYYY'),yr*12)) as svc_st_dt
     12              ,least(svc_end_dt, add_months(trunc(svc_st_dt,'YYYY'),(yr+1)*12)-1) as svc_end_dt
     13        from t
     14             cross join (select rownum-1 as yr
     15                         from   dual
     16                         connect by rownum <= (select extract(year from max(svc_end_dt)) - extract(year from min(svc_st_dt)) + 1 from t)
     17                        )
     18       )
     19  where svc_st_dt <= svc_end_dt
     20* order by 2, 3
    SQL> /
    
    NAME     CUST_ID SVC_ST_DT            SVC_END_DT
    ----- ---------- -------------------- --------------------
    TOM            1 31-AUG-2009 00:00:00 31-DEC-2009 00:00:00
    TOM            1 01-JAN-2010 00:00:00 31-DEC-2010 00:00:00
    TOM            1 01-JAN-2011 00:00:00 23-MAR-2011 00:00:00
    DOCK           2 01-JAN-2004 00:00:00 31-DEC-2004 00:00:00
    DOCK           2 01-JAN-2005 00:00:00 31-DEC-2005 00:00:00
    DOCK           2 01-JAN-2006 00:00:00 31-DEC-2006 00:00:00
    DOCK           2 01-JAN-2007 00:00:00 31-DEC-2007 00:00:00
    DOCK           2 01-JAN-2008 00:00:00 31-DEC-2008 00:00:00
    DOCK           2 01-JAN-2009 00:00:00 31-DEC-2009 00:00:00
    DOCK           2 01-JAN-2010 00:00:00 31-MAY-2010 00:00:00
    HARRY          3 28-FEB-2007 00:00:00 31-DEC-2007 00:00:00
    HARRY          3 01-JAN-2008 00:00:00 31-DEC-2008 00:00:00
    HARRY          3 01-JAN-2009 00:00:00 31-DEC-2009 00:00:00
    
    13 rows selected.
    
  • Need help to build the SQL query

    Hi all

    I struggle to create the select statement.

    This is my expected outcome:

    Insert into tmp (aa, bb, cc, dd)

    values('CUST1','10100001',2,'10-Jan-2013');

    Insert into tmp (aa, bb, cc, dd)

    values('CUST1','10100002',4,'11-Jan-2013');

    Insert into tmp (aa, bb, cc, dd)

    values('CUST2','10200001',2,'19-Jan-2013');

    Insert into tmp (aa, bb, cc, dd)

    values('CUST2','10200002',6,'28-Jan-2013');

    Insert into tmp (aa, bb, cc, dd)

    values('CUST2','10200003',1,'28-Mar-2013');

    My result is:

    AA COUNT (1) MAX (DD) by cc dd AA AA

    CUST1 2 10100002 4 11 January 2013

    CUST2 3 10200003 1 28 MARCH 2013

    Can someone help with the select statement?

    Thank you and best regards,

    Iwan

    Just change it to the column:

    SELECT

    AA

    COUNT (aa)

    , MAX (bb) keep (last dense_rank command by JJ)

    , MAX (cc) keep (last dense_rank command by JJ)

    MAX (dd)

    OF THE TMP

    GROUP BY aa

    ORDER BY aa

    Note that by default sort order is ascending with the last NULL values.

    If in case your line-date-max will contain null value in the bb or cc columns those will be returned.

    Post edited by: Correction of chris227

    Post edited by: chris227 added note

  • Need help to write a sub query

    Our environment - Oracle 10 g

    Hi all
    Need help to write a sub query to reach him here are examples of data using which iam trying to replace the value column in the table based on two other columns in the same table

    Examples of data

    ClaimNo flag LineNo Procedurecode
    100 01 N MN4567
    100 02 Y 7863
    100 03 N MN8976
    100 04 Y 9000
    101 01 Y 8954
    101 02 N MN6754
    101 03 N MN7654
    101 04 Y 8976
    102 01 Y 1234
    102 02 Y 2345
    102 03 Y 3456
    102 03 Y 4567

    Each column of ClaimNo has several rows of data. But if column procedurecode for a claimNo starts with MN then all values associated with the claimno for the flag column should replace N

    If the data must become like below

    ClaimNo flag LineNo Procedurecode
    100 01 N MN4567
    100 02 N 7863
    100 03 N MN8976
    100 04 N 9000
    101 01 N 8954
    101 02 N MN6754
    101 03 N MN7654
    101 04 N 8976
    102 01 Y 1234
    102 02 Y 2345
    102 03 Y 3456
    102 03 Y 4567


    Thank you

    See the example:

    with t as (
                  select 100 ClaimNo, '01' LineNo, 'N' Flag, 'MN4567' Procedurecode from dual
        union all select 100, '02', 'Y', '7863' from dual
        union all select 100, '03', 'N', 'MN8976' from dual
        union all select 100, '04', 'Y', '9000' from dual
        union all select 101, '01', 'Y', '8954' from dual
        union all select 101, '02', 'N', 'MN6754' from dual
        union all select 101, '03', 'N', 'MN7654' from dual
        union all select 101, '04', 'Y', '8976' from dual
        union all select 102, '01', 'Y', '1234' from dual
        union all select 102, '02', 'Y', '2345' from dual
        union all select 102, '03', 'Y', '3456' from dual
        union all select 102, '03', 'Y', '4567' from dual
    )
    select
        claimno,
        lineno,
        flag,
        case
          when count(decode(substr(procedurecode,1,2),'MN',1)) over(partition by claimno)>0
            then 'N'
          else flag
        end new_flag,
        procedurecode
    from t
    

    Kind regards
    Sayan M.

  • Need help in writing the SQL CASE or DECODE statement

    Hi experts,

    I need to write a SQL select order_num, cntry_cde, prod_id and Qty by joining order_num on PROD_ORDER and PROD_ORDER_TXT.

    Here is my sample data

    PROD ORDER_
    order_num Prod_id Qty cntry_cde
    100 US A1 5
    101 US 10 A2
    102 IN A3 4
    103 TO THE A4 9
    104. IN A5 3

    PROD ORDER_TXT_
    cntry_cde Prod_id order_num
    100 US A1
    101 US A2
    102 NZ A3
    103 TO THE A4
    A5 104

    Here's the requirement,

    (1) if the cntry_cde in PROD_ORDER is the same as cntry_cde in PROD_ORDER_TXT then select PROD_ORDER.cntry_cde (orders 100, 101, 103)
    (2) if they are different, choose PROD_ORDER_TXT (order 102, to THE NZ <>) country code
    (3) if they are different and PROD_ORDER_TXT.cntry_cde is null, I can't use it like cntry_cde in my report (order 104). It happenend just because of bad data to the source.
    I can't avoid it. Then just use the cntry_cde of PROD_ORDER

    Expected results
    100 US A1 5
    101 US 10 A2
    102 NZ A3 4 - changed in NZ
    103 TO THE A4 9
    104. IN A5 3 - IN retained as PROD_ORDER_TXT.cntry_cde is null


    instructions for creation and insertion of sample table are lower than

    create the table prod_order
    (number of order_num,
    cntry_cde CHAR (2),
    prod_id VARCHAR2 (6).
    number of quantity)

    create the table prod_order_txt
    (number of order_num,
    cntry_cde CHAR (2),
    prod_id VARCHAR2 (6))

    insert into prod_order values (100, 'WE', 'A1', 5);
    insert into prod_order values (101, 'WE', 'A2', 1);
    insert into prod_order values (102, ' to THE ', 'A3', 4);
    insert into prod_order values (103, ' to THE ', 'A4', 9);
    insert into prod_order values (104, 'IN', 'A5', 3);



    insert into prod_order_txt values (100, 'WE', 'A1');
    insert into prod_order_txt values (101, 'WE', 'A2');
    insert into prod_order_txt values (102, 'NZ', 'A3');
    insert into prod_order_txt values (103, ' to THE ', 'A4');
    insert into prod_order_txt values (104, 'A5', NULL);

    commit;

    Thank you for your help in advance

    Published by: manon March 28, 2012 13:39
  • Need help to write a sql

    Hi all

    I have a table with 2 fileds, say Patch, Applied_date

    Table example is below:

    Patch Applied_date
    ==================
    111 1 January 10
    222 1st February 10
    333 1 March 10
    444 2 January 10
    555 1st January 12
    666 3 January 10


    I want a query to display the output as below.

    I have search for "where patch in (111,222,777,888).

    I expect the output to be


    patch Applied_date
    ================
    111 1 January 10
    222 1st February 10
    777 not applied * 777 is not in the table, I want the applied to the display a date not applied *.
    not applied 888 * 888 dosent column exists in the table, even in this case I want in the result and its
    column (Applied_date) corresponding apply do not.


    Can someone write a sql to do this.

    I can write a PL/SQL. I want a sql.

    Thank you
    Prasad

    Published by: user13062453 on February 18, 2012 12:10

    Create list of patches in a table and use an outer join:

    with patch as (
                   select 111 patch,to_date('1-Jan-10','dd-mon-rr') applied_date from dual union all
                   select 222,to_date('1-Feb-10','dd-mon-rr') from dual union all
                   select 333,to_date('1-Mar-10','dd-mon-rr') from dual union all
                   select 444,to_date('2-Jan-10','dd-mon-rr') from dual union all
                   select 555,to_date('1-Jan-12','dd-mon-rr') from dual union all
                   select 666,to_date('3-Jan-10','dd-mon-rr') from dual
                  ),
         list  as (
                   select 111 patch from dual union all
                   select 222 from dual union all
                   select 777 from dual union all
                   select 888 from dual
                  )
    select  l.patch,
            nvl(to_char(p.applied_date,'dd-Mon-yy'),'Not applied') applied_date
      from      patch p
            right join
                list l
              on l.patch = p.patch
    /
    
         PATCH APPLIED_DAT
    ---------- -----------
           111 01-Jan-10
           222 01-Feb-10
           777 Not applied
           888 Not applied
    
    SQL> 
    

    SY.

  • Need help to convert a sql query to a stored procedure

    I have a task to convert a script sql in a stored precedure. The sql with different pr_id test_type are below. And the stored procedure must accept a pr_id and a test_type as an argument. Test type will be 3 for ATI and 2 for TI.  It must return a single value, the greatest distance calculated to fill the value of tap.  It is possible that they will pass a prid, test_type combination that will have all the records in the dsltdr table.

    {
    SELECT pw,
    Round ((DECODE (t.rfltype1, 5, t.rfldist1,)))
    DECODE (t.rfltype2, 5, t.rfldist2,)
    DECODE (t.rfltype3, 5, t.rfldist3,)
    DECODE (t.rfltype4, 5, t.rfldist4,)
    DECODE (t.rfltype5, 5, t.rfldist5,)
    DECODE (t.rfltype6, 5, t.rfldist6,)
    DECODE (t.rfltype7, 5, t.rfldist7,)
    DECODE (t.rfltype8, 5, t.rfldist8,)
    NULL)))
    (- launch_start) * distk * vop, 2) dist
    OF dsltdr t
    WHERE pr_id = 464529581
    AND test_type = 3
    ORDER BY pw CSA;
    }



    SELECT pw,
    Round ((DECODE (t.rfltype1, 5, t.rfldist1,)))
    DECODE (t.rfltype2, 5, t.rfldist2,)
    DECODE (t.rfltype3, 5, t.rfldist3,)
    DECODE (t.rfltype4, 5, t.rfldist4,)
    DECODE (t.rfltype5, 5, t.rfldist5,)
    DECODE (t.rfltype6, 5, t.rfldist6,)
    DECODE (t.rfltype7, 5, t.rfldist7,)
    DECODE (t.rfltype8, 5, t.rfldist8,)
    NULL)))
    (- launch_start) * distk * vop, 2) dist
    OF dsltdr t
    WHERE pr_id = 464528353
    AND test_type = 3
    ORDER BY pw CSA;


    SELECT pw,
    Round ((DECODE (t.rfltype1, 5, t.rfldist1,)))
    DECODE (t.rfltype2, 5, t.rfldist2,)
    DECODE (t.rfltype3, 5, t.rfldist3,)
    DECODE (t.rfltype4, 5, t.rfldist4,)
    DECODE (t.rfltype5, 5, t.rfldist5,)
    DECODE (t.rfltype6, 5, t.rfldist6,)
    DECODE (t.rfltype7, 5, t.rfldist7,)
    DECODE (t.rfltype8, 5, t.rfldist8,)
    NULL)))
    (- launch_start) * distk * vop, 2) dist
    OF dsltdr t
    WHERE pr_id = 464527142
    AND test_type = 2
    ORDER BY pw CSA;


    SELECT pw,
    Round ((DECODE (t.rfltype1, 5, t.rfldist1,)))
    DECODE (t.rfltype2, 5, t.rfldist2,)
    DECODE (t.rfltype3, 5, t.rfldist3,)
    DECODE (t.rfltype4, 5, t.rfldist4,)
    DECODE (t.rfltype5, 5, t.rfldist5,)
    DECODE (t.rfltype6, 5, t.rfldist6,)
    DECODE (t.rfltype7, 5, t.rfldist7,)
    DECODE (t.rfltype8, 5, t.rfldist8,)
    NULL)))
    (- launch_start) * distk * vop, 2) dist
    OF dsltdr t
    WHERE pr_id = 464528984
    AND test_type = 2
    ORDER BY pw CSA;



    >

    SELECT pw,
    Round ((DECODE (t.rfltype1, 5, t.rfldist1,)))
    DECODE (t.rfltype2, 5, t.rfldist2,)
    DECODE (t.rfltype3, 5, t.rfldist3,)
    DECODE (t.rfltype4, 5, t.rfldist4,)
    DECODE (t.rfltype5, 5, t.rfldist5,)
    DECODE (t.rfltype6, 5, t.rfldist6,)
    DECODE (t.rfltype7, 5, t.rfldist7,)
    DECODE (t.rfltype8, 5, t.rfldist8,)
    NULL)))
    (- launch_start) * distk * vop, 2) dist
    OF dsltdr t
    WHERE pr_id = 464529918
    AND test_type = 2
    ORDER BY pw CSA;

    How to start with?

    Thanks in advance.

    I removed the dbms_output statement because it does not seem to turn it on. If you do this from sqlplus
    Make sure that you type "serverout on" and press return.

    declare
    vPW number := 0 ;
    vDistance number := 0 ;
    begin
    sp_dsl_test(3,'12345',vDistance,vPW) ;
    DBMS_OUTPUT.PUT_LINE('Distance = '|| vDistance || ' PW = '|| vPW);
    end;
    

    Published by: FlyingGuy on March 3, 2011 14:24

  • Need help to write the query to extract the value of the previous row - Lag not help


    Hello

    I created follwing table.

    Create table test

    (number of fi,

    number of fo_fv

    number of jup_fv

    action varchar2 (10)

    );

    insert into TEST(1,1,1,'LOAD');

    Insert into TEST (2, NULL, 2, "ROLL");

    insert into TEST(3,,3,'ROLL');

    insert into TEST(4,,4,ROLL);

    insert into TEST (5,2,5,LOAD);

    I want the result of the query as below:

    FI FO_FV JUP_FV ACTION

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

    1          1                    1                    LOAD

    2          1                    2                    ROLL

    3          1                    3                    ROLL

    4          1                    4                    ROLL

    5          2                    5                    LOAD

    Help, please.

    Thank you!

    SQL > select fi
    2, max (fo_fv) on fo_fv (fi control)
    3, jup_fv
    4, action
    5 of the test;

    FI FO_FV JUP_FV ACTION
    ---------- ---------- ---------- ----------
    1 1 1 LOAD
    ROLL OF 2 1 2
    3 1 3 ROLL
    4 1 4 ROLL
    5 2 5 LOAD

    OR

    SQL > select *.
    2 test
    model 3
    Dimension 4 by (fi)
    5 measures (fo_fv, jup_fv, action)
    6 rules
    7   (
    8 fo_fv [any] = case when fo_fv [cv ()] is null
    9. can fo_fv [cv () - 1]
    10 fo_fv [cv () else]
    11 end
    (12);

    FI FO_FV JUP_FV ACTION
    ---------- ---------- ---------- ----------
    1 1 1 LOAD
    ROLL OF 2 1 2
    3 1 3 ROLL
    4 1 4 ROLL
    5 2 5 LOAD

  • Need help to write a MySQL query that returns only the peer matching records

    Because I don't know how to explain it easily, I use the table below as an example.

    I want to create a MySQL query that returns only the records that match counterparts where 'col1' = 'ABC '.

    Notice the ' ABC / GHI' record does not have a Counter-match ' GHI / ABC' record. This record must not be returned because there is no Counter-Party correspondent. With this table, the ' ABC / GHI' record should be the one returned in the query.

    How can I create a query that will do it?


    ID | col1 | col2
    --------------------
    1. ABC | DEF
    2. DEF | ABC
    3. ABC | IGS
    4. DEF | IGS
    5. IGS | DEF


    * Please let me know if you have no idea of what I'm trying to explain.

    I wanted to just the results where col1 = ABC, but I already got the answer I needed on another forum. Thank you anyway.

    SELECT a.col1,
    a.col2
    FROM table_name AS a
    LEFT OUTER
    Table_name JOIN b
    ON b.col1 = a.col2
    AND a.col1 = b.col2
    WHERE b.col1 IS NOT NULL AND a.col1 = 'ABC '.

  • How can I write the SQL query for this requirement?

    Hello

    I have a table that looks like this:

    NAME | ANNUAL |     VALUE
    ==== | ====== | =====
    execno |     480.     000004
    step |      480.     0400
    SCNA |     480. cd_demo
    System |     480.     D47-010
    type |     480.     step
    free_text |     480.     stage 400
    rbare |     480.     RBA-1
    execno |     482. 000004
    SCNA |     482. cd_demo
    System |     482.     D47-010
    free_text |     482.     step 300
    step |          482.          0300
    type |      482.     step
    rbare |     482.     RBA-1
    execno |     483.     000001
    type |     483.     step
    rbare |     483.     rke1
    SCNA |     483.     rke10
    step |     483.     0240

    Now, say that I want to fetch ONLY annual with execno = '000004' and '400' = step and scna = "cd_demo" and system = "d47-010' and type = 'step', how to write SQL code?
    At first, it seemed like a simple writing query but I've been struggling with it for hours without success. I must admit though that I'm not strong in SQL :-)
    There, can anyone help? Please...

    Thanks in advance.

    Emmanuel

    Published by: user12138559 on October 30, 2009 03:05

    Hi, Emmanuel.

    Welcome to the forum!

    Here's a way to do what you asked:

    SELECT       doc_id
    FROM       table_x
    GROUP BY  doc_id
    HAVING       SUM (CASE WHEN name = 'execno' AND value = '000004'  THEN 1 END) > 0
    AND       SUM (CASE WHEN name = 'step'   AND value = '400'     THEN 1 END) > 0
    AND       SUM (CASE WHEN name = 'scna'   AND value = 'cd_demo' THEN 1 END) > 0
    AND       SUM (CASE WHEN name = 'system' AND value = 'd47-010' THEN 1 END) > 0
    AND       SUM (CASE WHEN name = 'type'   AND value = 'step'    THEN 1 END) > 0
    ;
    

    If you think that a WHERE clause would be used, but WHERE does apply to a single line. You need a condition that checks several rows in the same group.
    WHEN has an effect something like WHERE.

    Published by: Frank Kulash, October 30, 2009 06:26

    This solution assumes that (name, annual) is unique.

  • Please help me write this SQL query...

    Hi everyone,
    
    Please help me in this query.
    A patient can multiple types of Adresses (types P,M,D).If they have all the 3 types i need to select type: p and
    if they have (M and D) i need to select type M,and if they have only type D i have to select that.
    For each address i need to validate whether that particular address is valid or not (by start date and end date and valid flag)
    
    Patient table
    =============
    
    Patient_id          First_name    last_name
    
    1                   sanjay        kumar
    2                   ajay          singh
    3                   Mike          John
    
    
    Adress table
    ============
    
    address_id       patient_id       adresss       city       type       startdate        enddate      valid_flg
    
    1                   1             6222         dsadsa           P          01/01/2007       01/01/2010
    2                   1             63333        dsad             M          01/02/2006       01/01/2007      N
    3                   1             64564         fdf              M          01/01/2008       07/01/2009      
    4                   1             654757       fsdfsa          D          01/02/2008       09/10/2009  
    5                   2             fsdfsd       fsdfsd            M          01/03/2007       09/10/2009   
    6                   2             jhkjk        dsad              D          01/01/2007       10/10/2010   
    7                   3             asfd         sfds               D          01/02/2008       10/10/2009      
    
    
    output
    =====
    
    1        sanjay       kumar            6222       dsadsa      P          01/01/2007        01/01/2010     
    2        ajay         singh            fsdfsd     fsdfsd       M          01/03/2007        09/10/2009 
    3        mike         john              asfd       sfds        D          01/02/2008        10/10/2009
    Thanks in advance
    Phani

    Hello, Fabienne,.

    This race for you (twisted code of Sarma):

    SELECT patient_id, first_name, last_name, address, city, type, startdate, enddate
     FROM (
      SELECT a.patient_id patient_id, first_name, last_name, address, city, type, startdate, enddate,
                 ROW_NUMBER() OVER (PARTITION BY p.patient_id ORDER BY CASE type WHEN 'P' THEN 1
                                                                          WHEN  'M' THEN 2
                                                                          WHEN  'D' THEN 3
                                                                        END) rn
        FROM  patient p
        JOIN  address a ON (p.patient_id = a.patient_id )
       WHERE NVL(valid_flg, 'X') != 'N'
         AND SYSDATE BETWEEN startdate AND  NVL(enddate, SYSDATE)
         )
    WHERE rn = 1; 
    

    Edit, currently in the trial:

    With Patient AS (
    SELECT 1  Patient_id , 'sanjay' First_name, 'kumar'  last_name FROM DUAL UNION ALL
    SELECT 2, 'ajay', 'singh' FROM DUAL UNION ALL
    SELECT 3, 'Mike', 'John' FROM DUAL),
    Address AS (
    SELECT 1   address_id, 1  patient_id, '6222'    address, 'dsadsa'   city, 'P'  type, to_date('01/01/2007', 'DD/MM/YYYY')  startdate, to_date('01/01/2010', 'DD/MM/YYYY')  enddate, NULL  valid_flg FROM DUAL UNION ALL
    SELECT 2,1,'63333','dsad','M', to_date('01/02/2006', 'DD/MM/YYYY'), to_date('01/01/2007', 'DD/MM/YYYY'),  ' N'  FROM DUAL UNION ALL
    SELECT 3,1,'64564','fdf','M', to_date('01/01/2008', 'DD/MM/YYYY'), to_date('07/01/2009', 'DD/MM/YYYY'), NULL  FROM DUAL UNION ALL
    SELECT 4,1,'654757','fsdfsa','D', to_date('01/02/2008', 'DD/MM/YYYY'), to_date('09/10/2009', 'DD/MM/YYYY'),  NULL  FROM DUAL UNION ALL
    SELECT 5,2,'fsdfsd ','fsdfsd','M', to_date('01/03/2007', 'DD/MM/YYYY'), to_date('09/10/2009', 'DD/MM/YYYY'), NULL  FROM DUAL UNION ALL
    SELECT 6,2,' jhkjk','dsad','D', to_date('01/01/2007', 'DD/MM/YYYY'), to_date('10/10/2010', 'DD/MM/YYYY'),  NULL  FROM DUAL UNION ALL
    SELECT 7,3,'asfd',' sfds',' D', to_date('01/02/2008', 'DD/MM/YYYY'), to_date('10/10/2009', 'DD/MM/YYYY'),  NULL  FROM DUAL)
    -- end test data
     SELECT patient_id, first_name, last_name, address, city, type, startdate, enddate
     FROM (
      SELECT a.patient_id patient_id, first_name, last_name, address, city, type, startdate, enddate,
                 ROW_NUMBER() OVER (PARTITION BY p.patient_id ORDER BY CASE type WHEN 'P' THEN 1
                                                                          WHEN  'M' THEN 2
                                                                          WHEN  'D' THEN 3
                                                                        END) rn
        FROM  patient p
        JOIN  address a ON (p.patient_id = a.patient_id )
       WHERE NVL(valid_flg, 'X') != 'N'
         AND SYSDATE BETWEEN startdate AND  NVL(enddate, SYSDATE)
         )
    WHERE rn = 1; 
    
    PATIENT_ID FIRST_ LAST_ ADDRESS CITY   TY STARTDATE ENDDATE
    ---------- ------ ----- ------- ------ -- --------- ---------
             1 sanjay kumar 6222    dsadsa P  01-JAN-07 01-JAN-10
             2 ajay   singh fsdfsd  fsdfsd M  01-MAR-07 09-OCT-09
             3 Mike   John  asfd     sfds  D 01-FEB-08 10-OCT-09
    
  • Need a Suggestion tune the SQL query

    Hello


    There is a view that is created that takes 17 seconds to run the query, when I split the query and run each query prend.15 seconds to run. Below the query I need to improve the performance of the code if you need your suggestion please order to tweek so this time take for execution to become less

    SELECT "Parature'"Source. "
    NULL 'retailer ',.
    reseller_name "reseller."
    NULL city "reseller."
    NULL state "reseller."
    A.Country "dealer Country."
    DECODE (a.state, "ACPA", "ACPA", 'EMEA', 'EMEA', NULL, 'Unknown', 'US') "Dealer Theater",
    NULL "Customer Name,"
    NO city 'customer ',.
    'Client state', NULL
    NULL 'country of the customer. "
    NULL "customer Theater."
    NULL "sales book Date."
    NULL "Ship Date."
    c.sales_order_number 'Sales Order Number',
    C.Po_Number "Number"
    controller_model_number_1 "product name."
    TRIM (UPPER (serial_number_1)) 'product serial number.
    c.contract_id "Contract ID",
    product_name 'name of support. "
    To_date (c.contract_purchase_date) "Start Date"
    To_date (c.contract_expiration_date) 'Expiry Date',
    NULL "header Status."
    NULL "status of line."
    NULL 'line Type. "
    NULL "reason for termination of employment."
    NULL 'location_id. "
    NULL 'Product_id '.
    Of edb_assets c,.
    edb_accounts one
    WHERE controller_model_number_1! = 'NULL '.
    AND Serial_Number_1! = 'NULL '.
    AND C.Amid = A.Amid (+)

    UNION
    SELECT "Parature'"Source. "
    NULL 'retailer ',.
    reseller_name "reseller."
    NULL city "reseller."
    NULL state "reseller."
    A.Country "dealer Country."
    DECODE (a.state, "ACPA", "ACPA", 'EMEA', 'EMEA', NULL, 'Unknown', 'US') "Dealer Theater",
    NULL "Customer Name,"
    NO city 'customer ',.
    'Client state', NULL
    NULL 'country of the customer. "
    NULL "customer Theater."
    NULL "sales book Date."
    NULL "Ship Date."
    c.sales_order_number 'Sales Order Number',
    C.Po_Number "Number"
    controller_model_number_2 "product name."
    TRIM (UPPER (serial_number_2)) 'product serial number.
    c.contract_id "Contract ID",
    product_name 'name of support. "
    To_date (c.contract_purchase_date) "Start Date"
    To_date (c.contract_expiration_date) 'Expiry Date',
    NULL "header Status."
    NULL "status of line."
    NULL 'line Type. "
    NULL "reason for termination of employment."
    NULL 'location_id. "
    NULL 'Product_id '.
    Of edb_assets c,.
    edb_accounts one
    WHERE controller_model_number_2! = 'NULL '.
    AND serial_number_2! = 'NULL '.
    AND C.Amid = A.Amid (+)
    UNION

    SELECT "Parature'"Source. "
    NULL 'retailer ',.
    reseller_name "reseller."
    NULL city "reseller."
    NULL state "reseller."
    A.Country "dealer Country."
    DECODE (a.state, "ACPA", "ACPA", 'EMEA', 'EMEA', NULL, 'Unknown', 'US') "Dealer Theater",
    NULL "Customer Name,"
    NO city 'customer ',.
    'Client state', NULL
    NULL 'country of the customer. "
    NULL "customer Theater."
    NULL "sales book Date."
    NULL "Ship Date."
    c.sales_order_number 'Sales Order Number',
    C.Po_Number "Number"
    controller_model_number_3 "product name."
    TRIM (UPPER (serial_number_3)) 'product serial number.
    c.contract_id "Contract ID",
    product_name 'name of support. "
    To_date (c.contract_purchase_date) "Start Date"
    To_date (c.contract_expiration_date) 'Expiry Date',
    NULL "header Status."
    NULL "status of line."
    NULL 'line Type. "
    NULL "reason for termination of employment."
    NULL 'location_id. "
    NULL 'Product_id '.
    Of edb_assets c,.
    edb_accounts one
    WHERE controller_model_number_3! = 'NULL '.
    AND serial_number_3! = 'NULL '.
    AND C.Amid = A.Amid (+)

    UNION
    SELECT "Parature'"Source. "
    NULL 'retailer ',.
    reseller_name "reseller."
    NULL city "reseller."
    NULL state "reseller."
    A.Country "dealer Country."
    DECODE (a.state, "ACPA", "ACPA", 'EMEA', 'EMEA', NULL, 'Unknown', 'US') "Dealer Theater",
    NULL "Customer Name,"
    NO city 'customer ',.
    'Client state', NULL
    NULL 'country of the customer. "
    NULL "customer Theater."
    NULL "sales book Date."
    NULL "Ship Date."
    c.sales_order_number 'Sales Order Number',
    C.Po_Number "Number"
    controller_model_number_4 "product name."
    TRIM (UPPER (serial_number_4)) 'product serial number.
    c.contract_id "Contract ID",
    product_name 'name of support. "
    To_date (c.contract_purchase_date) "Start Date"
    To_date (c.contract_expiration_date) 'Expiry Date',
    NULL "header Status."
    NULL "status of line."
    NULL 'line Type. "
    NULL "reason for termination of employment."
    NULL 'location_id. "
    NULL 'Product_id '.
    Of edb_assets c,.
    edb_accounts one
    WHERE controller_model_number_4! = 'NULL '.
    AND serial_number_4! = 'NULL '.
    AND C.Amid = A.Amid (+)

    UNION
    SELECT "Parature'"Source. "
    NULL 'retailer ',.
    reseller_name "reseller."
    NULL city "reseller."
    NULL state "reseller."
    A.Country "dealer Country."
    DECODE (a.state, "ACPA", "ACPA", 'EMEA', 'EMEA', NULL, 'Unknown', 'US') "Dealer Theater",
    NULL "Customer Name,"
    NO city 'customer ',.
    'Client state', NULL
    NULL 'country of the customer. "
    NULL "customer Theater."
    NULL "sales book Date."
    NULL "Ship Date."
    c.sales_order_number 'Sales Order Number',
    C.Po_Number "Number"
    controller_model_number_5 "product name."
    TRIM (UPPER (serial_number_5)) 'product serial number.
    c.contract_id "Contract ID",
    product_name 'name of support. "
    To_date (c.contract_purchase_date) "Start Date"
    To_date (c.contract_expiration_date) 'Expiry Date',
    NULL "header Status."
    NULL "status of line."
    NULL 'line Type. "
    NULL "reason for termination of employment."
    NULL 'location_id. "
    NULL 'Product_id '.
    Of edb_assets c,.
    edb_accounts one
    WHERE controller_model_number_5! = 'NULL '.
    AND serial_number_5! = 'NULL '.
    AND C.Amid = A.Amid (+)
    UNION
    SELECT "Source", "ERP"
    Imv.Bill_To 'retailer ',.
    Imv.Ship_To "dealer."
    Ship_To_City "Dealer City."
    Ship_To_State "State dealer."
    Edb2_Global.Country_Name_Theater (Imv.Ship_To_Country, 'COUNTRY') 'dealer country. "
    Edb2_Global.Country_Name_Theater (Imv.Ship_To_Country, 'THÉÂTRE') 'dealer Theater. "
    Cl.Company_Name "name of the customer."
    Cl.City "customer's city."
    Cl.State "State of the customer."
    Edb2_Global.Country_Name_Theater (cl.) Country, 'COUNTRY') 'country of the customer. "
    Edb2_Global.Country_Name_Theater (cl.) Country, 'THEATER') "customer Theater."
    Imv.So_Booked_Date "Date from the sale of book."
    Imv.Ship_Date "Delivery Date"
    Imv.Order_Number "client order number."
    Imv.Cust_Po_Number "Number"
    Cp.Item_Name "product name."
    Cp.Product_Serial_Number "serial number of product."
    To_char (Imv.contract_number) "Contract ID"
    Imv.Service_Description "name of support."
    Imv.Service_Start_Date "Start Date"
    Imv.Service_End_Date "expiration Date."
    Imv.Header_Status "header Status."
    Imv.Line_Status "status of line."
    Imv.Line_Type 'line Type. "
    Imv.Termination_Reason "reason for termination of employment."
    Cl.Location_Id 'location_id. "
    CP.ID "Product_id".
    Of ib_support_contracts_mv imv.
    customer_products cp,
    customer_locations cl
    WHERE superior (Trim (Imv.Serial_Number)) = Upper (Trim (Cp.Product_Serial_Number (+)))
    AND Cp.Location_Id = Cl.Location_Id (+)
    /


    There is a Union for each request, please suggest how tweek

    Thank you
    Sudhir

    A quick look indicates that first 5 select queries are that even accepting the 2 conditions

    WHERE controller_model_number_1! = 'NULL '.
    AND Serial_Number_1! = 'NULL '.

    Use SEPARATE and Clause OR reduce these 5 queries in one like that

    SELECT DISTINCT
               .....
               ......  
    
      FROM edb_assets       c
          ,edb_accounts     a
    WHERE  C.Amid = A.Amid(+)
      AND  (
              (     controller_model_number_1 != 'NULL'
                AND Serial_Number_1 != 'NULL'
              )
             OR
              (     controller_model_number_2 != 'NULL'
                AND Serial_Number_2 != 'NULL'
              )
             OR
              (     controller_model_number_3 != 'NULL'
                AND Serial_Number_3 != 'NULL'
              )
             OR
              (     controller_model_number_4 != 'NULL'
                AND Serial_Number_4 != 'NULL'
              )
             OR
              (     controller_model_number_5 != 'NULL'
                AND Serial_Number_5 != 'NULL'
              )
    
           )
    

    Concerning
    Arun

    Published by: Arun Kumar Gupta on May 9, 2012 12:10

  • need help to write a conditional query recordset

    I have two fields or not in the database. VeteranMarker and VeteranNoMarker. Answering one can be Y or N.
    I want to write a statement for my detail page where there is a label "veteran? If VeteranMarker or VeteranNoMarker has a Y in the database, then I want to display "YES" next to the label of "veteran? If neither has a Y, then I want to say 'NO '.

    The recordset is called DetailRS1, the fields would be so (I think) DetailRS1.VeteranMarker and DetailRS1.VeteranNoMarker.

    I have no idea how to write a conditional statement to achieve this.

    Thanks in advance,
    Miriam

    I think I have it solved. Here is the code, and it seems to work. If this is correct, I hope it can help someone else too.

  • Write a SQL query with lines in columns

    All the

    I need help in writing a SQL query with lines in columns, let give u an example...

    drop table activity;

    CREATE TABLE 'ACTIVITY '.

    (

    "PROJECT_WID" NUMBER (22.0) NOT NULL,

    VARCHAR2 (150 CHAR) "PROJECT_NO."

    VARCHAR2 (800 CHAR) 'NAME '.

    );

    Insert in the ACTIVITY (PROJECT_WID, PROJECT_NO, NAME) values (1683691, '10007', 12-121');

    Insert in the ACTIVITY (PROJECT_WID, PROJECT_NO, NAME) values (1684994, '10008', 12-122');

    Insert in the ACTIVITY (PROJECT_WID, PROJECT_NO, NAME) values (1686296, '10009', 12-123');

    Insert in the ACTIVITY (PROJECT_WID, PROJECT_NO, NAME) values (2225222, '9040', 12-124');

    drop table lonet;

    CREATE TABLE 'LONET.

    (

    VARCHAR2 (150 CHAR) "NAME."

    NUMBER OF THE "ROOT."

    VARCHAR2 (150 CHAR) "ENTRYVALUE".

    );

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ("GAC", 1683691, "LDE");

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('NAM', 1683691, 'LME');

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('BAG', 1683691, 'ICE');

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('PAP', 1683691, 'IKE');

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('NAM', 1686291, "QTY");

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('PAP', 1686291, 'MAX');

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ("GAC", 1684994, "MTE");

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('PAP', 1684994, 'MAC');

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('FMT', 1684994, 'NICE');

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('FMR', 1684994, 'RAY');

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('BAG', 1686296, "CAQ");

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ("PAP", 1686296, "QAQ");

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ("VANESSA", 1686296, "THEW");

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ("ANDR", 1686296, "REYL");

    commit;

    Link: activity.project_wid = lonet.root

    look like output

    Project_wid Project_no NAME GAC NAM BAG RAC
    16836911000712-121LDELMELCELKE
    16849941000812-122MTEnullnullMAC
    16862961000912-123nullnullCAQQAQ
    2225222904012-124nullnullnullnull

    two problems, in that I am running

    1. I dono how simply we can convert rows to columns

    2. for root = 1683691, there are double NAM and RAC in lonet table... ideally these data should not be there, but since its here, we can take a MAX so that it returns a value

    3. There are undesirables who should be ignored

    Once again my thought process is that we join the activity and 4 alias table lonet.

    ask for your help in this

    Thank you

    Hello

    This is called pivoting.

    Here's a way to do it:

    WITH relevant_data AS

    (

    SELECT a.project_wid, a.project_no, b.SID

    , l.name AS lonet_name, l.entryvalue

    Activity one

    LEFT OUTER JOIN lonet l.root = a.project_wid l

    )

    SELECT *.

    OF relevant_data

    PIVOT (MAX (entryvalue)

    FOR lonet_name IN ("GAC" IN the gac

    "NAM" AS nam

    'BAG' IN the bag

    "RAC" AS cars

    )

    )

    ORDER BY project_wid

    ;

    Output:

    PROJECT_WID PROJECT_NO GAC NAM BAG RAC NAME

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

    1683691 12 - 10007 121 LDE LME LCE LKE

    1684994 MAC MTE 10008 12-122

    1686296 12 - 10009 123 QAC QAQ

    2225222 9040 12 - 124

    To learn more about swivel, see the FAQ in the Forum: Re: 4. How can I convert rows to columns?

    Thanks for posting the CREATE TABLE and INSERT statements; It's very useful!

  • Need help to build the query/pl-sql block to get the query result and the name of column from DB table in the form of key-value pairs.

    Hi Experts,

    I have a DB table has columns of more than 50.

    I question this table, it should only return one line at any time. as sqldeveloper below image.

    here, I need to build block pl/sql-query, Discover the column in the table as a key and query result as values.

    Eg:     Key                         -  Value

    TASK_EVENT_ID - 1765

    EVENT_TYPE - ASR_UPDATE

    ... etc until all of the columns in my table.

    Experts please comment on that point, appreciate your help on this.

    Thank you

    -Vincent.

    Here is an approach using DBMS_SQL to iterate over the columns of key / value to assign... (Little code snipped for brevity)

    create or replace procedure (task_expired)

    v_store_id in full,

    v_task_action_id in full,

    v_job_id in full

    )

    as

    -[SNIP code...]

    v_sql VARCHAR2 (4000): = ' select * from my_table where PK = 123';  -Your SQL here!

    v_v_val VARCHAR2 (4000);

    v_n_val NUMBER;

    v_d_val DATE;

    v_ret NUMBER;

    c NUMBER;

    d NUMBER;

    col_cnt INTEGER.

    f BOOLEAN;

    rec_tab DBMS_SQL. DESC_TAB;

    col_num NUMBER;

    vAsString VARCHAR2 (4000);

    BEGIN

    -[SNIP code...]

    Message_properties. CORRELATION: = "EDF_EVENT";

    MSG: = SYS. AQ$ _JMS_BYTES_MESSAGE. Construct();

    Msg.set_string_property ('queueName', ' shipping/csi_cth');

    Msg.set_string_property ('MODE', 'CR8');

    c: = DBMS_SQL. OPEN_CURSOR;

    DBMS_SQL. PARSE (c, v_sql, DBMS_SQL. NATIVE);

    d: = DBMS_SQL. Execute (c);

    DBMS_SQL. DESCRIBE_COLUMNS (c, col_cnt, rec_tab);

    1.col_cnt J

    LOOP

    CASE rec_tab (j) .col_type

    WHEN 2 THEN

    DBMS_SQL. DEFINE_COLUMN (c, j, v_n_val);      -Number

    WHEN 12 CAN

    DBMS_SQL. DEFINE_COLUMN (c, j, v_d_val);      -Date

    ON THE OTHER

    DBMS_SQL. DEFINE_COLUMN (c, j, v_v_val, 2000);   -Else treat as varchar2

    END CASE;

    END LOOP;

    LOOP

    v_ret: = DBMS_SQL. FETCH_ROWS (c);

    WHEN OUTPUT v_ret = 0;

    1.col_cnt J

    LOOP

    -Fetch each column to the correct data type based on coltype

    CASE rec_tab (j) .col_type

    WHEN 2 THEN

    DBMS_SQL. COLUMN_VALUE (c, j, v_n_val);

    vAsString: = to_char (v_n_val);

    WHEN 12 CAN

    DBMS_SQL. COLUMN_VALUE (c, j, v_d_val);

    vAsString: = to_char (v_d_val, ' DD/MM/YYYY HH24:MI:SS');

    ON THE OTHER

    DBMS_SQL. COLUMN_VALUE (c, j, v_v_val);

    vAsString: = v_v_val;

    END CASE;

    Msg.set_string_property (rec_tab (j) .col_name, vAsString);

    END LOOP;

    END LOOP;

    DBMS_SQL. CLOSE_CURSOR (c);

    DBMS_AQ. ENQUEUE (queue_name-online 'cbus.aqjms_common',

    Enqueue_options => Enqueue_options,

    Message_properties => Message_properties,

    Payload-online msg,

    Msgid => Message_handle);

    dbms_output.put_line ('00 Msgid =' |) Message_handle);

    dbms_output.put_line('===Done=');

    -[SNIP code...]

    END;

    /

Maybe you are looking for