Help with decode

Let's call the field "xfieldx". It’s currently a char data type that either gets inputted as null or “y” meaning yes. The problem comes when the query counts the number of rows that have a non-null value. The sql is below
sum(decode(xfieldx, null, 0, 'n', 0, 1)) as xfieldxCount
still returns a char value and later, when subject to a numeric condition “>” it fails. I need to make sure that this count is occurring correctly. Any wisdom?

Welcome to the forum!
Whenever you have a question, please post a little sample data (CREATE TABLE and INSERT statements), and the results you have from that data, so that the people who want to help you can re-create the problem and test their ideas.
If you have an existing query, post the complete query, point out where it's getting the wrong results, and explain how you'd get the right results in those places.
Always say which version of Oracle you're uisng.
Since this is your first post, I'll do some sample data for you:
CREATE TABLE     table_x
(       x_id     NUMBER (4)     PRIMARY KEY
,     xfieldx     VARCHAR2 (1)
INSERT INTO table_x (x_id, xfieldx) VALUES (0, NULL);
INSERT INTO table_x (x_id, xfieldx) VALUES (1, 'n');
INSERT INTO table_x (x_id, xfieldx) VALUES (2, 'y');
INSERT INTO table_x (x_id, xfieldx) VALUES (3, 'n');
894540 wrote:Let's call the field "xfieldx". It’s currently a char data type that either gets inputted as null or “y” meaning yes. The problem comes when the query counts the number of rows that have a non-null value. The sql is below
sum(decode(xfieldx, null, 0, 'n', 0, 1)) as xfieldxCount
still returns a char value and later, when subject to a numeric condition “>” it fails. I need to make sure that this count is occurring correctly. Any wisdom?That DECODE doesn't return a CHAR; it returs a NUMBER, either 0 or 1. (You can't use SUM on a CHAR expression.) And it's guaranteed either 0 or 1, never NULL. If you're interested in how many of the rows have a non-NULL value, just use COUNT.
The following query shows the difference:
SELECT  SUM ( DECODE ( xfieldx
                     , NULL     , 0
               , 'n'     , 0
                           , 1
         )               AS total_y
,       COUNT (xfieldx)          AS count_xfieldx
FROM     table_x
;Output:
`  TOTAL_Y COUNT_XFIELDX
         1             3This should work in any version of Oracle.
What results are you trying to get?
What are you trying to do with a > condition?

Similar Messages

  • Help with Decode function

    Hello!!
    Can anyone please help me with the decode statement
    Table 1 Table2 Table3
    Id Id Code
    Volume Code
    For each of the codes in Table3 I need to find the corresponding Volume. Can I use decode in the select statement to this,
    Eg Code Volume
    ABC 20
    XYZ 10 etc etc.
    Thankyou all in advance.

    Your table structure is a little unclear from your post. I am assuming that what you posted was:
    Table 1
    Id
    Table2
    Id
    Code
    Table3
    Volume
    Code You can use decode if there are only a few values for table3. For example,
    SELECT table2.code,
    DECODE(table2.code,'ABC',10,'XYZ',20,'UNKNOWN') volume
    FROM table2
    or even
    SELECT code,DECODE(code,null,'NONE',
                      (SELECT volume FROM table3 where code=table2.code)) volume
    FROM table2However, the first will break, or at least be incorrect, if anyone adds a new code/volume pair, and is tedious if you have more than a few values. The second will likely be pretty slow if there are a large number of records in table3. The best solution would be to use a simple join rather than decode. Something like:
    SELECT table1.id, table2.code, table3.volume
    FROM table1, table2, table3
    WHERE table1.id = table2.id and
          table2.code = table3.code

  • Help with Decode/CASE function

    Can anyone provide some help or insight how can this be done.
    Senario:
    I have two parameters in my report.
    Paramerer_A and Parameter_B
    If I enter a value (XYZ) in Parameter_A and value (XYZ) in Parameter_B, I want the report to display ERROR and do not run.

    Hi
    It is not possible to have a use defined message come up based on the values of parameters but we can stop the workbook from executing.
    First of all, you will will need to make sure that both parameters are optional and then create your condition such that it will not run if both are populated, like this:
    (Item1 = :Parameter_A OR Item2 = :Parameter_B)
    AND NOT
    :Parameter_A IS NOT NULL AND :Parameter_B IS NOT NULL
    You can also put in a check parameter that controls whether A or B should be used, with a prompt like this: Use Parameter A or Parameter B? Enter A or B
    :Check_Parameter = 'A' AND Item1 = :Parameter_A
    OR
    :Check_Parameter = 'B' AND Item2 = :Parameter_B
    Best wishes
    Michael

  • Need help with DECODE

    Hi,
    I need to write a DECODE function to which if I pass 'mystring' and if it has the value 'M' it should output 'M', if it has a value of 'F' it should output 'F' and if mystring is not same as string_coded then it should output string_coded.
    I know the below statement is incorrect.
    decode (mystring, 'M', 'M', 'F', 'F', (mystring <> string_coded), string_coded)
    Is there a way to correct this DECODE? Please suggest.
    Thanks.

    It is not clear of you want it to match the string 'string_coded' or if it is some column name, but with the example below you should be able to figure out what to adjust to make it work in your case.
    SQL> create table mytable
      2  as
      3  select 'M' mystring, 'X' string_coded from dual union all
      4  select 'F', 'X' from dual union all
      5  select 'X', 'X' from dual union all
      6  select 'Z', 'X' from dual
      7  /
    Tabel is aangemaakt.
    SQL> select mystring
      2       , string_coded
      3       , decode(mystring,'M','M','F','F',string_coded,'mystring = string_coded','mystring != string_coded') your_expression
      4    from mytable
      5  /
    M S YOUR_EXPRESSION
    M X M
    F X F
    X X mystring = string_coded
    Z X mystring != string_coded
    4 rijen zijn geselecteerd.Regards,
    Rob.

  • Help with decode or case statement

    I have the following insert statement
    insert into t_outcome (
    TRANSACTION_ID,
    charge_DATE,
    Charge_TIME,
    STATUS_CODE)
    values(cur_tem.transaction_id,
    cur_tem.charge_date,
    cur_tem.charge_time,
    cur_tem.STATUS_code)
    I require to incorporate the following rules into the population of charge_TIME
    if cur_tem.STATUS_code is 7 and cur_temp.charge_time is not null then populate charge_TIME with cur_temp.charge_time
    else if cur_tem.STATUS_code is 7 and cur_temp.charge_time is null then populate charge_TIME with -9
    else if cur_tem.STATUS_code is not 7 then populate charge_TIME with -7
    How do I add these rules into the insert statement ?
    Thanks
    Brendon

    decode(cur_tem.STATUS_code, 7, nvl(cur_tem.charge_time, -9), -7)
    I think that will work.
    Lee
    Message was edited by:
    Lee Forkenbrock

  • Help with Decode/Case

    Hello All,
    Can I use decode/case function within a decode function?
    {code}
    SELECT TO_CHAR (
              EDMS_STRAGG_WC (
                 DISTINCT DECODE (
                             eqs.attrib_code,
                             'PRODUCT_AUTHORIZATION',    'Authorization: '
                                                      || CASE eqs.qual_value
                                                            WHEN 'LIST'
                                                            THEN
                                                               (SELECT lookup_desc
                                                                  FROM edmsadm.edms_lookup
                                                                 WHERE     lookup_type =
                                                                              'PARTNER_AUTHORIZATION'
                                                                       AND lookup_code =
                                                                              eqls.list_value)
                                                            ELSE
                                                               (SELECT lookup_desc
                                                                  FROM edmsadm.edms_lookup
                                                                 WHERE     lookup_type =
                                                                              'PARTNER_AUTHORIZATION'
                                                                       AND lookup_code =
                                                                              eqs.qual_value)
                                                         END,
                             'PRODUCT_CERTIFICATION',    'Certification: '
                                                      || CASE eqs.qual_value
                                                            WHEN 'LIST'
                                                            THEN
                                                               eqls.list_value
                                                            ELSE
                                                               eqs.qual_value
                                                         END,
                             'PRODUCT_SPECIALIZATION',    'Specialization: '
                                                       || (SELECT lookup_desc
                                                             FROM edmsadm.edms_lookup
                                                            WHERE     lookup_type =
                                                                         'PARTNER_SPECIALIZATION'
                                                                  AND lookup_code =
                                                                         CASE eqs.qual_value
                                                                            WHEN 'LIST'
                                                                            THEN
                                                                               eqls.list_value
                                                                            ELSE
                                                                               eqs.qual_value
                                                                         END))))
              program_value
      FROM edms_qual_stg eqs, edms_qual_list_stg eqls
    WHERE     1 = 1
           AND eqs.qual_id = eqls.qual_id(+)
           AND eqs.req_id = 192647
           AND eqs.disc_line_id = 598631
           AND eqs.attrib_code IN
                  ('PRODUCT_CERTIFICATION',
                   'PRODUCT_AUTHORIZATION',
                   'PRODUCT_SPECIALIZATION');
    {code}
    Edms_qual_stg:
    AND_OR_CONDITION
    ATTRIBUTE_SOURCE
    ATTRIB_CODE
    CREATED_BY
    CREATED_DT
    DISC_LINE_ID
    END_DT
    EXCLUDE_INCLUDE
    GROUP_AND_OR_CONDITION
    GROUP_CODE
    MAX_VALUE
    MIN_VALUE
    MODIFIED_BY
    MODIFIED_DT
    QUAL_APPL_PRECEDENCE
    QUAL_ID
    QUAL_OPERATOR
    QUAL_TYPE
    QUAL_VALUE
    REQ_ID
    START_DT
    Edms_qual_list_stg:
    ATTRIBUTE_SOURCE
    ATTRIB_CODE
    CREATED_BY
    CREATED_DT
    END_DT
    INCLUDE_AFFILIATES
    INCLUDE_EXCLUDE
    LIST_VALUE
    MODIFIED_BY
    MODIFIED_DT
    PRIMARY_PARTY
    QUAL_ID
    QUAL_LIST_ID
    REFERENCE_ID
    START_DT
    Edms_lookup:
    CREATED_BY
    CREATED_DT
    DISPLAY_SEQ
    EDMS_LOOKUP_ID
    END_DATE
    LOOKUP_CODE
    LOOKUP_DESC
    LOOKUP_REFERENCE
    LOOKUP_TYPE
    MODIFIED_BY
    MODIFIED_DT
    START_DATE
    SELECT eqs.qual_id, eqs.disc_line_id, eqs.req_id, eqs.attrib_code, eqs.qual_value, eqls.list_value
      FROM edms_qual_stg eqs, edms_qual_list_stg eqls
    WHERE     1 = 1
           AND eqs.qual_id = eqls.qual_id(+)
           AND disc_line_id = 598631
           AND req_id = 192647
           AND eqs.attrib_code IN
                  ('PRODUCT_CERTIFICATION',
                   'PRODUCT_AUTHORIZATION',
                   'PRODUCT_SPECIALIZATION');
    7509575    598631    192647    PRODUCT_CERTIFICATION    LIST    GOLD
    7509575    598631    192647    PRODUCT_CERTIFICATION    LIST    SILVER
    7509576    598631    192647    PRODUCT_AUTHORIZATION    LIST    ATP - JOULEX PROVIDER ESCO
    7509576    598631    192647    PRODUCT_AUTHORIZATION    LIST    ATP - JOULEX PROVIDER IDENTIFY
    7509577    598631    192647    PRODUCT_SPECIALIZATION    LIST    ADVANCED SECURITY
    7509577    598631    192647    PRODUCT_SPECIALIZATION    LIST    EXPRESS FOUNDATION
    Required Output:
    Certification: GOLD, SILVER, Authorization: ATP - JOULEX PROVIDER ESCO, ATP - JOULEX PROVIDER IDENTIFY,  SPECIALIZATION: ADVANCED SECURITY, EXPRESS FOUNDATION.
    Thx
    Shank.

    Hi,
    Sure; a DECODE or CASE expression that returns a NUMBER can be used any place a NUMBER is expected, including within another DECODE or CASE expression.  A DECODE or CASE expression that returns a DATE can be used any place a DATE is expected, including within another DECODE or CASE expression.  A DECODE or CASE expression that returns a VARCHAR2 can be used almost any place a VARCHAR2 is expected.  (There a  couple of special situations where a string literal is absolutely required.)
    There are not many situations where you really need to do that, though.  It's usually simpler and more efficient to use a single CASE expression; nesting is rarely needed.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Simplify the problem as much as possible, so that it contains only enough to show the part you don't already know how to do.
    If you really need a user-defined function to show the problem, then include a CREATE FUNCTION statement, and explain what the function does.  Again, simplify: if the function isn't what you don't understand, post a problem that doesn't use the function.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

  • Need help with DECODE function

    Hello,
    I am trying to use default within the decode function and every time I get a missing expression. I have searched everywhere and cant figure out what I'm doing wrong. Thanks
    select decode (request_id,0,'No files found', DEFAULT)

    Hi,
    Welcome to the forum!
    When you use a default value, the last argument to DECODE is the actual value you want as a default.
    For example:
    SELECT       ename
    ,       deptno
    ,       DECODE ( deptno
                 , 30     , 'Sales'
                      , 'All others'     -- Default value
                  )                 AS dname
    FROM      scott.emp
    ORDER BY  ename
    ;Output:
    ENAME          DEPTNO DNAME
    ADAMS              20 All others
    ALLEN              30 Sales
    BLAKE              30 Sales
    CLARK              10 All others
    FORD               20 All others
    JAMES              30 Sales
    JONES              20 All others
    KING               10 All others
    MARTIN             30 Sales
    MILLER             10 All others
    SCOTT              20 All others
    SMITH              20 All others
    TURNER             30 Sales
    WARD               30 Sales 
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    If you can show the problem using commonly available tables (such as those in the scott schema) then you don't need to post any sample data; just the results and the explanation.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}

  • Error while replacing IF statements with DECODE function in procedure

    Hi All,
    I have created a procedure which has nested IF statements. Now I want to replace the IF statements with DECODE functions to improve performance.
    Procedure:
    IF (var_int_sev = '0')
    THEN
    var_sev := '2';
    ELSE
    SELECT sev
    INTO var_int_sev
    FROM errorconfig
    WHERE errorcode = var_errorcode;
    var_sev := var_int_sev;
    END IF;
    I converted the above IF statement into DECODE function as mentioned below:
    var_Sev := DECODE(var_int_sev,0,2,SELECT severity FROM errorconfig WHERE errorcode=var_ErrorCode)
    But it throws below error at the select statement used inside DECODE.
    Error(58,51): PLS-00103: Encountered the symbol "SELECT" when expecting one of the following: ( - + case mod new not null others <an identifier> <a double-quoted delimited-identifier> <a bind variable> avg count current exists max min prior sql stddev sum variance execute forall merge time timestamp interval date <a string literal with character set specification> <a number> <a single-quoted SQL string> pipe <an alternatively-quoted string literal with character set specification> <an alternativ
    Can someone help me in converting the IF to DECODE in the above case. Also how can we use a select statement inside decode.

    instead of trying to rewrite all your code and hoping that the performance will be better, it's a better option to investigate and find out which part of your application is slow
    read this:
    When your query takes too long ...

  • HELP WITH TRYING TO DO A FIXED ASSETS REPORT IN DISCOVERER

    Hi...
    I'll try and explain this simply as I can.
    I am trying to do a Disco report to basically list the asset numbers with the cost, the opening depreciation, the YTD depreciation, Accumulated depreciation and the remaining life of the asset.
    I can get most of the data from the FABG_DEPRECIATIONS table.
    The report will be run for a specific period say for example 05-2008. The problem I have is that for some of the assets there won't have been any depreciation for the year 2008 but I still need those assets to appear on the report showing the cost, opening depreciation etc.
    But because the report is being run for a specific period say 05-2008 in this example these assets that have no depreciation for the period are not being displayed on the report.
    As there isn't a field (I couldn't find one in any of the tables)that has the opening depreciation I have used a calculation for this which is Accumulated Depreciation - YTD depreciation. This is where my problem is. For those assets that have had no depreciation in the current year being reported on it should use the accumulated depreciation for say 12-2007 as the opening depreciation for the year 2008.
    So in the example of reporting for period 05-2008, it show the opening depreciation which would be the accumulated depreciation for 12-2007 and 0 (zero) for YTD depreciation.
    That is why I have attempted without success to use a union statement. The sql is below.
    I would be very grateful for some help with this please.
    select apps.fabg_depreciations.asset_id Asset_Number
    ,apps.fabg_depreciations.ytd_deprn YTD_Deprn
    ,apps.fabg_depreciations.deprn_amount Deprn_Amount
    ,apps.fabg_depreciations.accumulated_deprn Accumulated_Deprn
    ,apps.fabg_depreciations.reval_reserve Reval_reserve
    ,apps.fabg_acct_prds.period_name Period
    ,apps.fabg_asset_bks.original_cost Original_Cost
    ,apps.fabg_asset_bks.cost Cost
    ,apps.fabg_assets.asset_category_id Category_ID
    ,Null Period_Counter
    ,Null Opening_Dep
    ,apps.fabg_asset_cats.description Description
    from apps.fabg_depreciations
    , apps.fabg_acct_prds
    , apps.fabg_asset_bks
    , apps.fabg_assets
    , apps.fabg_asset_cats
    where apps.fabg_depreciations.book_type_code= 'ASSETS CCA'
    and apps.fabg_depreciations.period_counter =apps.fabg_acct_prds.period_counter
    and apps.fabg_asset_bks.asset_id=apps.fabg_depreciations.asset_id(+)
    and apps.fabg_assets.asset_id=apps.fabg_asset_bks.asset_id
    and apps.fabg_assets.asset_category_id=fabg_asset_cats.asset_category_id
    union
    select Null Asset_Number
    ,Null YTD_Deprn
    ,Null Deprn_Amount
    ,Null Accumulated_Deprn
    ,Null Reval_reserve
    ,Null Period
    ,Null Original_Cost
    ,Null Cost
    ,Null Category_ID
    ,Null Period_Counter
    ,decode(apps.fabg_depreciations.period_counter,24096,ytd_deprn,0) Opening_Dep
    ,Null Description
    from apps.fabg_depreciations
    , apps.fabg_acct_prds
    , apps.fabg_asset_bks
    , apps.fabg_assets
    , apps.fabg_asset_cats
    where apps.fabg_depreciations.book_type_code= 'ASSETS CCA'
    and apps.fabg_depreciations.period_counter=24096
    and apps.fabg_depreciations.period_counter =apps.fabg_acct_prds.period_counter
    and apps.fabg_asset_bks.asset_id=apps.fabg_depreciations.asset_id(+)
    and apps.fabg_assets.asset_id=apps.fabg_asset_bks.asset_id
    and apps.fabg_assets.asset_category_id=fabg_asset_cats.asset_category_id

    Hi...
    I've changed the custom code and used an embedded sql instead of a union but I still don't get the required info. I think it's down to the conditions. Can someone please help? Thanks.
    This is the revised code:
    select apps.fabg_depreciations.asset_id Asset_Number
    ,apps.fabg_depreciations.ytd_deprn YTD_Deprn
    ,apps.fabg_depreciations.deprn_amount Deprn_Amount
    ,apps.fabg_depreciations.accumulated_deprn Accumulated_Deprn
    ,apps.fabg_depreciations.reval_reserve Reval_reserve
    ,apps.fabg_acct_prds.period_name Period
    ,apps.fabg_asset_bks.original_cost Original_Cost
    ,apps.fabg_asset_bks.cost Cost
    ,apps.fabg_assets.asset_category_id Category_ID
    ,OD.accumulated_deprn Opening_Dep
    ,apps.fabg_asset_cats.description Description
    from apps.fabg_depreciations
    , apps.fabg_acct_prds
    , apps.fabg_asset_bks
    , apps.fabg_assets
    , apps.fabg_asset_cats
    ,(select fabg_depreciations.asset_id, fabg_depreciations.accumulated_deprn, fabg_depreciations.period_counter from apps.fabg_depreciations) OD
    where apps.fabg_depreciations.book_type_code= 'ASSETS CCA'
    and apps.fabg_asset_bks.asset_id=apps.fabg_assets.asset_id
    and apps.fabg_assets.asset_id = OD.asset_id
    and apps.fabg_assets.asset_id=apps.fabg_depreciations.asset_id
    --and apps.fabg_acct_prds.period_counter=apps.fabg_depreciations.period_counter(+)
    and apps.fabg_assets.asset_category_id=fabg_asset_cats.asset_category_id
    and apps.fabg_depreciations.period_counter=OD.period_counter(+)
    and OD.period_counter = 24096

  • Problem with DECODE block in WHERE clause

    Hi,
    I'm facing problem with DECODE statement. I just simulated my problem in the simple way as follows. If I execute this following query, I should get "hello", but I'm not getting anything (ZERO rows returned).
    SELECT 'hello' FROM DUAL
    WHERE 'sample1' in (DECODE(1, 1, '''sample1'', ''sample2'', ''sample3''',
    2, '''sample4'', ''sample5'', ''sample6'''
    I think some problem is there in my WHERE clause.
    But When I'm exeucting the following query as a seperate query, then I'm getting the value of DECODE block properly, but didn;t understnad why its not returning the same way when I'm putting the same DECODE statement in WHERE clause.
    SELECT DECODE(1, 1, '''sample1'', ''sample2'', ''sample3''',
    2, '''sample4'', ''sample5'', ''sample6'''
    FROM DUAL;
    Please help me to get out of this problem. Thank you so much in advance.
    Thanks,
    Ramji.

    The value returned by SELECT DECODE(1, 1, '''sample1'', ''sample2'', ''sample3''',2, '''sample4'', ''sample5'', ''sample6''') FROM DUAL;
    'sample1', 'sample2', 'sample3' is a single string. Consider it x.
    SELECT 'hello' FROM DUAL WHERE 'sample1' in ( DECODE(1, 1, '''sample1'', ''sample2'', ''sample3''',2, '''sample4'', ''sample5'', ''sample6'''));
    is like SELECT 'hello' FROM DUAL WHERE 'sample1' in ('x');
    or
    SELECT 'hello' FROM DUAL WHERE 'sample1' in ('''sample1'', ''sample2'', ''sample3''') and not
    SELECT 'hello' FROM DUAL WHERE 'sample1' in ('sample1', 'sample2', 'sample3');
    For this same reason SELECT 'hello' FROM DUAL WHERE 'sample1' in (select '''sample1'', ''sample2'', ''sample3''' from dual);
    also does'nt work.
    Please use INSTR to find whether 'sample1' exists in the string 'sample1', 'sample2', 'sample3'.

  • Problems with decoding an latin1-encoded url

    Hi,
    i have a problem with decoding german umlaut-characters from an URL.
    I'm using Tomcat 5.5 on a Linux server and one on a windows machine for development. Both webapps have the same configurations.
    A servlet decodes the URL-String, parses it and stores the parsed data into a mysql-DB.
    For decoding the query-string i'm using org.apache.commons.codec.net.URLCodec.URLCodec.decode .
    Here's the code:
    String unparsedParameters = request.getQueryString();
    URLCodec codec = new URLCodec("ISO-8859-1");
    result = codec.decode(unparsedParameters);Here an example for a query-string: http://servername:8080/servlet/Import?Etwas%20wurde%20am%2025.08.2010%2010%3A16%3A50%20*ge%E4ndert*
    On the windows machine the word "*ge&auml;ndert*" is decoded correctly. But on the linux server i get "*ge?ndert*". It makes no difference if i write the result into the database or just into a logfile.
    Can anyone help?
    Thanks in advance.
    Edited by: sol1640 on Aug 26, 2010 5:59 AM

    Problem resolved.
    Instead of using the decode-method as described in my fist message now i'm doing the folowing:
    fURLDecodigCharset = "ISO8859-1";
    byte[] bytes = originalParam.getBytes(fURLDecodigCharset);
    byte[] decodeUrl = URLCodec.decodeUrl(bytes);
    result = new String (decodeUrl, fURLDecodigCharset);because the method "decode" decodes the string by using the defaultcharset. And that was the problem.
    >
    The default charset is determined during virtual-machine startup and typically depends upon the locale and charset of the underlying operating system.
    >
    Thats why i've got different behaviours on different systems.
    Thanks

  • Need help with a query

    Hi,
    I need help with the following query. I want the balance (bal) with the latest exchange rate available.
    Sample table & data
    with
    FX_RATE as
    select 11 as id_date, 1 as id_curr, 47 as EXCH_rate from dual union
    select 12, 1, 48 from dual union
    select 13, 2, 54 from dual union
    select 14, 2, 55 from dual union
    select 15, 3, 56 from dual union
    select 15, 2, 49 from dual),
    TBL_NM as
    select 13 as p_date, 2 as p_curr, 200 as bal from dual union
    select 14, 2, 200 from dual union
    select 15, 2, 200 from dual union
    select 16, 2, 200 from dual union
    select 17, 2, 200 from dual union
    select 11, 5, 100 from dual
    select p_date, p_curr, bal * nvl(exch_rate,1) from TBL_NM T LEFT OUTER JOIN FX_RATE F1 on (id_curr = p_curr and F1.id_date = T.p_Date)In the above query for p_date 16 & 17 and p_curr 2 it returns just balance multiplied by exchange rate 1"default". But i want the balance to have data as per latest exchange rate which is of exchange rate 15.
    I tried this but returns error ORA-01799: a column may not be outer joined to a subquery ..
    with
    FX_RATE as
    select 11 as id_date, 1 as id_curr, 47 as EXCH_rate from dual union
    select 12, 1, 48 from dual union
    select 13, 2, 54 from dual union
    select 14, 2, 55 from dual union
    select 15, 3, 56 from dual union
    select 15, 2, 49 from dual),
    TBL_NM as
    select 13 as p_date, 2 as p_curr, 200 as bal from dual union
    select 14, 2, 200 from dual union
    select 15, 2, 200 from dual union
    select 16, 2, 200 from dual union
    select 17, 2, 200 from dual union
    select 11, 5, 100 from dual
    select p_date, p_curr, bal * nvl(exch_rate,1) from TBL_NM T LEFT OUTER JOIN FX_RATE F1
    on (id_curr = p_curr and F1.id_date = (select max(F2.id_date) from FX_RATE F2 where F2.id_curr = T.p_curr and F2.id_Date <=  T.p_date))Please advice on how i can achieve this ..

    The entire query wud be like this .. I've to incorporate in here
    CREATE MATERIALIZED VIEW MV_DUMMY
    BUILD IMMEDIATE
    REFRESH FORCE ON DEMAND
    AS
        SELECT T.ID_TSACTION_RELEASED                                                                                
        BAL.ID_CONTRACT_BALANCE                                                                                                                                                                                                                                                                           AS ID_CONTRACT_BALANCE,   
        T.N_REFERENCE_NUMBER                                                                                          
        T.INSTRUMENT_N_REFERENCE                                                                                      
        T.ITEM_NUMBER                                                                                                   
        T.EXTERNAL_SYSTEM_ID                                                                                            
        T.SEQUENCE_NUMBER                                                                                               
        T.ID_RELEASED_DATE                                                                                              
       ROUND(BAL.LC_AVAILABLE_BALANCE * NVL(FX1.EXCHANGE_RATE,1) / NVL(FX2.EXCHANGE_RATE,1) , 4)                           
        BAL.LIABILITY_BALANCE                                                                                              
        BAL.LIABILITY_BALANCE * NVL(FX3.EXCHANGE_RATE,1)                                                                   
        BAL.LIABILITY_CHANGE_USD                                                                                           
        BAL.MEMO_LIABILITY_BALANCE                                                                                         
        BAL.MEMO_LIABILITY_BALANCE * NVL(FX3.EXCHANGE_RATE,1)                                                              
        BAL.MEMO_LIABILITY_CHANGE_USD                                                                                      
        BAL.ORIGINAL_FACE_AMOUNT                                                                                           
        decode(T.TENOR_CODE,'Time','T','Sight','S','Split Sight Time','SST','Split Multiple Time','SMT',T.TENOR_CODE)
        CASE
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('ILC','IB','AIR','STG','NLC','NP')
          THEN T.ID_LIABILITY_CIF
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('ELC','EB','XLC','XP','EC','LN','SCF-AR')
          THEN T.Id_Beneficiary
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('TLC','IC','OA','SCF-AP')
          THEN T.ID_Applicant
        END PRIMARY_CUSTOMER_ID,
        CASE
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('ILC','IB','AIR','STG','NLC','NP')
          THEN plbcif.EXTERNAL_SYSTEM_ID
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('ELC','EB','XLC','XP','EC','LN','SCF-AR')
          THEN PBCIF.EXTERNAL_SYSTEM_ID
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('TLC','IC','OA','SCF-AP')
          THEN pappcif.EXTERNAL_SYSTEM_ID
        END PRIMARY_CUSTOMER_EXT_SYS_ID,
        CASE
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('ILC','IB','AIR','STG','NLC','NP')
          THEN plbcif.CIF_NAME
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('ELC','EB','XLC','XP','EC','LN','SCF-AR')
          THEN PBCIF.CIF_NAME
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('TLC','IC','OA','SCF-AP')
          THEN pappcif.CIF_NAME
        END PRIMARY_CUSTOMER_NAME,
        CASE
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('ILC','IB','AIR','STG','NLC','NP')
          THEN plbbac.BAC
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('ELC','EB','XLC','XP','EC','LN','SCF-AR')
          THEN pbbac.BAC
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('TLC','IC','OA','SCF-AP')
          THEN pappbac.BAC
        END PRIMARY_CUST_BAC_CODE,
        CASE
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('ILC','IB','AIR','STG','NLC','NP')
          THEN nvl(plbmg.MARKET,'NOT APPLICABLE')
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('ELC','EB','XLC','XP','EC','LN','SCF-AR')
          THEN nvl(pbmg.MARKET,'NOT APPLICABLE')
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('TLC','IC','OA','SCF-AP')
          THEN nvl(pappmg.MARKET,'NOT APPLICABLE')
        END PRIMARY_CUST_MARKET,
        CASE
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('ILC','IB','AIR','STG','NLC','NP')
          THEN nvl(plbmg.SUB_MARKET,'NOT APPLICABLE')
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('ELC','EB','XLC','XP','EC','LN','SCF-AR')
          THEN nvl(pbmg.SUB_MARKET,'NOT APPLICABLE')
          WHEN GTSPROD.PRODUCT_CATEGORY IN ('TLC','IC','OA','SCF-AP')
          THEN nvl(pappmg.SUB_MARKET,'NOT APPLICABLE')
        END PRIMARY_CUST_SUB_MARKET
      FROM F_TSACTION_RELEASED T
      LEFT OUTER JOIN D_BAC_CODE BAC
      ON (T.BAC_CODE_LIABILITY = BAC.BAC_CODE)
      LEFT OUTER JOIN REF_BAC_SORT_CODE REF_BAC
      ON (T.BAC_CODE_LIABILITY = REF_BAC.BAC)
      LEFT OUTER JOIN F_CONTRACT_BALANCE BAL
      ON (T.ID_TSACTION_RELEASED = BAL.ID_TSACTION_RELEASED)
      LEFT OUTER JOIN D_MARKET_SEGMENT MG
      ON (T.ID_MARKET_SEGMENT = MG.ID_MARKET_SEGMENT)
      LEFT OUTER JOIN D_DATE DT
      ON (DT.ID_DATE = T.ID_RELEASED_DATE)
      LEFT OUTER JOIN D_DATE DB
      ON (DB.ID_DATE = BAL.ID_RELEASED_DATE)
      LEFT OUTER JOIN D_PROCESSING_UNIT PU
      ON (PU.ID_PROCESSING_UNIT = T.ID_PROCESSING_UNIT)
      LEFT OUTER JOIN D_BIR_PRODUCT BIRPROD
      ON (BIRPROD.ID_BIR_PRODUCT=T.ID_BIR_PRODUCT)
      LEFT OUTER JOIN D_GTS_PRODUCT_TYPE GTSPROD
      ON (GTSPROD.ID_GTS_PRODUCT_TYPE= T.ID_GTS_PRODUCT_TYPE)
      LEFT OUTER JOIN D_GTS_TSACTION_TYPE GTST
      ON (GTST.ID_GTS_TSACTION_TYPE = T.ID_GTS_TSACTION_TYPE)
      LEFT OUTER JOIN D_CURRENCY CCYT
      ON (CCYT.ID_CURRENCY = T.ID_TSACTION_CURRENCY)
      LEFT OUTER JOIN d_cif lcif
      ON (lcif.id_cif = T.id_liability_cif)
      LEFT OUTER JOIN d_cif lbcif
      ON (lbcif.id_cif = bal.id_liability_cif)
      LEFT OUTER JOIN d_cif bcif
      ON (bcif.id_cif = T.id_BENEFICIARY)
      LEFT OUTER JOIN d_cif icif
      ON (icif.id_cif = T.id_ISSUING_BANK)
      LEFT OUTER JOIN d_cif acif
      ON (acif.id_cif = T.id_ADVISING_BANK)
      LEFT OUTER JOIN d_cif appcif
      ON (appcif.id_cif = T.id_applicant)
      LEFT OUTER JOIN d_state astate
      ON (astate.id_state = acif.id_state)
      LEFT OUTER JOIN d_state bstate
      ON (bstate.id_state = bcif.id_state)
      LEFT OUTER JOIN d_state lstate
      ON (lstate.id_state = lcif.id_state)
      LEFT OUTER JOIN d_state lbstate
      ON (lbstate.id_state = lbcif.id_state)
      LEFT OUTER JOIN d_state istate
      ON (istate.id_state = icif.id_state)
      LEFT OUTER JOIN d_state appstate
      ON (appstate.id_state = appcif.id_state)
      LEFT OUTER JOIN D_TSACTION_SOURCE TSrc
      ON (T.ID_TSACTION_SOURCE = TSrc.ID_TSACTION_SOURCE)
      LEFT OUTER JOIN D_COUNTRY LCTRY
      ON (LCTRY.ID_COUNTRY = lcif.ID_COUNTRY)
      LEFT OUTER JOIN D_COUNTRY LBCTRY
      ON (LBCTRY.ID_COUNTRY = lbcif.ID_COUNTRY)
      LEFT OUTER JOIN D_COUNTRY BCTRY
      ON (BCTRY.ID_COUNTRY = bcif.ID_COUNTRY)
      LEFT OUTER JOIN D_COUNTRY ICTRY
      ON (ICTRY.ID_COUNTRY = icif.ID_COUNTRY)
      LEFT OUTER JOIN D_COUNTRY ACTRY
      ON (ACTRY.ID_COUNTRY = acif.ID_COUNTRY)
      LEFT OUTER JOIN D_COUNTRY APPCTRY
      ON (APPCTRY.ID_COUNTRY = appcif.ID_COUNTRY)
      LEFT OUTER JOIN D_COUNTRY PCTRY
      ON (PCTRY.ID_COUNTRY = T.ID_PRESENTER_COUNTRY)
      LEFT OUTER JOIN D_LOCATION LOC
      ON (LOC.ID_LOCATION = T.ID_PROCESSING_LOCATION)
      LEFT OUTER JOIN D_CURRENCY BCCYT
      ON (BCCYT.ID_CURRENCY = BAL.ID_LIABILITY_CURRENCY)
      LEFT OUTER JOIN D_CURRENCY BALCYT
      ON (BALCYT.ID_CURRENCY = BAL.ID_BALANCE_CURRENCY)
      LEFT OUTER JOIN d_liability_type li
      ON (li.id_liability_type = BAL.id_liability_type)
      LEFT OUTER JOIN d_cif plbcif
      ON (plbcif.id_cif = T.id_liability_cif)
      LEFT OUTER JOIN REF_BAC_SORT_CODE plbbac
      ON (plbcif.bac_code=plbbac.bac)
      LEFT OUTER JOIN D_MARKET_SEGMENT plbmg
      ON (plbbac.SORT_CODE=plbmg.MARKET_SEGMENT)
      LEFT OUTER JOIN d_cif pbcif
      ON (pbcif.id_cif = T.id_BENEFICIARY)
      LEFT OUTER JOIN REF_BAC_SORT_CODE pbbac
      ON (pbcif.bac_code=pbbac.bac)
      LEFT OUTER JOIN D_MARKET_SEGMENT pbmg
      ON (pbbac.SORT_CODE=pbmg.MARKET_SEGMENT)
      LEFT OUTER JOIN d_cif pappcif
      ON (pappcif.id_cif = T.id_applicant)
      LEFT OUTER JOIN REF_BAC_SORT_CODE pappbac
      ON (pappcif.bac_code=pappbac.bac)
      LEFT OUTER JOIN D_MARKET_SEGMENT pappmg
      ON (pappbac.SORT_CODE=pappmg.MARKET_SEGMENT)
      LEFT OUTER JOIN D_CURRENCY LOCALCYT
      ON (LOCALCYT.alpha_code = PU.local_ccy)
      LEFT OUTER JOIN D_BRANCH Branch              
      ON (T.ID_BRANCH  = Branch.ID_BRANCH )
      LEFT OUTER JOIN F_USD_FX_RATE_HISTORY FX1
      ON (BAL.ID_BALANCE_CURRENCY = FX1.ID_CURRENCY and FX1.ID_DATE = (select max(FX11.ID_DATE) from F_USD_FX_RATE_HISTORY FX11 where BAL.ID_BALANCE_CURRENCY = FX11.ID_CURRENCY and FX11.ID_DATE <= BAL.id_released_date))
      LEFT OUTER JOIN F_USD_FX_RATE_HISTORY FX2
      ON (LOCALCYT.ID_CURRENCY = FX2.ID_CURRENCY and FX2.ID_DATE = (select max(FX22.ID_DATE) from F_USD_FX_RATE_HISTORY FX22 where LOCALCYT.ID_CURRENCY = FX22.ID_CURRENCY and FX22.ID_DATE <= BAL.id_released_date))
      LEFT OUTER JOIN F_USD_FX_RATE_HISTORY FX3
      ON (BAL.ID_LIABILITY_CURRENCY = FX3.ID_CURRENCY and FX3.ID_DATE = (select max(FX33.ID_DATE) from F_USD_FX_RATE_HISTORY FX33 where BAL.ID_LIABILITY_CURRENCY = FX33.ID_CURRENCY and FX33.ID_DATE <= BAL.id_released_date))Note the lines
    ROUND(BAL.MN_AVAILABLE_BALANCE * NVL(FX1.EXCHANGE_RATE,1) / NVL(FX2.EXCHANGE_RATE,1) , 4)                           
    BAL.LIABILITY_BALANCE * NVL(FX3.EXCHANGE_RATE,1)                                                                   
    BAL.MEMO_LIABILITY_BALANCE * NVL(FX3.EXCHANGE_RATE,1)                 
    And
    LEFT OUTER JOIN F_USD_FX_RATE_HISTORY FX1
      ON (BAL.ID_BALANCE_CURRENCY = FX1.ID_CURRENCY and FX1.ID_DATE = (select max(FX11.ID_DATE) from F_USD_FX_RATE_HISTORY FX11 where BAL.ID_BALANCE_CURRENCY = FX11.ID_CURRENCY and FX11.ID_DATE <= BAL.id_released_date))
      LEFT OUTER JOIN F_USD_FX_RATE_HISTORY FX2
      ON (LOCAMNYT.ID_CURRENCY = FX2.ID_CURRENCY and FX2.ID_DATE = (select max(FX22.ID_DATE) from F_USD_FX_RATE_HISTORY FX22 where LOCAMNYT.ID_CURRENCY = FX22.ID_CURRENCY and FX22.ID_DATE <= BAL.id_released_date))
      LEFT OUTER JOIN F_USD_FX_RATE_HISTORY FX3
      ON (BAL.ID_LIABILITY_CURRENCY = FX3.ID_CURRENCY and FX3.ID_DATE = (select max(FX33.ID_DATE) from F_USD_FX_RATE_HISTORY FX33 where BAL.ID_LIABILITY_CURRENCY = FX33.ID_CURRENCY and FX33.ID_DATE <= BAL.id_released_date))Thsi is where I need to incorporate the change

  • How to convert rows into columns with decode function

    Hi,
    How to convert rows into columns with the help of decode function in oracle.
    thanks and regards
    P Prakash

    say
    col1 col2
    1 10
    2 20
    3 30
    then use
    select col1,
    sum(decode(col2,10,10)) "new1"
    sum(decode(col2,20,20))"new2"
    sum(decode(col2,30,30))"new3"
    from table_name
    group by col1;
    we used sum u can use ny function if wont u have to give the column name i.e col2 name also
    so i think u got it nw
    regards

  • Problem with DECODE statement while migrating forms to 6i

    Hi,
    I'm migrating a form from 5 to 6i. When I compiled the form, I got this error witha decode statement.
    The error is
    Error 307 at line 15 column 7
    too many declarations of "DECODE" match this call
    The trigger has this code:
    IF :PRUN_RECS_INSERTED = 'Y' THEN
          RETURN ;
       END IF ;
       INSERT INTO GJBPRUN
        ( GJBPRUN_JOB,
          GJBPRUN_ONE_UP_NO,
          GJBPRUN_NUMBER,
          GJBPRUN_ACTIVITY_DATE,
          GJBPRUN_VALUE )
       SELECT :KEYBLCK_JOB,
              :ONE_UP_NO,
               GJBPDFT_NUMBER,
               SYSDATE,
          DECODE(GJBPDFT_VALUE, 'SYSDATE',
                          DECODE(GJBPDEF_LENGTH,'11',TO_CHAR(SYSDATE,'DD-MON-YYYY'), SYSDATE),
                          GJBPDFT_VALUE)
       FROM   GJBPDFT G, GJBPDEFEdited by: Charan on Mar 16, 2011 9:15 AM

    Hi Charan
    i think it's all about using both CHARACTER and DATE values at the same time in a DECODE statment u should either use char or date datatype.
    DECODE compares expr to each search value one by one. If expr is equal to a search, then Oracle Database returns the corresponding result. If no match is found, then Oracle returns default. If default is omitted, then Oracle returns null.
    e.g.
    If expr and search are character data, then Oracle compares them using nonpadded comparison semantics.
    expr, search, and result can be any of the datatypes CHAR, VARCHAR2, NCHAR, or NVARCHAR2.
    The string returned is of VARCHAR2 datatype and is in the same character set as the first result parameter.
    for more pls have a look here
    Hope this helps,
    Regards,
    Abdetu...

  • Problem with decode!!!

    Hi guys,
    I have a problem with "decode"!
    How can I tell the decode expression
    that if a rowset don't exists --> then doing something.
    I've tried that with "NULL" but that don't works.
    here my code:
    I wanted that if tx.text doesn't exists then
    it returns fs.anlageschwerpunkt_lang, and otherwise
    it returns tx.Text.
    select
    decode(tx.Text,NULL,fs.anlageschwerpunkt_lang,tx.Text) Anlageschwerpunkt_1 from
    POI.Fondsstamm fs,
    Texte tx,
    Texttypstamm txy
    where
    tx.match='amfcomm'
    and tx.match=rtrim(fs.match)
    and tx.TEXTTYPID=txy.TEXTTYPID
    and txy.BEREICHSID=14
    and txy.texttyp='Marketingstrategie'
    I hope somebody of you can help me
    thanxx
    Schoeib

    I read Schoeibs question differently; no ROWS are being returned. In that case you cannot expect DECODE or any other function to do anything. Assuming that rows always exist in fs and txy and are only missing in tx, then you need an outer join. Note that the join of tx.match = rtrim(fs.match) has been altered to avoid outer joining to more than one table. As mentioned before, although the decode is OK, NVL could be used instead.
    select
    decode(tx.Text,NULL,fs.anlageschwerpunkt_lang,tx.Text) Anlageschwerpunkt_1 from
    POI.Fondsstamm fs,
    Texte tx,
    Texttypstamm txy
    where
    tx.match(+)='amfcomm'
    and rtrim(fs.match) = 'amfcomm'
    and tx.TEXTTYPID(+)=txy.TEXTTYPID
    and txy.BEREICHSID=14
    and txy.texttyp='Marketingstrategie'

Maybe you are looking for

  • Can't open adobe reader in safari on my Macbook

    When I click on a link to open a pdf document while on the internet, a new tab opens in safari and begins to load but freezes up. The only way I've been able to view the document is to actually right click and download it onto my computer. I've tried

  • Unable to sync TV shows

    I recently downloaded the Colbert report off of Itunes, and I keep trying to get it to sync to my Ipod, but it never shows up. The only article I could find on this topic was for the 3G nano, and I have the 4G nano. Please help!

  • H.264 export without audio creates files that are not recognized in Quicktime or VLC

    Dear all, I need to generate h.264 files with video only. (short clips for use with a "clickable" catalog on an iPad) Used the "H.264" category and chose a preset. Unchecked "Audio" so I only get the video exported. The resulting .m4v file is not pla

  • Where are custom styles saved on my computer?

    Hi, I need to create a cd with all the customizations I have made to a template (object, table, cell, paragraph, and character styles).  I can't seem to find them, however. In CS4 I found them here: Computer > Local Disk (C:) > Program Files > Adobe

  • Differences in field TEXT_MCHA_CHARG

    Hi expert, i have a problem when i want to make a query for batch characteristic, i only use MCHA table and i want to use MATNR and CHARG field, i also add a simple code to get the batch characteristic, the problem is when i try to generate the infos