SQL to sum a column while avoiding repeating values

Dear All
i have this table called Loans_installments that contains the client's loan installments.
a sample of data:
branch currency client_id loan_no inst_mat_date inst_seq original_inst_amt int_amt
110 2 222 100 1/1/2013 1 0 50
110 2 222 100 1/2/2013 2 0 52
110 2 222 100 1/3/2013 3 0 54
110 2 222 100 1/4/2013 4 500 90
110 2 222 100 1/5/2013 5 0 50
110 2 222 100 1/6/2013 6 0 51
110 2 222 100 1/7/2013 7 0 50
110 2 222 100 1/8/2013 8 600 105
110 2 222 100 1/9/2013 9 0 50
110 2 222 100 1/10/2013 10 0 54
110 2 222 100 1/11/2013 11 0 50
110 2 222 100 1/12/2013 12 700 120
now what i want to sum the field int_amt based on original_inst_amt value (0 or has a value) and put the result on the int_amt that has an orig_inst_amt value <>0.
the result should be like this:
branch currency client_id loan_no inst_mat_date inst_seq original_inst_amt int_amt
110 2 222 100 1/1/2013 1 0 0
110 2 222 100 1/2/2013 2 0 0
110 2 222 100 1/3/2013 3 0 0
110 2 222 100 1/4/2013 4 500 246
110 2 222 100 1/5/2013 5 0 0
110 2 222 100 1/6/2013 6 0 0
110 2 222 100 1/7/2013 7 0 0
110 2 222 100 1/8/2013 8 600 256
110 2 222 100 1/9/2013 9 0 0
110 2 222 100 1/10/2013 10 0 0
110 2 222 100 1/11/2013 11 0 0
110 2 222 100 1/12/2013 12 700 274
any help plz.

Using model clause
SQL> with t
  2  as
  3  (
  4  select 110 branch, 2 currency, 222 client_id, 100 loan_no, to_date('1/1/2013','mm/dd/yyyy') inst_mat_date, 1  inst_seq, 0   original_inst_amt, 50 int_amt from dual
  5  union all
  6  select 110 branch, 2 currency, 222 client_id, 100 loan_no, to_date('1/2/2013','mm/dd/yyyy') inst_mat_date, 2  inst_seq, 0   original_inst_amt, 52 int_amt from dual
  7  union all
  8  select 110 branch, 2 currency, 222 client_id, 100 loan_no, to_date('1/3/2013','mm/dd/yyyy') inst_mat_date, 3  inst_seq, 0   original_inst_amt, 54 int_amt from dual
  9  union all
10  select 110 branch, 2 currency, 222 client_id, 100 loan_no, to_date('1/4/2013','mm/dd/yyyy') inst_mat_date, 4  inst_seq, 500 original_inst_amt, 90 int_amt from dual
11  union all
12  select 110 branch, 2 currency, 222 client_id, 100 loan_no, to_date('1/5/2013','mm/dd/yyyy') inst_mat_date, 5  inst_seq, 0   original_inst_amt, 50 int_amt from dual
13  union all
14  select 110 branch, 2 currency, 222 client_id, 100 loan_no, to_date('1/6/2013','mm/dd/yyyy') inst_mat_date, 6  inst_seq, 0   original_inst_amt, 51 int_amt from dual
15  union all
16  select 110 branch, 2 currency, 222 client_id, 100 loan_no, to_date('1/7/2013','mm/dd/yyyy') inst_mat_date, 7  inst_seq, 0   original_inst_amt, 50 int_amt from dual
17  union all
18  select 110 branch, 2 currency, 222 client_id, 100 loan_no, to_date('1/8/2013','mm/dd/yyyy') inst_mat_date, 8  inst_seq, 600 original_inst_amt, 105 int_amt from dual
19  union all
20  select 110 branch, 2 currency, 222 client_id, 100 loan_no, to_date('1/9/2013','mm/dd/yyyy') inst_mat_date, 9  inst_seq, 0   original_inst_amt, 50 int_amt from dual
21  union all
22  select 110 branch, 2 currency, 222 client_id, 100 loan_no, to_date('1/10/201','mm/dd/yyyy') inst_mat_date, 10 inst_seq, 0   original_inst_amt, 54 int_amt from dual
23  union all
24  select 110 branch, 2 currency, 222 client_id, 100 loan_no, to_date('1/11/201','mm/dd/yyyy') inst_mat_date, 11 inst_seq, 0   original_inst_amt, 50 int_amt from dual
25  union all
26  select 110 branch, 2 currency, 222 client_id, 100 loan_no, to_date('1/12/201','mm/dd/yyyy') inst_mat_date, 12 inst_seq, 700 original_inst_amt, 120 int_amt from dual
27  )
28  select branch
29       , currency
30       , client_id
31       , loan_no
32       , inst_mat_date
33       , inst_seq
34       , original_inst_amt
35       , decode(original_inst_amt, 0, 0, sum(int_amt) over(partition by cnt)) int_amt
36    from (
37            select branch
38                 , currency
39                 , client_id
40                 , loan_no
41                 , inst_mat_date
42                 , inst_seq
43                 , original_inst_amt
44                 , int_amt
45                 , cnt
46              from t
47             model
48             dimension by
49             (
50                inst_seq
51             )
52             measures
53             (
54                branch, currency, client_id, loan_no, inst_mat_date, original_inst_amt, int_amt, 1 cnt
55             )
56             rules
57             (
58                 cnt[any] = case
59                                   when original_inst_amt[cv()-1] > 0 then
60                                      cnt[cv()-1] + 1
61                                   else
62                                      nvl(cnt[cv()-1], cnt[cv()])
63                               end
64             )
65         )
66  /
    BRANCH   CURRENCY  CLIENT_ID    LOAN_NO INST_MAT_   INST_SEQ ORIGINAL_INST_AMT    INT_AMT
       110          2        222        100 01-JAN-13          1                 0          0
       110          2        222        100 02-JAN-13          2                 0          0
       110          2        222        100 03-JAN-13          3                 0          0
       110          2        222        100 04-JAN-13          4               500        246
       110          2        222        100 05-JAN-13          5                 0          0
       110          2        222        100 06-JAN-13          6                 0          0
       110          2        222        100 08-JAN-13          8               600        256
       110          2        222        100 07-JAN-13          7                 0          0
       110          2        222        100 09-JAN-13          9                 0          0
       110          2        222        100 11-JAN-01         11                 0          0
       110          2        222        100 10-JAN-01         10                 0          0
       110          2        222        100 12-JAN-01         12               700        274
12 rows selected.
SQL>

Similar Messages

  • Avoid repeating values in details section

    Hi,
    I have a report with a lot of formulas - depending on certain values in a certain Oracle database table values are summed up.
    The fields are therefore placed in the report footer.
    As I now have to insert a grouping I need to move the fields into the details section. However, I don't want to display each value there but only the sum - I would like to avoid repeating values in the details section.
    A formula looks like this:
    stringvar A1;
    if {OUR_TABLE_FIELD} = 1 then A1 := {OTHER_TABLE.OTHER_FIELD}
    Else A1:=A1;
    A1;
    Thanks!

    Add a suitable group and then display data in this group footer, suppress detail section. It will effectively show the last detail line and thus eliminate duplicates from view. However, data is still there so if you want to use summaries you will need to use Running totals to ensure duplicates are not counted/summed
    Ian

  • ReportViewer Total column InScope causes repeating values in Innermost group

    I have a table which has only one cell. Inside that cell it has a rectangle (design purposes only) and inside that rectangle there is my main table. Primary table is used for paging, so it has one group. Innermost table is for data view. The problem is,
    that if i have ANY expression containing InScope("Matrix1_Group1") in Total column in the innermost table, i get repeating values in that table. Numbers are ok, but rows titles are repeating.
    +-----------+------------+---------+----------+
    | Country | Producer | [Month] | Total |
    +-----------+------------+---------+----------+
    | [Country] | [Producer] | SUM(Q) | <<Expr>> |
    +-----------+------------+---------+----------+
    | Total | SUM(Q) | <<Expr>> |
    +------------------------+---------+----------+
    This is the sample of my innermost table (tried my best. not allowed to insert images). I i use InScope("Matrix1_Group1") in ANY (value, Color, BackgroundColor) expression in Total column, Producer column values are repeating (the first value
    is repeated in all rows).
    Sample expression from cell in Total column is: =IIF(InScope("Matrix1_Group1"), Fields!Producer.Value/SUM(Fields!Producer.Value, "Matrix1_Group1"), "100%")
    More information abou this problem.
    It only occurs if two conditions are met: repor has paging and InScope returns true. I have to make pages in report and each page contains table and some other blocks. I use List component to create a list and use grouping. Then i put a table inside. If
    table is outside any element, everything works perfectly, but if it is inside list, table, matrix or something similar allowing to create pages, the problem occurs. 
    Also, if InScope allways returns FALSE and none condition is met - there is no problem. But if any InScope return TRUE - i have repeating values in innermost group.

    Please have a look at the following links:
    http://download-west.oracle.com/docs/html/B10602_01/orbr_summary.htm#1010648
    http://download-west.oracle.com/docs/html/B10602_01/toc.htm

  • Update one column while getting the value in another column

    Is it possible to in one single SQL statement update two columns in a table while at the same time obtaining the value of another column, on the same row, in the same table, and independently (that is, the update of the columns has nothing to do with the data that I want from another column)*?* Of course, I can do this in two operations, one being a "select" and the other one being an "update", but since I am in the same table and even on the same row, is it really necessary to make TWO database calls? That's why I want to combine the the two SQL-statements, for reasons of presumed effiency.

    jsun wrote:
    Is it possible to in one single SQL statement update two columns in a table while at the same time obtaining the value of another column, on the same row, in the same table, and independently (that is, the update of the columns has nothing to do with the data that I want from another column)*?* Of course, I can do this in two operations, one being a "select" and the other one being an "update", but since I am in the same table and even on the same row, is it really necessary to make TWO database calls? That's why I want to combine the the two SQL-statements, for reasons of presumed effiency.Two statements != two database calls.
    At least not in terms of SQL.
    JDBC requires a 'statement' but in SQL (depending on the data source) that can include multiple statements. An obvious example of this is a stored proc but there are other ways as well.

  • Sql sript for Insert of data with repeating values

    It has been a long long time since I had to do write and use any SQL scripts, please forgive the question. I used to use a script to insert values into a table as part of my job. I have forgotten what the script I used was and since lost all my Oracle note books and other DBA material.
    I did a search and went through 30 pages of results, I didn't see what I'm looking for.
    The data is from one large file that is appended at the end and sometimes updated somewhere in the middle of the set which is considered new data. I am not concern with getting the data out of the file, I got that handled but the insert into the table - transactions - is where I'm lost.
    I used to use a script to load the data, about 6 years ago, and it would load the file, exclude the data that was already in the table and insert the new data and the data with the changes.
    The data columns are date, time, reference, transaction code, location, debit amount, fee amount, balance.
    The date repeats but the time and reference values are unique.
    Any help with this script is appreciated.

    Hi,
    welcome to the forum..!
    You can use Oracle's merge statement to (update + insert) data into a table ... if the data exists update it with the new values and if it does not, then insert it.
    Here's a link to get you started...
    http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_9016.htm
    Since, the data is from a file, you could create an external table on the file and directly do a select from the file.
    MERGE INTO bonuses D
       USING (SELECT employee_id, salary, department_id FROM employees
       WHERE department_id = 80) S
       ON (D.employee_id = S.employee_id)
       WHEN MATCHED THEN UPDATE SET D.bonus = D.bonus + S.salary*.01
         DELETE WHERE (S.salary > 8000)
       WHEN NOT MATCHED THEN INSERT (D.employee_id, D.bonus)
         VALUES (S.employee_id, S.salary*0.1)
         WHERE (S.salary <= 8000);in the above example, the
    SELECT employee_id, salary, department_id FROM employeesis the source data. instead of loading the file into a temporary table and then merge into the target table , you could read from <<<external_table_on_your_file>> and then do a merge into the target table.
    http://www.oracle.com/technology/products/oracle9i/daily/sept19.html
    If you encounter any problems, please post the full description of your error.
    Thanks,
    Rajesh.
    Please mark this/any other answer as helpful or answered if it is so. If not, provide additional details/feedback.
    Always try to provide create table and insert statements to help the forum members help you better.

  • Excluding a column causes non-repeating values in 2nd table view

    I have an analysis (11.1.1.5) that has these columns: Month, Country, State, City, Sales, Country Sales, Share of Country. Country Sales is a level-based measure that returns sales at the Country level. Country, State, and City are a hierarchy as you might expect.
    When I display the initial Table view for this analysis, the Country Sales column shows a value on every row.
    When I create a 2nd Table view and exclude the City column from that view, the Country Sales column now only shows a value for the first State within each Country. In other words, each value of Country Sales is shown only once, and is NOT repeated on each subsequent row for that country.
    Any ideas if this is a bug, or if it was intentionally designed this way for some reason? Is there a way to force the values to repeat? (Green Bar / Repeat doesn't do it.)

    Thank you for the responses, guys. Still no luck.
    I moved the Country Sales column as Deepak suggested, both in the criteria and in the view. That didn't change the results. I also started fresh with a new analysis, and placed the columns in the suggested positions from the start. Still no change.
    New information: I tried excluding State and leaving City in the table view. Got the same goofy results - Country Sales did not repeat.
    More new information: I added a Brand Revenue measure to the Sample Sales subject area. Brand Revenue is defined as '1 - Revenue' at the Product Brand level. Created a similar view, and it worked fine.
    I'll investigate what the differences might be between Sample Sales and my repository. Hard to imagine what it might be. My repository is very simple and straightforward.

  • ALV Avoid repeated values for a field

    I have developed an ALV report. In that 1 field say Company Code along with its details are getting displayed. I dont want the same Company Code to get printed repeatedly. It is sorted by Company Code.
    Company code should get printed only once when it gets changed ..
    eg:
    Comp1 sdf ghj
    Comp1 bvc asd
    Comp2 qqq ert
    Comp2 www rrr
    Comp2 tyu iop
    I want a report like this:
    Comp1 sdf ghj
          bvc asd
    Comp2 qqq ert
          www rrr
          tyu iop
    Can anyone help me ? Its urgent ..
    Thanking you in advance,
    Shankar

    Hi,
    Check the sample code.
    REPORT  Z_TEST_HERSEQ_LIST_DISPLAY.
    type-pools : slis.
    *--Data declaration
    data : itab_ekko like standard table of ekko with header line,
           itab_ekpo like standard table of ekpo with header line.
    data : it_fldcat_ekko type SLIS_T_FIELDCAT_ALV,
           it_fldcat_ekpo type slis_t_fieldcat_alv.
    data : v_repid type sy-repid.
    DATA : IS_KEYINFO TYPE SLIS_KEYINFO_ALV.
    data : header type slis_tabname,
           item   type slis_tabname,
           layout type slis_layout_alv.
    **--Table declaration
    tables : ekko.
    **--selection screen
    select-options: s_ebeln for ekko-ebeln.
    initialization.
      v_repid = sy-repid.
    **--Start of selection
    start-of-selection.
    select * from ekko
      into table itab_ekko
      where ebeln in s_ebeln.
    if not itab_ekko[] is initial.
      select * from ekpo
        into table itab_ekpo
        for all entries in itab_ekko
        where ebeln = itab_ekko-ebeln.
    endif.
    perform fldcat.
    *perform set_layout.
    perform herseq_list.
    *&      Form  fldcat
    *       text
    * Form to populating fieldcat
    form fldcat .
    CALL FUNCTION 'REUSE_ALV_FIELDCATALOG_MERGE'
    EXPORTING
       I_PROGRAM_NAME               = v_repid
       I_INTERNAL_TABNAME           = 'ITAB_EKKO'
       I_STRUCTURE_NAME             = 'EKKO'
    *   I_CLIENT_NEVER_DISPLAY       = 'X'
    *   I_INCLNAME                   =
    *   I_BYPASSING_BUFFER           =
    *   I_BUFFER_ACTIVE              =
      CHANGING
        ct_fieldcat                  = it_fldcat_ekko
    * EXCEPTIONS
    *   INCONSISTENT_INTERFACE       = 1
    *   PROGRAM_ERROR                = 2
    *   OTHERS                       = 3
    IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    CALL FUNCTION 'REUSE_ALV_FIELDCATALOG_MERGE'
    EXPORTING
       I_PROGRAM_NAME               = v_repid
       I_INTERNAL_TABNAME           = 'ITAB_EKPO'
       I_STRUCTURE_NAME             = 'EKPO'
    *   I_CLIENT_NEVER_DISPLAY       = 'X'
    *   I_INCLNAME                   =
    *   I_BYPASSING_BUFFER           =
    *   I_BUFFER_ACTIVE              =
      CHANGING
        ct_fieldcat                  = it_fldcat_ekKo
    * EXCEPTIONS
    *   INCONSISTENT_INTERFACE       = 1
    *   PROGRAM_ERROR                = 2
    *   OTHERS                       = 3
    IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    endform.                    " fldcat
    *&      Form  herseq_list
    *       text
    *her list
    form herseq_list .
    IS_KEYINFO-HEADER01 ='EBELN' .
    IS_KEYINFO-ITEM01 = 'EBELN'.
    header = 'ITAB_EKKO'.
    item = 'ITAB_EKPO'.
    CALL FUNCTION 'REUSE_ALV_HIERSEQ_LIST_DISPLAY'
      EXPORTING
    *   I_INTERFACE_CHECK              = ' '
    *   I_CALLBACK_PROGRAM             =
    *   I_CALLBACK_PF_STATUS_SET       = ' '
    *   I_CALLBACK_USER_COMMAND        = ' '
    *   IS_LAYOUT                      = layout
       IT_FIELDCAT                    =  IT_FLDCAT_EKKO
    *   IT_EXCLUDING                   =
    *   IT_SPECIAL_GROUPS              =
    *   IT_SORT                        =
    *   IT_FILTER                      =
    *   IS_SEL_HIDE                    =
    *   I_SCREEN_START_COLUMN          = 0
    *   I_SCREEN_START_LINE            = 0
    *   I_SCREEN_END_COLUMN            = 0
    *   I_SCREEN_END_LINE              = 0
    *   I_DEFAULT                      = 'X'
    *   I_SAVE                         = ' '
    *   IS_VARIANT                     =
    *   IT_EVENTS                      =
    *   IT_EVENT_EXIT                  =
        i_tabname_header               = HEADER
        i_tabname_item                 = ITEM
    *   I_STRUCTURE_NAME_HEADER        =
    *   I_STRUCTURE_NAME_ITEM          =
        is_keyinfo                     = is_keyinfo
    *   IS_PRINT                       =
    *   IS_REPREP_ID                   =
    *   I_BYPASSING_BUFFER             =
    *   I_BUFFER_ACTIVE                =
    *   IR_SALV_HIERSEQ_ADAPTER        =
    *   IT_EXCEPT_QINFO                =
    *   I_SUPPRESS_EMPTY_DATA          = ABAP_FALSE
    * IMPORTING
    *   E_EXIT_CAUSED_BY_CALLER        =
    *   ES_EXIT_CAUSED_BY_USER         =
      tables
        t_outtab_header                =   itab_ekko
        t_outtab_item                  =   itab_ekpo
    EXCEPTIONS
       PROGRAM_ERROR                  = 1
       OTHERS                         = 2
    IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    endform.                    " herseq_list
    Regards
    vijay

  • How to avoid repeat values in two tables

    hi there,
    I have two tables. SUPPLIERS and MANUFACTURERS. SUPPLIERS has more than one MANUFACTURERS. In normalization rule, a field must have single piece of data. SUPPLIERS_ID is repeating for every MANUFACTURERS. pls help me out to normalize these two tables.
    Thank u...

    Ideally you need to have 2 master tables SUPPLIER & MANUFACTURER.
    Then you need an intermediate transaction table to hold the relationship bet SUPPLIED & MANUFACTURER. Here the records will be repeated.

  • How do i avoid repeted values in a report.

    how do i avoid repeated values in a report. for example..
    DEPTID EMPLID NAME
    10          101     aaaaaa
    10          166     bbbbb
    10          176     ggggg
    10          145     iiiiiiiii
    20          234     zzzzzz
    20          285     ddddd
    20          266     uuuuu
    but I want see the report as below.
    DEPTID EMPLID NAME
    10          101     aaaaaa
              166     bbbbb
              176     ggggg
              145     iiiiiiiii
    20          234     zzzzzz
              285     ddddd
              266     uuuuu
    Thanks in advance

    I apologize for jumping in here, but I had this problem in the past and Marc Sewtz had indicated there is a fix slated for APEX 3.0 timeframe.
    Here's a couple of links if you are interested:
    Re: Break Formatting Region and effect on other regions
    report error: ORA-01403: no data found when SUM columns
    The second link contains the workaround I used.
    Again, sorry for interjecting, but I thought it might be a bit helpful,
    Mark

  • In JDBC Sender Adapter , the server is Microsoft SQL .I need to pass current date as the input column while Executing stored procedure, which will get me 10 Output Columns. Kindly suggest me the SQL Query String

    In JDBC Sender Adapter , the server is Microsoft SQL .I need to pass current date as the input column while Executing stored procedure, which will get me 10 Output Columns. Kindly suggest me the SQL Query String , for executing the Stored Procedure with Current date as the input .

    Hi Srinath,
    The below blog might be useful
    http://scn.sap.com/community/pi-and-soa-middleware/blog/2013/03/06/executing-stored-procedure-from-sender-adapter-in-sap-pi-71
    PI/XI: Sender JDBC adapter for Oracle stored procedures in 5 days
    regards,
    Harish

  • How to sum a column in SQL server??

    How do I sum a column called 'expenditureamount' in a sql table 'expenditureform', such that I get the total expenditure amount displayed in a text box??

    You can sum it with the SQL SUM function, of course, but what that has to do with how your program display that sum, I don't know. IOW, how you display is not anything related to JDBC, and how you SUM it is not anything related to JDBC. The first one is SQL (check on an SQL forum or Google for it) and the second depends on how you want to display it, and there are more appropriate forums than the JDBC one, for that.

  • How to avoid repeatation of code

    hi
    My code is as mentioned below.
    if l_location ='USA'
    insert into location
    select f1,f2,f3,f4
    from usa_tab
    else if l_location = 'FRANCE'
    insert into location
    select f1,f2,f3,f4
    from france_tab f , x1_tab x
    where f.id = x.id
    else if l_location = 'UK'
    insert into location
    select f1,f2,f3,f4
    from uk_tab u,y1_tab y
    where u.id = y.id
    end if;
    how to avoid the repeatation of code here?

    954992 wrote:
    it is an existing application. The tables can not be changed.
    actually here the insert and select statements are fixed , only the from and where conditions are getting changed.
    howf to avoid repeatation of the fixed code?Oracle supports features called "+partition views+" and "+instead of triggers+". This can be used to glue tables (same structure) together and select and insert against these tables via a view.
    Basic example:
    // tables that constitutes the partition view - a check constraint on
    // country is used to specify which cities are in which table, similar
    // to a partition key
    SQL> create table location_france(
      2          country varchar2(10) default 'FRANCE' not null,
      3          city    varchar2(20) not null,
      4          --
      5          constraint chk_france check (country in 'FRANCE'),
      6          constraint pk_location_france primary key
      7          ( country, city )
      8  ) organization index;
    Table created.
    SQL> create table location_uk(
      2          country varchar2(10) default 'UK' not null,
      3          city    varchar2(20) not null,
      4          --
      5          constraint chk_uk check (country in 'UK'),
      6          constraint pk_location_uk primary key
      7          ( country, city )
      8  ) organization index;
    Table created.
    SQL> create table location_spain(
      2          country varchar2(10) default 'SPAIN' not null,
      3          city    varchar2(20) not null,
      4          --
      5          constraint chk_spain check (country in 'SPAIN'),
      6          constraint pk_location_spain primary key
      7          ( country, city )
      8  ) organization index;
    Table created.A partition view is a view that uses union all to glue these tables together:
    SQL> create or replace view locations as
      2          select * from location_france
      3          union all
      4          select * from location_uk
      5          union all
      6          select * from location_spain
      7  /
    View created.To support inserts against the partition view, an instead-of trigger is used:
    SQL> create or replace trigger insert_location
      2          instead of insert on locations
      3  begin
      4          case :new.country
      5                  when 'FRANCE' then
      6                          insert into location_france values( :new.country, :new.city );
      7                  when 'UK' then
      8                          insert into location_uk values( :new.country, :new.city );
      9                  when 'SPAIN' then
    10                          insert into location_spain values( :new.country, :new.city );
    11          else
    12                  raise_application_error(
    13                          -20000,
    14                          'Country name ['||:new.country||'] is not supported.'
    15                  );
    16          end case;
    17  end;
    18  /
    Trigger created.Rows can now be inserted into the view and the trigger will ensure that the rows wind up in the correct table.
    SQL> insert into locations values( 'FRANCE', 'PARIS' );
    1 row created.
    SQL> insert into locations values( 'UK', 'LONDON' );
    1 row created.
    SQL> insert into locations values( 'SPAIN', 'BARCELONA' );
    1 row created.As with a partition table, a select on a partition view that uses the "partition column" (in this case, the COUNTRY column), the CBO can prune the non-relevant tables from the view and only select against the relevant table. In the following example, the UK is used as country filter and the CBO shows that only table LOCATION_UK is used.
    SQL> set autotrace on explain
    SQL> select * from locations where country = 'UK';
    COUNTRY    CITY
    UK         LONDON
    Execution Plan
    Plan hash value: 1608298493
    | Id  | Operation           | Name               | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT    |                    |     1 |    19 |     1   (0)| 00:00:01 |
    |   1 |  VIEW               | LOCATIONS          |     1 |    19 |     1   (0)| 00:00:01 |
    |   2 |   UNION-ALL         |                    |       |       |            |          |
    |*  3 |    FILTER           |                    |       |       |            |          |
    |*  4 |     INDEX RANGE SCAN| PK_LOCATION_FRANCE |     1 |    19 |     2   (0)| 00:00:01 |
    |*  5 |    INDEX RANGE SCAN | PK_LOCATION_UK     |     1 |    19 |     2   (0)| 00:00:01 |
    |*  6 |    FILTER           |                    |       |       |            |          |
    |*  7 |     INDEX RANGE SCAN| PK_LOCATION_SPAIN  |     1 |    19 |     2   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       3 - filter(NULL IS NOT NULL)
       4 - access("COUNTRY"='UK')
       5 - access("COUNTRY"='UK')
       6 - filter(NULL IS NOT NULL)
       7 - access("COUNTRY"='UK')
    Note
       - dynamic sampling used for this statement (level=2)
    SQL>Oracle provides a number of methods to address flawed data models and problematic client code. However, despite this flexibility on Oracle's part, you should still consider fixing the flawed design and code - as that flaws invariable mean reducing flexibility, performance and scalability.

  • Error importing text file into SQL Server when last column is null

    Hello all. Happy holidays!
    I'm trying to import a text file into a SQL Server table, and I get the error below when it gets to a row (row 264) that has null in the last column. I'm guessing the null jumbles up the delimiters somehow. The nulls are not errors, and I need to import
    them into the table with the rest of the rows. Any idea how I can do that?
    Thanks!
    [Flat File Source [1]] Error: Data conversion failed. The data conversion for column "XYZ" returned status value 2 and status text "The value could not be converted because of a potential loss of data.".
    [Flat File Source [1]] Error: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  The "output column "XYZ" (178)" failed because error code 0xC0209084 occurred, and the error row disposition on "output column "XYZ"
    (178)" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure.
    [Flat File Source [1]] Error: An error occurred while processing file "ABC.txt" on data row 264.
    [SSIS.Pipeline] Error: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED.  The PrimeOutput method on component "Flat File Source" (1) returned error code 0xC0202092.  The component returned a failure code when the pipeline engine called PrimeOutput().
    The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing.  There may be error messages posted before this with more information about the failure.
    WeeLass

    Hi WeeLass,
    The error that” Data conversion failed. The data conversion for column "XYZ" returned status value 2 and status text "The value could not be converted because of a potential loss of data.".” is generally error message, and the error indicates
    that there is data type mismatch issue between the input columns and the output columns.
    Based on your description, the issue is that you trying to convert a column contains empty value from string to integer data type for the output column "XYZ" in Flat File Source [1]. Please note that we cannot type an empty value as integer data
    type column value, so the error occurs.
    To fix this issue, just as you did, we should convert the data type for the output column "XYZ" in Flat File Source [1] back to DT_WSTR or DT_STR, then use a derived column task to replace the current column (UBPKE542). But the expression should
    be like below:
    LEN(TRIM(UBPKE542)) > 0 ? (DT_I8)UBPKE542 : NULL(DT_I8)
    In this way, the data type of the column in SQL table would be int, and the empty value would be replaced with NULL.
    If there are any other questions, please feel free to ask.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • Turning sql  string (with dynamic columns) into a pipelined function

    Hi guys,
    I was working on an apex report the other day, and wrote the sql below (for those who don't know apex well, in an apex report you can define the columns at runtime.) When I was finished, I said to myself: "It would be great to have a pipeline function with this capability." So, the idea would be to have a sql string where the columns are created dynamically, depending on input parameters - and then be able to use this sql everywhere (oracle reports, sqlplus) through a pipelined function.
    Here's the sql (simplified, of course, the data itself is actually not important - the LOOP is the key)
    declare
    v_sql varchar2(4000);
    begin
    v_sql := 'select client, ';
    for i in (select employee from company_employees_view where condition = pi_parameter order by 1) loop
    v_sql := v_sql || sum(decode(employee,''' || i.employee || ''', total)) "' || i.employee || '"';
    end loop;
    v_sql := v_sql || ', sum(total) "Total"';
    v_sql := v_sql || ' from company_employees_view group by client';
    end;
    This sql would result in a final product like:
    select client
    , sum(decode(employee,'John',total) "John"
    , sum(decode(employee,'Paul',total) "Paul"
    , sum(decode(employee,'George',total) "George"
    (and so on... this sql could have more or less columns depending on the input parameters of the function)
    from company_employees_view
    group by client;
    I have tried feeding this sql into a ref cursor and an object, but always received an "inconsistent datatypes" message.
    The object would be something like:
    create or replace object rt_employee as (total number);
    create or replace tt_employee as table of rt_employee;
    create or replace object rt_client as (
    client varchar2(100),
    employee tt_employee);
    create or replace tt_client as table of rt_client;
    (I am not paying too much attention to syntax here.)
    By the way, no hurry whatsoever, this is just for fun, take your time. I am using database XE with apex 2.1 and sql developer 1.2.
    Thanks, Roger

    This is the only solution I've ever seen to dynamic pipelined columns...
    How to pipeline a function with a dynamic number of columns?

  • Sum of columns in union query

    hi, i am using oracle 10g database..
    how to get the sum of column in union query ?
         select * from (select 100 records from dual), (select 50 available from dual)
    union
    select * from (select 200 records from dual), (select 150 available from dual)
    display should be like
                     records         available
                      100               50
                      200               150
    total            300               200thanks ...

    Peter vd Zwan wrote:
    try this:Grouping by records will not produce correct results:
    SQL> with a as
      2  (
      3  select * from (select 100 records from dual), (select 50 available from dual)
      4  union
      5  select * from (select 100 records from dual), (select 100 available from dual)
      6  union
      7  select * from (select 200 records from dual), (select 150 available from dual)
      8  )
      9  select
    10    case when grouping(records) = 0 then null else 'total' end tot
    11    ,sum(records)   records
    12    ,sum(available) available
    13  from
    14    a
    15  group by
    16  rollup (records)
    17  ;
    TOT      RECORDS  AVAILABLE
                 200        150
                 200        150
    total        400        300
    SQL> select  case grouping(rownum)
      2     when 1 then 'Total'
      3   end display,
      4          sum(records) records,
      5          sum(available) available
      6    from  (
      7            select * from (select 100 records from dual), (select 50 available from dual)
      8           union
      9            select * from (select 100 records from dual), (select 100 available from dual)
    10           union
    11            select * from (select 200 records from dual), (select 150 available from dual)
    12          )
    13    group by rollup(rownum)
    14  /
    DISPL    RECORDS  AVAILABLE
                 100         50
                 100        100
                 200        150
    Total        400        300
    SQL> SY.

Maybe you are looking for