Retrieve SQL using an optional condition

Hi,
Ive just created two tables that sql I describe below:
CREATE TABLE "TEST"
    "NAME" VARCHAR2(255 BYTE),
    "LEVEL1" VARCHAR2(255 BYTE),
    "LEVEL2" VARCHAR2(255 BYTE),
    "LEVEL3" VARCHAR2(255 BYTE),
    "CODE"   NUMBER
CREATE TABLE "TEST2"
    "LEVEL1" VARCHAR2(255 BYTE),
    "LEVEL2" VARCHAR2(255 BYTE),
    "LEVEL3" VARCHAR2(255 BYTE)
     ) and then Im going to populate them
INSERT INTO TEST VALUES('0.31 ACQUISITION','7722',     'foc',     NULL     ,1);
INSERT INTO TEST VALUES('0.32 ACQUISITION','7733',     'foco',     NULL     ,2);
INSERT INTO TEST VALUES('0.33 ACQUISITION','7700',     'house',     'class'     ,3);
INSERT INTO TEST2 VALUES('7733',null,null);
INSERT INTO TEST2 VALUES(null,'foco','teka');
INSERT INTO TEST2 VALUES('7733','foco',null);
INSERT INTO TEST2 VALUES('7700','house',null);
INSERT INTO TEST2 VALUES('7700',null,null);I would like to know if its there any way to obtain the desired code joining these tables,
this result consist in the followings conditions:
the levels can be macth or not, but if in any level match, the desired
record will be that one what has value in the higher level
therefore the desired test table record is
'0.32 ACQUISITION','7733',     'foco',     NULL     ,2Is there any way to obtain it using SQL.
Thanks in advanced...

Maybe (NOT TESTED!)
select name,level1,level2,level3,code,
  from (select t.name,t.level1,t.level2,t.level3,t.code,
               rank() over (order by '3'||case when t.level3 = t2.level3 then '1' else '0' end ||
                                     '2'||case when t.level2 = t2.level2 then '1' else '0' end ||
                                     '1'||case when t.level1 = t2.level1 then '1' else '0' end
                            desc
                           ) rnk
          from test t,
               test2 t2
         where t.level1 = t2.level1
            or t.level2 = t2.level2
            or t.level3 = t2.level3
where rnk = 1Regards
Etbin
Edited by: Etbin on 26.11.2011 6:44
Rereading the post seems I missed it :( you need just the one with the value (no need to be a the matching one)
select name,level1,level2,level3,code,
  from (select t.name,t.level1,t.level2,t.level3,t.code,
               rank() over (order by nvl2(t.level3,'1','0') ||
                                     nvl2(t.level2,'1','0') ||
                                     nvl2(t.level1,'1','0')
                            desc
                           ) rnk
          from test t,
               test2 t2
         where t.level1 = t2.level1
            or t.level2 = t2.level2
            or t.level3 = t2.level3
where rnk = 1

Similar Messages

  • Using Select option in Native SQL

    Hi,
    Can any one tell me, how to use select option value in native SQL.
    ie.,
    I want to use select option in where condition. Need to select all the records from table(non-SAP) where date in given range.
    Please suggest.
    Thanks,
    Amal

    Hi
    No!
    U need to find a way to convert a range of select-option to a range for Native SQL, probably it should be better doesn't use a select-option for the date but two parameters: one for date from and one for date to.
    Max

  • Setting and retrieving session using pl/sql

    How to set and retrieve session using pl/sql?Can anyone help me?

    mrs wrote:
    create or replace
    function get_login_details(in_user in VARCHAR2,in_pwd in VARCHAR2,in_cname in VARCHAR2)
    ..snipped..The code should look as follows:
    create or replace function AuthenticateUser( userName varchar2, userPassw varchar2, userGroup varchar2 )
    return integer is
      i integer;
    begin
      --// purpose of the SQL is simply to check if such a row exist -
    --// no data from the row needs to be fetched
      select 1 into i from acl_users_gv
      where user_name = userName
      and password = userPassw
      and entity_group_name = userGroup;
      --// if the SQL succeeded, then the row exists and matches
      --// the authentication details
      return( 0 );
    exception when NO_DATA_FOUND then
      --// SQL failed to find a row - authentication details do
      --// not exist
      return( 1 );
    end;No need to fetch data unnecessarily. No need too check the fetched data when the column values are already checked via the SQL filter condition (predicate).
    No need to return a flag variable as a freely formatted text string containing Successful Login and login failed. That is not a robust design to use a string variable like that. Use boolean for true/false. Or use integer values 0/1.
    This is my function get_login_details.And I need to get this 'o_mesg' in other java file also.Standard PL/SQL call from Java. The SQL string to execute contains an anonymous PL/SQL and needs to use bind variables. E.g.
    begin
      :result := AuthenticateUse( :userName, :userPassw, :userGroup );
    end;
    Can you suggest the right way, how I can get this variable in other pages?That depends on whether there is database session state. If there is, authentication can be done once only via a trusted context, that specifies whether the session is authenticated.
    If this is done from an app server that uses a db session pool and stateless db sessions, the state needs to be kept in the app server.
    Do you understand what stateful versus stateless db sessions are, and what the differences are?

  • Using multiple 'and' conditions in a SQL query

    Is it possible to reduce the SQL required to query using multiple 'and' conditions, e.g. I have a query like the following:
    select stat.personal_id, appt.username, appt.password, apps.rgn_apt_id, apps.apy_apn_id
    from apy_ast_application_status stat, rgn_usr_user appt, rgn_aps_applications apps
    where stat.apy_apn_id = apps.rgn_apt_id
    and apps.rgn_apt_id = appt.rgn_apt_id
    and stat.application_completed is null
    and stat.application_started_date > '01-MAY-11'
    and stat.amount_paid is null
    and stat.personal_details = 'C'
    and stat.further_details = 'C'
    and stat.education = 'C'
    and stat.employment = 'C'
    and stat.personal_statement = 'C'
    and stat.choices = 'C'
    and stat.reference = 'C'
    and stat.student_finance = 'C'
    Is there a way, to reduce all the multiple 'and' queries, to be read from say one line? If you know what I mean.......

    Ah, Ok this looks nice, thanks very much. It doesn't quite run as is because the stat.amount_paid query value is 'is null', while the others are 'C'. I tried amending the relevant line to various versions of the following:-
    in (select 'is null' 'C','C','C','C','C','C','C','C' from dual)
    which doesn't work.
    I can get the following to work so I am assuming that the it is not possible to use different query values within the brackets of the 'in (select....' statement?
    select stat.personal_id, appt.username, appt.password, apps.rgn_apt_id, apps.apy_apn_id
    from apy_ast_application_status stat, rgn_usr_user appt, rgn_aps_applications apps
    where stat.apy_apn_id = apps.rgn_apt_id
    and apps.rgn_apt_id = appt.rgn_apt_id
    and stat.application_completed is null
    and stat.application_started_date > '01-MAY-11'
    and stat.amount_paid is null
    and (stat.personal_details, stat.further_details, stat.education,
    stat.employment, stat.personal_statement, stat.choices, stat.reference, stat.student_finance)
    in (select 'C','C','C','C','C','C','C','C' from dual)
    Thanks for everybodys help - the suggested alternatives seem so much more elegant

  • Require Code which export SQL Query resuluts to excel using checkbox option

    Hi All,
    I need a sample code which can export the SQL Query results directly to an excel file using checkbox option. for example
    if I select checkbox1 and press a save button, then on backend SQL Query will execute and save the results in a excel file and so on.
    Thanks in advance..
    Regards,
    Chetan

    Thanks for the Code.
    Actually I need a code which is based on combo base values and when I click on Button, the SQL Query will execute using SQL Connection string and the results from that query will save into a excel file. Below is the screenshot of the form. Hope this will
    clear the requirements.
    Hello,
    To be honest, this forum is not for coding for anybody.
    You could refer to the suggestions shared above, and if you get any issue when using that code, you could share the code and error with us, we will focus on your code to help you.
    You could separate them into multiple steps, like the following.
    1. Getting the value of any control, like the textbox and combobox or even checkbox.
    2. Execute method inside button click event handler.
    3. Using ado.net to execuate sql query.
    4. Saving data to Excel.
    Then you could have a try step by step, if you get any issue, then post it in another thread with the code and error message.
    Regards,
    Carl
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Retrieving SQL queries used in BO reports using BO Java SDKs

    Hi,
    Is it possible to retrieve SQL queries generated by Canned Reports? I have 200+ reports saved in my local system and i need to retrieve SQL queries from them, this is required for documentation purpose. Please let me know if it is possible thru BO java SDKs.

    This is the code I am using to retrieve the SQL values.
    IEnterpriseSession boEnterpriseSession = null;
                  boEnterpriseSession = CrystalEnterprise.getSessionMgr().logon( boUser, boPassword, boCmsName, boAuthType);
                   // Get the Report Application Factory service from Crystal Enterprise
                   IReportAppFactory rptAppFactory = (IReportAppFactory)boEnterpriseSession.getService("", "RASReportService");
                   // Get the InfoStore service from Crystal Enterprise
                   IInfoStore boInfoStore = (IInfoStore)boEnterpriseSession.getService("", "InfoStore");
                   // Retrieve the report by name from Crystal Enterprise
                   IInfoObjects boInfoObjects = boInfoStore.query("Select SI_ID From CI_INFOOBJECTS Where SI_NAME = '" + reportName + "'");
                   // Open the report into a Report Document object
                   ReportClientDocument rcd = rptAppFactory.openDocument((IInfoObject)boInfoObjects.get(0), 0, Locale.ENGLISH);
                   System.out.println("SQL query \n \n");
                   System.out.println(rcd.getRowsetController().getSQLStatement(null, ""));
    I am a newbie and I dont understand where the error lies.. Please help me out.
    regards,
    nitin
    When run the code gives  the following errors
    com.crystaldecisions.sdk.occa.managedreports.ras.internal.ManagedRASException: Cannot open report document. --- 0x80004005
    Unspecified error
    cause:com.crystaldecisions.sdk.occa.report.lib.ReportSDKServerException: 0x80004005
    Unspecified error---- Error code:-2147467259 Error code name:failed
    detail: 0x80004005
    Unspecified error
         at com.crystaldecisions.sdk.occa.managedreports.ras.internal.RASReportAppFactory.a(Unknown Source)
         at com.crystaldecisions.sdk.occa.managedreports.ras.internal.RASReportAppFactory.a(Unknown Source)
         at com.crystaldecisions.sdk.occa.managedreports.ras.internal.RASReportAppFactory.openDocument(Unknown Source)
         at com.crystaldecisions.sdk.occa.managedreports.ras.internal.RASReportAppFactory.openDocument(Unknown Source)
         at com.hcl.BO.retrieveSql.RetrieveSQL.main(RetrieveSQL.java:44)
    Caused by: com.crystaldecisions.sdk.occa.report.lib.ReportSDKServerException: 0x80004005
    Unspecified error---- Error code:-2147467259 Error code name:failed
         at com.crystaldecisions.sdk.occa.report.lib.ReportSDKServerException.throwReportSDKServerException(Unknown Source)
         at com.crystaldecisions.proxy.remoteagent.s.a(Unknown Source)
         at com.crystaldecisions.sdk.occa.report.application.ReportClientDocument.if(Unknown Source)
         at com.crystaldecisions.sdk.occa.report.application.ReportClientDocument.if(Unknown Source)
         at com.crystaldecisions.sdk.occa.report.application.ReportClientDocument.a(Unknown Source)
         at com.crystaldecisions.sdk.occa.report.application.ClientDocument.open(Unknown Source)
         ... 4 more
    I am a newbie and

  • Hiding optional conditions that user doesn't need to use.

    Using Discoverer 9.0.4
    In Disco Admin in one folder I have three conditions.
    Two of them are optional.
    A: Two items are both null. (Optional)
    B: Two items don't have specific values X and Y (Optional)
    C: A OR B (Mandatory)
    Is there a way to hide the two optional conditions from user?
    And BTW the feature that Conditions containing analytic functions can't be made mandatory ain't good...

    I just tried this as I've never thought you couldn't hide them. However in Disco Plus 10g, it's the same story - you can't hide them using something like properties - visible to user.
    So I am surprised about this.
    It sounds like your users could edit the actual report (ie: not using Viewer), so one answer would be to go back a further level and have the conditions in a database view, but that seems to be a bit of a hack for just hiding conditions.
    Sorry, but I too can't see a way to hide them from users picking them.
    Russ

  • Using extend option with PL/SQL table of tables

    Hi,
    I have a PL/SQL table of tables sructure on which I want to use extend option available with PL/SQL tables.
    But I am not able to do so. Could anyone help?
    Below is sample code given.
    Type RA_TABLE is table of CALL_DETAIL_EXCEPTION.IC_CIRCT_GR_CD%TYPE;
    TYPE tab_of_RA_TABLE IS TABLE OF RA_TABLE;
    for idx in 1..cnt_interval Loop
    query1:='select Trunk_info from dbl.vw_cgi v where not exists (select 1 from dbl.varun f
    where f.ic_circt_gr_cd= v.TRUNK_INFO and f.call_gmt_dnect_dt_time between
    to_date('''||stime||''',''yyyymmddhh24miss'') and to_date('''||etime||''',''yyyymmddhh24miss''))';
    execute immediate query1 bulk collect into Outer_table(idx);
    ra_cnt_1:= Outer_table(idx).count;
    diff:= max_cnt-RA_CNT_1;
    dbms_output.put_line('idx: '||idx);
    dbms_output.put_line('diff: '||diff);
    if diff>=1 then
    Outer_table(idx).extend( Diff);
    end if;
    end loop;
    The extend doesnt work.
    Please help!!

    Hi,
    I have a PL/SQL table of tables sructure on which I want to use extend option available with PL/SQL tables.
    But I am not able to do so. Could anyone help?
    Below is sample code given.
    Type RA_TABLE is table of CALL_DETAIL_EXCEPTION.IC_CIRCT_GR_CD%TYPE;
    TYPE tab_of_RA_TABLE IS TABLE OF RA_TABLE;
    for idx in 1..cnt_interval Loop
    query1:='select Trunk_info from dbl.vw_cgi v where not exists (select 1 from dbl.varun f
    where f.ic_circt_gr_cd= v.TRUNK_INFO and f.call_gmt_dnect_dt_time between
    to_date('''||stime||''',''yyyymmddhh24miss'') and to_date('''||etime||''',''yyyymmddhh24miss''))';
    execute immediate query1 bulk collect into Outer_table(idx);
    ra_cnt_1:= Outer_table(idx).count;
    diff:= max_cnt-RA_CNT_1;
    dbms_output.put_line('idx: '||idx);
    dbms_output.put_line('diff: '||diff);
    if diff>=1 then
    Outer_table(idx).extend( Diff);
    end if;
    end loop;
    The extend doesnt work.
    Please help!!

  • Sql query not using parallel option

    I am working in oracle 11.2.0.2.0 .
    I am trying to execute one query using parallel options but in explain plan it is not using that PX option ...
    UPDATE /*+PARALLEL (emp,4) */
    cust_sku_allocation_data emp
    set emp.mean=
    (select sum(dep.stock_to_sales)/count(distinct dep.destination_facility)
    FROM cust_sku_allocation dep
    WHERE dep.stock_to_sales_ratio NOT IN (0,9999)
    AND dep.sku_id = emp.sku_id);
    Any idea where to check..

    Sorry I meant:
    You cannot parallelize UPDATE or DELETE operations on a nonpartitioned table, or when the update only affects 1 partition in a partitioned one.

  • Unable to see SQL Server 2008 option in Designer

    Hi Guys,
    We are using SQL Server 2008 and BO XI R3. While creating a new universe connection we can see (under microsoft) SQL Server 2005, but not the SQL Server 2008.
    How can we see the SQL Server 2008 option. Do we need to change some settings in BO or SQL Server?
    Thanks & Regards
    Manish Tiwari

    What version of XI 3.x are you on? Microsoft SQL Server Analysis Services 2008 is only supported with XI 3.1 and higher. The supported platforms document for XI 3.1 is [here|http://www.sdn.sap.com/irj/boc/index?rid=/library/uuid/60cdb229-d874-2b10-18ac-ed2f46873753&overridelayout=true].

  • Failed to Retrieve SQL

    Hi,
    Using STANDARD REPORT CREATION WIZARD, I connected to UNIVERSES Data Sources and RUN a querry in BUSINESS OBJECTS QUERY PANEL,i am getting ERROR Message "Failed to Retrieve SQL".What would be the causes?
    Thanks,
    Sandeep

    Hi,
    try this link, [Click HEre|http://www.forumtopics.com/busobj/viewtopic.php?t=40450&sid=14981ec8c36d528ba129eedb58fe2e18]
    Regards,
    Clint

  • How to see the SQL used in an existing Rule file?

    Hi,
    Is there a way to see the SQL used in the rule file defn of any existing rule file which retrieves data from a RDMS?
    Appreciate your thoughts.
    Thanks.

    Sure.
    In EAS open up the load rule in question, then select the menu item "File"-"Open SQL".
    Robert

  • Getting [Microsoft][ODBC SQL Server Driver] Optional feature not implemented

    I am using below mentioned code to insert values in MSAccess 2000 which having table structure as mentioned below:-
    Field Name Data Type
    TodaysDate Date/Time
    Cart ID Number
    Client Name Text
    Campaign Text
    Team & Segment Text
    Duration Number
    Tape ID Text
    Start Date Date/Time
    End Date Date/Time
    Station Text
    Code:-
    private boolean enterDataIntoMSAccessDatabaseusingPreparedStatement()
       try {
      ps = connection.prepareStatement("INSERT INTO Cart ID Details VALUES (?,?,?,?,?,?,?,?,?)");
      System.out.println("After Query");
       catch (SQLException se) {
      generateErrorMessage("Error in Prepared Statement \n " + se.getMessage() );
       return false;
       catch (Exception e)
      generateErrorMessage("Unexpected Error Occured \n " + e.getMessage());
       String todaysDate = cartIDApplicationAddCartIDDatejTextField.getText().trim();
       String cartID = cartIDApplicationAddCartIDCartIDjTextField.getText().trim();
       String clientName = cartIDApplicationAddCartIDClientNamejTextField.getText().trim();
       String campaign = cartIDApplicationAddCartIDCampaignjTextField.getText().trim();
       String teamSegment = cartIDApplicationAddCartIDTeamAndSegmentjTextField.getText().trim();
       String duration = cartIDApplicationAddCartIDDurationjTextField.getText().trim();
       String tapeID = cartIDApplicationAddCartIDTapeIDjTextField.getText().trim();
       String startDate = cartIDApplicationAddCartIDStartDatejTextField.getText().trim();
       String endDate = cartIDApplicationAddCartIDEndDatejTextField.getText().trim();
       String station = cartIDApplicationAddCartIDDELjCheckBox.getText().substring(0, 3);
      System.out.println(station);
       try {
      System.out.println("Before ps.setString()");
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
      System.out.println("Simple Date Format");
       /*ps.setString(1, todaysDate);
      ps.setString(2, cartID );
      ps.setString(3, clientName);
      ps.setString(4, teamSegment);
      ps.setString(5, duration);
      ps.setString(6, tapeID);
      ps.setString(7, startDate);
      ps.setString(8, endDate);*/
      System.out.println("1");
      ps.setDate(1, new java.sql.Date(simpleDateFormat.parse(todaysDate).getTime()));
      ps.setString(2, cartID);
      ps.setString(3, clientName);
      ps.setString(4, campaign);
      ps.setString(5, teamSegment);
      ps.setString(6, duration);
      ps.setString(7, tapeID);
      ps.setDate(8, new java.sql.Date(simpleDateFormat.parse(startDate).getTime()));
      ps.setDate(9, new java.sql.Date(simpleDateFormat.parse(endDate).getTime()));
      ps.setString(10, station);
      System.out.println("After ps.setString()");
      ps.executeUpdate();
       catch (SQLException se) {
      generateErrorMessage("Error while inserting data in database \n " + se.getMessage());
       return false;
       catch (Exception e)
      generateErrorMessage("Unexpected Error Occured \n" + e.getMessage() );
       return true;
    I got below error after implementing the above code:-
    [Microsoft][ODBC SQL Server Driver]Optional feature not implemented.
    Kindly help me for the same.

    >>  [Microsoft][ODBC SQL Server Driver]  
    I don't see anything Oracle in your question.   It looks like you're getting an error using Microsoft's SQL Server driver, did you mean to post this to a forum on  Microsoft's site perhaps?

  • [ODBC SQL Server Driver]Optional feature not implemented

    Hi,
    Has anyone faced such error @ analysis,
    Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 43113] Message returned from OBIS. [nQSError: 43119] Query Failed: [nQSError: 16001] ODBC error state: S1C00 code: 0 message: [Microsoft][ODBC SQL Server Driver]Optional feature not implemented. [nQSError: 16012] ODBC error occurred while binding the parameters of a SQL statement. (HY000)
    we are having some issue on DBfeature check box issue.
    Thanks
    Deva

    Hi,
    Yes. after that only i am getting error. if i enabled Query DBMS then report is working with out error (we don't want to use query dbms option that's i just query dbms off option by Reset to default) then its thoewing error.
    Thanks
    Deva

  • Sending E-mail from BI Publisher without using Bursting Option

    Hi All,
    “While clicking on Send Button and selecting E-mail as Delivery option in BI Publisher for a particular Report, we want that To, CC, BCC  and the Body part should get populated  with the Email id’s and Static text(for Body )  from database . We know that it can be done if we use the option of Bursting but we don’t want to use bursting . Is there any way (SQL Query or API’s) where we can achieve this option of populating the email id’s and body dynamically
    while clicking on the Send button on the BI Publisher Screen. Please Suggest.”

    Hi,
    Looking at the above link it seems thatit is for XML publisher in EBS rather than for a standalone BI publisher. Please let me know how to acheive the steps mentioned in the blog while working on standalone version BI publisher.
    Thanks
    Sunil

Maybe you are looking for

  • Missing photos after upgrade from iPhoto 08 to 11

    I just updated iPhoto from '08 (v7.1.5) to '11 (v9.5) and I opened a copy of my old '08 library.  Unfortunately iPhoto '11 does not show any events or photos from this library.  If I view the contents of the library in Finder I see that it still cont

  • Problems compiling 2.6.24.3

    I'm maintaining kernel26tp_plus in the AUR and currently working on a PKGBUILD for a 2.6.24 kernel. I have had a working build but needed to apply some patches afterwards. Now compiling doesn't work anymore. The issue seems to not be related to the p

  • What's wrong? I can't determine the cause of it.

    Hi all, I've gotten myself a macbook online (2 ghz with the stock 512 megs of ram). I bought myself 2 pieces of patriot 1 gb (it's of correct specifications) and installed them at a computer shop a week ago. Upon booting up, everything runs perfectly

  • Question on reinstallion of CS5

    I recently formatted the hard drive and re-installed Photoshop CS5; I purchased CS6 upgrade, and now CS5 has a panel from Adobe telling me I have 17 days left of this trial.  I have used chat with Adobe and told to enter serial number on trial panel

  • FM for splitting the date

    Hi Everyone, I need an FM to split the Date into days , month and year... can anyone help me out. Points will be rewarded. Regards, Syed