Select query for rows where condition 1

Say I have a table, tb1, that has the following entries:
FName LName
Code
John Doe
xxx
Jane Doe
xxx
Steve Harper
x
Barrak Obama
x
George Bush
xxxx
Bill Clinton
xx
I'd like to write a select query that only lists the rows where the count for Code is > 1, i.e not display the last two rows from the above entry. How would I go about writing that select query.
Thanks.

Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
This is minimal polite behavior on SQL forums. 
>> Say I have a table, tb1, that has the following entries: <<
Are you this rude or really ignorant and too lazy to read the Netiquette at the start to this forum? Why do you think you do not need a key? No DDL? No constraints? And , why, why do you think that “tb1” is a precise, ISO-11179 conforming table name? 
Let's make this a table of rude posters rated on a 4-star scale. 
CREATE TABLE Rude_Posters
(first_name VARCHAR(15) NOT NULL, 
 last_name VARCHAR(15) NOT NULL, 
 PRIMARY KEY (first_name, last_name), 
 rudeness_code VARCHAR (4) NOT NULL
   CHECK (rudeness_code IN ('x', 'xx', 'xxx', 'xxxx'));
INSERT INTO Rude_Posters
VALUES
('John', 'Doe', 'xxx'), 
('Jane', 'Doe', 'xxx'), 
('Steve', 'Harper', 'x'), 
('Barrack', 'Obama', 'x'), 
('George', 'Bush', 'xxxx'), 
('Bill', 'Clinton', 'xx');
>> I'd like to write a SELECT query that only lists the rows where the count for rudeness_code is > 1, i.e not display the last two rows from the above entry. << 
The rudeness scale is based on stars, so to ask for an integer value is like saying “on a scale from 1 to 10, what is the color of your favorite letter of the alphabet?”
Next, the number of stars and your narrative do not match. Did you want to say WHERE rudeness_code IN ('xx' 'xxx', 'xxxx')? 
Please stop programming SQL until you have gotten more education. At this point, you do not know enough to ask a question. 
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL

Similar Messages

  • Dynamic select query with dynamic where condition

    Hi all,
    I want to use the dynamic select query with dynamic where condition. For that I used the below code but I am getting dump when using this code.
    Please advice, if there is any other way to achieve this requirement.
    Thanks,
    Sanket Sethi
    Code***************
    PARAMETERS: p_tabnam      TYPE tabname,
                p_selfl1      TYPE edpline,
                p_value       TYPE edpline,
                p_where1      TYPE edpline .
    DATA: lt_where    TYPE TABLE OF edpline,
          lt_sel_list TYPE TABLE OF edpline,
          l_wa_name   TYPE string,
          ls_where    TYPE edpline,
          l_having    TYPE string,
          dref        TYPE REF TO data,
          itab_type   TYPE REF TO cl_abap_tabledescr,
          struct_type TYPE REF TO cl_abap_structdescr,
          elem_type   TYPE REF TO cl_abap_elemdescr,
          comp_tab    TYPE cl_abap_structdescr=>component_table,
          comp_fld    TYPE cl_abap_structdescr=>component.
    TYPES: f_count TYPE i.
    FIELD-SYMBOLS : <lt_outtab> TYPE ANY TABLE,
    *                <ls_outtab> TYPE ANY,
                    <l_fld> TYPE ANY.
    struct_type ?= cl_abap_typedescr=>describe_by_name( p_tabnam ).
    elem_type   ?= cl_abap_elemdescr=>describe_by_name( 'F_COUNT' ).
    comp_tab = struct_type->get_components( ).
    comp_fld-name = 'F_COUNT'.
    comp_fld-type = elem_type.
    APPEND comp_fld TO comp_tab.
    struct_type = cl_abap_structdescr=>create( comp_tab ).
    itab_type   = cl_abap_tabledescr=>create( struct_type ).
    l_wa_name = 'l_WA'.
    CREATE DATA dref TYPE HANDLE itab_type.
    ASSIGN dref->* TO <lt_outtab>.
    *CREATE DATA dref TYPE HANDLE struct_type.
    *ASSIGN dref->* TO <ls_outtab>.
    * Creation of the selection fields
    APPEND p_selfl1 TO lt_sel_list.
    APPEND 'COUNT(*) AS F_COUNT' TO lt_sel_list.
    ** Creation of the "where" clause
    *CONCATENATE p_selfl1 '= '' p_value ''.'
    *            INTO ls_where
    *            SEPARATED BY space.
    *APPEND ls_where TO lt_where.
    * Creation of the "where" clause
    APPEND p_where1 TO lt_where.
    * Creation of the "having" clause
    l_having = 'count(*) >= 1'.
    * THE dynamic select
    SELECT          (lt_sel_list)
           FROM     (p_tabnam)
           INTO CORRESPONDING FIELDS OF TABLE <lt_outtab>.
    *       WHERE    (lt_where).

    Hi Sanket,
    The above given logic of mine works for you, put the code in the If condition and try-
    just like below:
    IF NOT P_EBELN IS INITIAL.
    lt_where = '& = ''&'' '.
    REPLACE '&' WITH p_ebeln INTO lt_where.
    REPLACE '&' WITH field_value INTO lt_where.
    SELECT (lt_sel_list) INTO CORRESPONDING FIELDS OF TABLE <lt_outtab>
    FROM (p_tabnam)
    WHERE (lt_where).
    ENDIF.
    thanks\
    Mahesh

  • Select query with optional where condition

    Hi,
    Can Anybody help me out in the following problem?
    I have the following query in a procedure.
    SELECT replace(shipper_name,'\',' ') as shipper,
    sum(teus / cntSailings) as teus
    FROM VW_CONTRIBUTION,
    VW_TOTAL_SAILINGS
    WHERE VW_CONTRIBUTION.dir = VW_TOTAL_SAILINGS.DIR
    AND VW_CONTRIBUTION.line = VW_TOTAL_SAILINGS.LINE
    AND VW_CONTRIBUTION.accounting_month = VW_TOTAL_SAILINGS.ACCOUNTING_MONTH
    AND VW_CONTRIBUTION.accounting_year = VW_TOTAL_SAILINGS.ACCOUNTING_YEAR
    AND VW_CONTRIBUTION.Principal = arg_principal
    AND VW_CONTRIBUTION.Dir = arg_direction
    AND VW_CONTRIBUTION.line in ( arg_service )
    AND VW_CONTRIBUTION.POL_country = arg_pol
    AND VW_CONTRIBUTION.POd_country = arg_pod
    AND VW_CONTRIBUTION.salesOffice = arg_SalesOffice
    AND VW_CONTRIBUTION.salesregion = arg_SalesRegion
    AND VW_CONTRIBUTION.cargo_type = arg_txtCargoType
    AND VW_CONTRIBUTION.eqgroup = arg_ContType
    AND VW_CONTRIBUTION.eq_size = arg_txtSize
    AND VW_CONTRIBUTION.acct_date between arg_from_date and arg_end_date
    GROUP BY shipper_name
    ORDER BY teus desc;
    Here some of the arguments are optional(Eg : VW_CONTRIBUTION.salesOffice, AND VW_CONTRIBUTION.eqgroup etc. ) and the values can be null. When they are null, I want them to be excluded from the where condition. Can anybody suggest me a solution for this?
    Thanks,
    Shalet.

    I guess i misunderstood your original question.
    The clause
    AND (VW_CONTRIBUTION.salesOffice = arg_SalesOffice OR VW_CONTRIBUTION.salesOffice IS NOT NULL)
    will cause the where clause to evaluate to FALSE anytime salesOffice IS NULL so the record will be excluded.
    I thought you were asking how to not compare the value if the field contained a NULL.
    Glad you found what you wanted.

  • How to write the select query with complex where condition

    Hi all,
    Can u help me in writing  following select query.
    select * from zu1cd_corr where time_stamp between firstday and lastday .
    In the above query time_stamp contains the date and time.
    where as firstday and lastday contains the dates.
    I need to compare the date in the time_stamp with the firstday and lastday.
    But time_stamp contains the time also and it is char of 14 characters length.

    Hi,
    If that is the case u can do as advait specified....
    if the firstday and secondday are select-options then declare two more variables having 14 character length and then concatenate '000000' to firstday variable and '240000' to last day variable and then write ur query.
    CLEAR : lv_firstday,
                 lv_lastday.
    concatenate firstday '000000' to lv_firstday.
    concatenate lastday '240000' to lv_lastday.
    ranges : r_Date for zu1cd_corr-time_stamp.
    r_date-sign = 'I'.
    r_date-option = 'BT'.
    r_Date-low = lv_firstday.
    r_Date-high = lv_lastday.
    append r_date.
    select * from zu1cd_corr  into table it_zu1cd_corr where time_stamp in  r_Date.
    I hope it helps.
    Regards,
    Nagaraj

  • Can any one send select query for this?

    Hi,
    can any one plese send select query for the following query.please send as early as possible.
    Loop through the I_BSID internal table to fill records in I_OUTPUT.Combine data from I_BSID, I_KNKK, I_KNKK_KNKLI, I_KNA1 and I_KNVV into I_OUTPUT based on the linking conditions .Field Description Source are
    I_OUTPUT-BUKRS     Company code     I_BSID-BUKRS
    I_OUTPUT-KUNNR     Customer number     I_BSID-KUNNR
    I_OUTPUT-NAME1     Customer Name     I_KNA1-NAME1
    I_OUTPUT-KNKLI     Credit account     I_KNKK-KNKLI
    I_OUTPUT-KDGRP     Customer Group     I_KNKK-KDGRP
    I_OUTPUT-KLIMK     Credit Limit     I_KNKK_KNKLI-KLIMK
    I_OUTPUT-KVGR1     Business Unit     I_KNVV-KVGR1
    I_OUTPUT-REBZG     Invoice Number     I_BSID-REBZG
    I_OUTPUT-BLDAT     Invoice Date     I_BSID-BLDAT
    I_OUTPUT-WAERS     Document Currency     I_BSID-WAERS
    I_OUTPUT-DUE_DATE     Due Date     Based on below
    Calculation
      Get the Payment terms days combining I_BSID and I_T052 based on the linking conditions mentioned above.    Note : a) Baseline Date : If baseline date I_BSID-ZFBDT is blank , use the Document Date.b) Payment Term Days :If I_BSID-ZBD3T is not blank, take this as Payment Term Days for Due date calculation.
                       If I_BSID-ZBD3T is Blank, then get payment term days from I_T052 based on I_BSID-ZTERM. If there are more than one record in I_T052 for the given Payment term, get the day part from baseline date and select the first record where the day limit I_T052-ZTAGG is greater than the day part.If I_BSID-ZBD3T is blank and I_BSID-ZTERM is also blank, then take Y000 (Due Immediately) as Payment term and proceed with the above logic. Set the payment term field blank while printing.
    Calculate Due date : For Debits, Determine Due Date = Baseline Date + Payment term Days(not discount days)                                                          For  Credits  Due date = Baseline date.Then, move the amount I_BSID-DMBTR to respective buckets (Not yet Due, Current Due, Past due 1-30, Past Due 31-60 etc.)  Based on the due date.
    Thanks&Regards,
    praveen kumar.A

    HI,
    To get Open Items you can use Function module:
    data:i_items TYPE STANDARD TABLE OF rfpos.
    CALL FUNCTION 'CUSTOMER_OPEN_ITEMS'
    EXPORTING
    bukrs = p_bukrs
    kunnr = wa_customer-kunnr
    TABLES
    t_postab = i_items
    EXCEPTIONS
    no_open_items = 1
    OTHERS = 2.
    Table I_items will have all the open items for that Customer in the given company code.
    Well for Clear Items: Try
    GET_CLEARED_ITEMS or FMITPOFM_CLEARED_ITEMS_GET.
    Hope it helps.
    Manish

  • Select Query for smart form-invoice

    Hi Folks,
    I have to fetch the following fields as per the requirement for desiging a invoice smartform.I had copied lb_bill_invoice smartform into z format.
    Can anyone here please give me the select query for the same.
    fields to fetched are as follows:-
    1.vbrp-arktx,
    2.vbrp-fkimg,
    3.konv-kbetr with respect to vbrk-knumv
    4.konv-kwert.
    And also what all I have to give in format interface and global definitions of the smartform.
    please help  me in this regard.
    Points will be given.
    K.Kiran.

    Hi,
    declare the variables V_arktx(40) and v_Qty like vbrp-fkimp  and other varaibles for Kbetr, kwert, knumv on the global definitions.
    select  single arktx fkimg into (v_arktx, v_qty) from vbrp
    where vbeln = LBBIL_IT_REFPURORD-BIL_NUMBER.
    select single knumv into v_knumv from vbrk where where vbeln = LBBIL_IT_REFPURORD-BIL_NUMBER.
    this select has to fire in the item level and in the loop.
    so have to write in the correct place.
    select kbetr kwert into (v_kbetr, v_kwert) from konv
    where where knumv = v_knumv and kposn = LBBIL_IT_REFPURORD-ITM_NUMBER.
    regards,
    anji

  • Select Query Based on date condition

    Hi ,
    Is it Possible.
    i want to run select query based on date condition.
    Eg...
    if the date between 01-jan-01 and 01-jan-05 then
    select * from table1;
    if the date between 02-jan-05 and 01-jan-08 then
    select * from table2;
    Becaz i have data in 2 diffrent tables , based on the date condition i wnt to run the select statement to diffrent tables.
    i dont want plsql here Just SQL needed.
    thanks,
    -R
    Edited by: infant_raj on May 5, 2009 11:48 PM

    Helo Kanish,
    this is not the one i was asking..
    wht i mean was .
    i use bind variable to get date while running the select statement , once i get the date then i want to choose any one of the table to run select query.
    EG..
    select col1,col2 from table1 where date between only if 01-jan-01 and 01-jan-05;
    select col1,col2 from table2 where date between only if 02-jan-05 and 01-jan-08;
    Run any one of the two . not all
    thanks,
    _raj                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to write selection Query for the following requirment.

    Hi All,
    I am new to ABAP, I need a help ,
    I need to select all plants(WERKS) from MARC at Plant/Material level,
    then I need to take all sales organozation(VKORG) from T001w,
    then I need the company code(BUKRS) from TVKO based on VKORG,
    then I need the currency key(WAERS) from T001 based on BUKRS,
    Can any one help me in writing selection Query for the same?
    Thanks All,
    Debrup.

    Hi,
    Its easy for you if you learn SELECT with JOIN to complete your task. So SEARCH the forum with SELECT statement and you will get a lot of examples using which you can write your own.
    If you struck up anywhere revert back.
    Regards
    Karthik D

  • Select query for fetching from 3 tables.

    Can we have a single Select query for fetching same fields (kappl,kschl,vkorg,vtweg,spart,kunwe,datbi,knuma,datab,knumh)
    from 3 tables >> KOTE707,KOTE708 and KOTE709 into an internal table for a particular KUNNR?
    Regards,
    Shashank.

    Hi,
    If you have kunnr field in all the 3 tables then it is possible. use inner join as below
    PARAMETERS: p_cityfr TYPE spfli-cityfrom,
                p_cityto TYPE spfli-cityto.
    DATA: BEGIN OF wa,
             fldate TYPE sflight-fldate,
             carrname TYPE scarr-carrname,
             connid   TYPE spfli-connid,
           END OF wa.
    DATA itab LIKE SORTED TABLE OF wa
                   WITH UNIQUE KEY fldate carrname connid.
    SELECT c~carrname p~connid f~fldate
           INTO CORRESPONDING FIELDS OF TABLE itab
           FROM ( ( scarr AS c
             INNER JOIN spfli AS p ON p~carrid   = c~carrid
                                  AND p~cityfrom = p_cityfr
                                  AND p~cityto   = p_cityto )
             INNER JOIN sflight AS f ON f~carrid = p~carrid
                                    AND f~connid = p~connid ).
    LOOP AT itab INTO wa.
      WRITE: / wa-fldate, wa-carrname, wa-connid.
    ENDLOOP.
    <b>Reward Points if this helps,</b>
    Satish

  • How to do outer join select query for an APEX report

    Hello everyone,
    I am Ann.
    I have one select statement that calculate the statistics for one month(October 2012 in this example)
    select ph.phase_number
    , sum ( (case
    WHEN ph.date_finished IS NULL OR ph.date_finished > last_day(TO_DATE('Oct 2012','MON YYYY'))
    THEN last_day(TO_DATE('Oct 2012','MON YYYY'))
    ELSE ph.date_finished
    END )
    - ph.date_started + 1) / count(def.def_id) as avg_days
    from phase_membership ph
    inner join court_engagement ce on ph.mpm_eng_id = ce.engagement_id
    inner join defendant def on ce.defendant_id = def.def_id
    where def.active = 1
    and ph.date_started <= last_day(TO_DATE('Oct 2012','MON YYYY'))
    and ph.active = 1
    and UPPER(ce.court_name) LIKE '%'
    group by rollup(phase_number)
    Result is as below
    Phase_Number     AVG_DAYS
    Phase One     8.6666666666666667
    Phase Two     14.6
    Phase Three     12
         11.4615365
    I have other select list mainly list the months between two date value.
    select to_char(which_month, 'MON YYYY') as display_month
    from (
    select add_months(to_date('Aug 2012','MON YYYY'), rownum-1) which_month
    from all_objects
    where
    rownum <= months_between(to_date('Oct 2012','MON YYYY'), add_months(to_date('Aug 2012','MON YYYY'), -1))
    order by which_month )
    Query result is as below
    DISPLAY_MONTH
    AUG 2012
    SEP 2012
    OCT 2012
    Is there any way that I can join these two select statement above to generate a result like:
    Month          Phase Number     Avg days
    Aug 2012     Phase One     8.666
    Sep 2012     Phase One     7.66
    Oct 2012     Phase One     5.66
    Aug 2012     Phase Two     8.666
    Sep 2012     Phase Two     7.66
    Oct 2012     Phase Two     5.66
    Aug 2012     Phase Three     8.666
    Sep 2012     Phase Three     7.66
    Oct 2012     Phase Three     5.66
    Or
    Month          Phase Number     Avg days
    Aug 2012     Phase One     8.666
    Aug 2012     Phase Two     7.66
    Aug 2012     Phase Three     5.66
    Sep 2012     Phase One     8.666
    Sep 2012     Phase Two     7.66
    Sep 2012     Phase Three     5.66
    Oct 2012     Phase One     8.666
    Oct 2012     Phase Two     7.66
    Oct 2012     Phase Three     5.66
    And it can be order by either Phase Number or Month.
    My other colleague suggest I should use an left outer join but after trying so many ways, I am still stuck.
    One of the select I tried is
    select a.display_month,b.* from (
    select to_char(which_month, 'MON YYYY') as display_month
    from (
    select add_months(to_date('Aug 2012','MON YYYY'), rownum-1) which_month
    from all_objects
    where
    rownum <= months_between(to_date('Oct 2012','MON YYYY'), add_months(to_date('Aug 2012','MON YYYY'), -1))
    order by which_month )) a left outer join
    ( select to_char(ph.date_finished,'MON YYYY') as join_month, ph.phase_number
    , sum ( (case
    WHEN ph.date_finished IS NULL OR ph.date_finished > last_day(TO_DATE(a.display_month,'MON YYYY'))
    THEN last_day(TO_DATE(a.display_month,'MON YYYY'))
    ELSE ph.date_finished
    END )
    - ph.date_started + 1) / count(def.def_id) as avg_days
    from phase_membership ph
    inner join court_engagement ce on ph.mpm_eng_id = ce.engagement_id
    inner join defendant def on ce.defendant_id = def.def_id
    where def.active = 1
    and ph.date_started <= last_day(TO_DATE(a.display_month,'MON YYYY'))
    and ph.active = 1
    and UPPER(ce.court_name) LIKE '%'
    group by to_char(ph.date_finished,'MON YYYY') , rollup(phase_number)) b
    on a.display_month = b.join_month
    but then I get an error
    SQL Error: ORA-00904: "A"."DISPLAY_MONTH": invalid identifier
    I need to display a report on APEX with option for people to download at least CSV format.
    I already have 1 inteactive report in the page, so don’t think can add another interactive report without using the iframe trick.
    If any of you have any ideas, please help.
    Thanks a lot.
    Ann

    First of all, a huge thanks for following this Frank.
    I have just started working here, I think the Oracle version is 11g, but not sure.
    To run Oracle APEX version 4, I think they must have at least 10g R2.
    This report is a bit challenging for me.I has never worked with PARTITION before.
    About the select query you suggested, I run , and it seems working fine, but if I try this,
    it return error ORA-01843: not a valid month
    DEFINE startmonth = "Aug 2012";
    DEFINE endmonth   = "Oct 2012";
    WITH     all_months     AS
         select add_months(to_date('&startmonth','MON YYYY'), rownum-1) AS which_month
         ,      add_months(to_date('&startmonth','MON YYYY'), rownum  ) AS next_month
         from all_objects
         where
         rownum <= months_between(to_date('&endmonth','MON YYYY'), add_months(to_date('&startmonth','MON YYYY'), -1))
    select TO_CHAR (am.which_month, 'Mon YYYY')     AS month
    ,      ph.phase_number
    , sum ( (case
    WHEN ph.date_finished IS NULL OR ph.date_finished > last_day(TO_DATE(am.which_month,'MON YYYY'))
    THEN last_day(TO_DATE(am.which_month,'MON YYYY'))
    ELSE ph.date_finished
    END )
    - ph.date_started + 1) / count(def.def_id) as avg_days
    FROM           all_months          am
    LEFT OUTER JOIN  phase_membership  ph  PARTITION BY (ph.phase_number)
                                        ON  am.which_month <= ph.date_started
                               AND am.next_month  >  ph.date_started
                               AND ph.date_started <= last_day(TO_DATE(am.which_month,'MON YYYY'))  -- May not be needed
                               AND ph.active = 1
    LEFT OUTER join  court_engagement  ce  on  ph.mpm_eng_id = ce.engagement_id
                                        and ce.court_name IS NOT NULL  -- or something involving LIKE
    LEFT OUTER join  defendant         def on  ce.defendant_id = def.def_id
                                        AND def.active = 1
    group by rollup(phase_number, am.which_month)
    ORDER BY  am.which_month
    ,            ph.phase_number
    ;Here is the shorted versions of the three tables:
    A_DEFENDANT, A_ENGAGEMENT, A_PHASE_MEMBERSHIP
    CREATE TABLE "A_DEFENDANT"
        "DEF_ID"     NUMBER NOT NULL ENABLE,
        "FIRST_NAME" VARCHAR2(50 BYTE),
        "SURNAME"    VARCHAR2(20 BYTE) NOT NULL ENABLE,
        "DOB" DATE NOT NULL ENABLE,
        "ACTIVE" NUMBER(2,0) DEFAULT 1 NOT NULL ENABLE,
        CONSTRAINT "A_DEFENDANT_PK" PRIMARY KEY ("DEF_ID"))
    Sample Data
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (101,'Joe','Bloggs',to_date('12/12/99','DD/MM/RR'),1);
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (102,'John','Smith',to_date('20/05/00','DD/MM/RR'),1);
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (103,'Jane','Black',to_date('15/02/98','DD/MM/RR'),1);
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (104,'Minnie','Mouse',to_date('13/12/88','DD/MM/RR'),0);
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (105,'Daisy','Duck',to_date('05/08/00','DD/MM/RR'),1);
    CREATE TABLE "A_ENGAGEMENT"
        "ENGAGEMENT_ID" NUMBER NOT NULL ENABLE,
        "COURT_NAME"    VARCHAR2(50 BYTE) NOT NULL ENABLE,
        "DATE_REFERRED" DATE,
        "DETERMINATION_HEARING_DATE" DATE,
        "DATE_JOINED_COURT" DATE,
        "DATE_TREATMENT_STARTED" DATE,
        "DATE_TERMINATED" DATE,
        "TERMINATION_TYPE" VARCHAR2(50 BYTE),
        "ACTIVE"           NUMBER(2,0) DEFAULT 1 NOT NULL ENABLE,
        "DEFENDANT_ID"     NUMBER,
        CONSTRAINT "A_ENGAGEMENT_PK" PRIMARY KEY ("ENGAGEMENT_ID"))
    Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (1,'AA',to_date('12/08/12','DD/MM/RR'),null,to_date('12/08/12','DD/MM/RR'),null,null,null,1,101);
    Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (2,'BB',to_date('01/09/12','DD/MM/RR'),null,to_date('02/09/12','DD/MM/RR'),null,null,null,1,102);
    Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (3,'AA',to_date('02/09/12','DD/MM/RR'),null,to_date('15/09/12','DD/MM/RR'),null,null,null,1,103);
    Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (4,'BB',to_date('01/10/12','DD/MM/RR'),null,to_date('02/10/12','DD/MM/RR'),null,null,null,1,105);
    CREATE TABLE "A_PHASE_MEMBERSHIP"
        "MPM_ID"       NUMBER NOT NULL ENABLE,
        "MPM_ENG_ID"   NUMBER NOT NULL ENABLE,
        "PHASE_NUMBER" VARCHAR2(50 BYTE),
        "DATE_STARTED" DATE NOT NULL ENABLE,
        "DATE_FINISHED" DATE,
        "NOTES"  VARCHAR2(2000 BYTE),
        "ACTIVE" NUMBER(2,0) DEFAULT 1 NOT NULL ENABLE,
        CONSTRAINT "A_PHASE_MEMBERSHIP_PK" PRIMARY KEY ("MPM_ID"))
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (1,1,'PHASE ONE',to_date('15/09/12','DD/MM/RR'),to_date('20/09/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (2,1,'PHASE TWO',to_date('21/09/12','DD/MM/RR'),to_date('29/09/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (3,2,'PHASE ONE',to_date('12/09/12','DD/MM/RR'),null,null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (4,3,'PHASE ONE',to_date('20/09/12','DD/MM/RR'),to_date('01/10/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (5,3,'PHASE TWO',to_date('02/10/12','DD/MM/RR'),to_date('15/10/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (6,4,'PHASE ONE',to_date('03/10/12','DD/MM/RR'),to_date('10/10/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (7,3,'PHASE THREE',to_date('17/10/12','DD/MM/RR'),null,null,0);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (8,1,'PHASE THREE',to_date('30/09/12','DD/MM/RR'),to_date('16/10/12','DD/MM/RR'),null,1);
    The requirements are:
    The user must be able to request the extract for one or more calendar months, e.g.
    May 2013
    May 2013 – Sep 2013.
    The file must contain a separate row for each calendar month in the requested range. Each row must contain the statistics computed for that calendar month.
    The file must also include a row of totals.
    The user must be able to request the extract for either Waitakere or Auckland or Consolidated (both courts’ statistics accumulated).
    Then the part that I am stuck is
    For each monitoring phase:
    Phase name (e.g. “Phase One”)
    Avg_time_in_phase_all_particip
    for each phase name,
    Add up days in each “phase name” Monitoring Phase, calculated as:
    If Monitoring Phase.Date Finished is NULL or > month end date,
    +(*Month end date* Minus Monitoring Phase.Date Started Plus 1)+
    Otherwise (phase is complete)
    +(Monitoring Phase.Date Finished Minus Monitoring Phase.Date Started Plus 1.)+
    Divide by the numbers of all participants who have engaged in “phase name”.
    This is the words of the Business Analyst,
    I try to do as required but still struggle to identify end_month for the above formula to display for the range of months.
    Of course, I can write two nested cursor. The first one run the list of month, then for each month, run the parameterised report.
    But I prefer if possible just use SQL statements, or at least a PL/SQL but return a query.
    With this way, I can create an APEX report, and use their CSV Extract function.
    Yes, you are right, court_name is one of the selection parameters.
    And the statistics is not exactly for one month. It is kind of trying to identify all phases that are running through the specified month (even phase.date_started is before the month start).
    This is the reason why I put the condition AND ph.date_started <= last_day(TO_DATE('Oct 2012','MON YYYY')) (otherwise I get negative avg_days)
    User can choose either one court "AA" or "BB" or combined which is all figures.
    Sorry for bombarding you a lot of information.
    Thanks a lot, again.
    Edited by: Ann586341 on Oct 29, 2012 9:57 PM
    Edited by: Ann586341 on Oct 29, 2012 9:59 PM

  • Select query for fields in selection screen

    SELECT * FROM hrus_d2
               INTO TABLE ta_list
               WHERE us_name IN subs_obj
               and begdat in date_ran.
              and enddat in date_ran
    How can I rewrite the above query for high and low ranges of date_ran field in condition? It doesn't allow in operator with date_ran-low.Can u please help me out

    Hi
    rahul
    SELECT *
    FROM hrus_d2
    INTO TABLE ta_list
    WHERE us_name IN subs_obj
    and begdat = date_ran-low
    and enddat = date_ran -high.
    u can write like this or i amnot getting why u r expliciting this date u can give directly as
    SELECT *
    FROM hrus_d2
    INTO TABLE ta_list
    WHERE us_name IN subs_obj
    date in date_ran.
    plzz reward if i am usefull to u in any way.. plzz dont forget to reward

  • Performance optimization on select query for all entries

    Hi All,
          I want to optimize the select query in my Program.
         The select query is taking lot of time to search the records for the given condition in the where clause
         and more interestingly there are no records fetched from the database as the where condition does not matches. 
         It is taking more than 30 min to search the record and the result is no record found.
         Below is my select query. I have also created the secondary Index for the same.
         In My opinion FOR ALL ENTRIES is taking lot of time. Because there are more than 1200 records in internal table t_ajot     
          select banfn  bnfpo     bsart      txz01   matnr   Werks   lgort     matkl    reswk   menge     meins   flief      ekorg  
              INTO CORRESPONDING FIELDS OF TABLE t_req
              FROM eban
                FOR ALL ENTRIES IN t_ajot
              WHERE matkl >= t_ajot-matkl_low
                AND matkl <= t_ajot-matkl_high
                AND werks = t_ajot-werks
                AND loekz = ' '
                AND badat IN s_badat
                AND bsart = 'NB'.  
        Please suggest.

    Hi,
    that,
    FOR ALL ENTRIES IN t_ajot
    WHERE matkl >= t_ajot-matkl_low
    AND matkl <= t_ajot-matkl_high
    AND werks = t_ajot-werks
    AND loekz = ' '
    AND badat IN s_badat
    AND bsart = 'NB'.
    looks strange.
    However:
    How does your index look like?
    What executoin plan do you get?
    How do the statistics look like?
    Whats the content of the variables t_ajot-... and s_badata?
    Kind regards,
    Hermann

  • Issue with select query for secondary index

    Hi all,
    I have created a secondary index A on mara table with fields Mandt and Packaging Material Type VHART.
    Now i am trying to write a report
    Tables : mara.
    data : begin of itab occurs 0.
    include structure mara.
    data  : end of itab.
    *select * from mara into table itab*
    CLIENT SPECIFIED where
      MANDT = SY-MANDT and
      VHART = 'WER'.
    I'm getting an error
    Unable to interpret "CLIENT". Possible causes of error: Incorrect spelling or comma error.          
    if i change to my select query     to
    *select * from mara into table itab*
      where
      MANDT = SY-MANDT and
      VHART = 'WER'.
    I'm getting an error
    Without the addition "CLIENT SPECIFIED", you cannot specify the client     field "MANDT" in the WHERE condition.
    Let me know if iam wrong and we are at 4.6c
    Thanks

    Like I already said, even if you have added the mandt field in the secondary index, there is no need the use it in the select statement.
    Let me elaborate on my reply before. If you have created a UNIQUE index, which I don't think you have, then you should include CLIENT in the index. A unique index for a client-dependent table must contain the client field.
    Additional info:
    The accessing speed does not depend on whether or not an index is defined as a unique index. A unique index is simply a means of defining that certain field combinations of data records in a table are unique.
    Even if you have defined a secondary index, this does not automatically mean, that this index is used. This also depends on the database optimizer. The optimizer will determine which index is best and use it. So before transporting this index, you should make sure that the index is used. How to check this, have a look at the link:
    [check if index is used|http://help.sap.com/saphelp_nw70/helpdata/EN/cf/21eb3a446011d189700000e8322d00/content.htm]
    Edited by: Micky Oestreich on May 13, 2008 10:09 PM

  • Select query 'for all entries'

    Hello Friends,
           SELECT emp_id emp_name
           INTO corresponding fields of table itab_emp
           FROM employee
           for all entries in itab_dept
           WHERE emp_id = itab_dept_emp_id.
    In the above select query we are using 'for all entries' for the internal table itab_dept.What will happen if the join fails?Will we get any data in the output table?
    What is the prerequisites for using 'for all entries'.
    Please advice me on this.
    Regards
    Ashish.

    Hi
    In this case all the records available in employee table are extracted into internal table itab_emp.
    It is safe to check whether itab_dept is initial or not.
    If it is initial then stop the select query.
    Check the following program u will get an idea.
    Also try this program by removing comment to 'REFRESH IT_LFA1'.
    REPORT  ZBM_PG                                  .
    TABLES: LFA1, EKKO.
    DATA:
         IT_LFA1 TYPE TABLE OF LFA1 WITH NON-UNIQUE DEFAULT KEY INITIAL SIZE 10,
          IT_LFA1 TYPE TABLE OF LFA1 WITH HEADER LINE,
          IT_EKKO TYPE TABLE OF EKKO WITH HEADER LINE.
    SELECT * FROM LFA1 INTO TABLE IT_LFA1 WHERE LIFNR EQ '0000001000' OR LIFNR EQ '0000001500'.
    SELECT * FROM LFA1 INTO TABLE IT_LFA1 UP TO 1 ROWS.
    refresh it_lfa1.
    SELECT * FROM EKKO INTO TABLE IT_EKKO FOR ALL ENTRIES IN IT_LFA1 WHERE LIFNR = IT_LFA1-LIFNR.
    LOOP AT IT_EKKO.
      WRITE: / IT_EKKO-LIFNR, IT_EKKO-EBELN.
    ENDLOOP.
    Reward me if it is useful

  • How  to write select query for this

    Hi,
    I had a html form and in the for i had drop down box and it needs to select multiple values from the drop down box. When i select multiple values then i have to write the SQL select statement  query .
    When i try to write the select statement and trying to run i am getting error.
    select * from Table
    where emo_no = '1,2,3'
    this is how i write query please suggest me how  to write query for selecting multiple values from the drop down box.
    Thanks

    select * from Table
    where emo_no in ( 1,2,3)
    for integer values
    select * from Table
    where emo_no in ('1','2','3')
    for characters
    If we talk about large scale applications that may have millions of records, I would suggest this.
    declare @t table (v int)
    insert into t (v) values (1)
    insert into t (v) valves (2)
    insert into t (v) values (3)
    select *
    from table
         inner join @t t on table.emo_no = t.v
    Using "in" for a where clause is not so bad for filtering on a few values, but if you are filtering a lot of rows and a lot of values (emo_no) the performance degrades quickly for some reasons beyond the scope of this.
    This is just one solution, I'll through this out as well, instead of an in memory (@t) table, doing a disk based temp table (#t) and creating an index on the column "v".
    create table #t (v int)
    insert into #t (v) values (1)
    insert into #t (v) valves (2)
    insert into #t (v) values (3)
    create index ix_t on #t (v)
    select *
    from table
         inner join #t t on table.emo_no = t.v
    drop table #t
    Pardon any syntax errors and careful using a drop statement.
    Sometimes in memory tables work better than disk temp tables, it takes some testing and trial and error depending on your datasets to determine the best solution.
    Probably too much info  ;-)
    Byron Mann
    [email protected]
    [email protected]
    Software Architect
    hosting.com | hostmysite.com
    http://www.hostmysite.com/?utm_source=bb

Maybe you are looking for