How to Query up Monthly Closing Balance on a Table of Transactions

Probably a simple question for an analytics wizard, but I'm not there yet...
Suppose I have a table of financial transactions named TX with TX_DATE and TX_AMOUNT columns and that some months may not have any transactions (i.e., there are gaps). I would like to know the best query for returning the closing monthly balance with no gaps. I suspect it will involve a trick I saw on asktom.oracle.com for generating the list of months between two dates, some outer join cleverness, the use of SUM(TX_AMOUNT) OVER (ORDER BY TX_DATE) or something to generate the running account balance, and some magic to pluck out the last balance amount for each month.
The trick I saw from askTom for generating a gap-less list of months looked like:
with date_range as
(select to_date('1/1/2007','mm/dd/yyyy') mindt, sysdate maxdt from dual)
select level, add_months(mindt,level-1) dt
from date_range
connect by level <= months_between(maxdt,mindt)+1
(assuming in this case the range of tx dates was Jan 1, 2007 through today).
Any assistance would be greatly appreciated.
Thanks,
Bill

Sorry for the lack of clarity - by closing monthly balance, I mean I want the balance of the account as of the end of each month. So, you have to keep a running balance across the transactions (including a data point for months with no transactions) and then grab the running balance out for the latest transaction in each month. I have all but that last bit (which may be answered by another recent thread that I am reading). Here is what I have so far:
with date_range as
(select min(transaction_date) mindt, sysdate maxdt
from fz_transaction
where account_id = 320001
all_months as
(select level, add_months(mindt,level-1) dt
from date_range
connect by level <= months_between(maxdt,mindt)+1
gapless_transactions as
(select id, transaction_date, amount
from fz_transaction
where account_id = 320001
union all
select 1 id, dt transaction_date, 0 amount
from all_months
running_balance as
(select id, transaction_date, sum(amount) over (order by transaction_date, id) balance
from gapless_transactions
order by transaction_date desc, id desc
select * from running_balance
-- Working on this last part to pull out the last entry in each month...
Note that the UNION ALL in the gapless_transactions part throws in a bogus (but harmless in this computation) $0 transaction each month so I have no gaps in any month.
Perhaps there is a more elegant strategy, but I think I'm almost there...

Similar Messages

  • How To Upload OPening or Closing Balance In RG1 Register.

    How To Upload OPening or Closing Balance In RG1 Register.in this table with the help of bdc J_2IRG1BAL.
    I had seen all the links in sdn but didnt get.
    Edited by: Pritesh kumar on Apr 3, 2011 12:20 PM

    How To Upload OPening or Closing Balance In RG1 Register.in this table with the help of bdc J_2IRG1BAL.
    I had seen all the links in sdn but didnt get.
    Edited by: Pritesh kumar on Apr 3, 2011 12:20 PM

  • How to calculate opening and closing balance for period

    Hi all,
    i have to find out opening and closing balance.
    the table structure of temporary table is
    select * from hwcn_xn_fa_report_temp1 where asset_id=10029400
    PERIOD_COUNTER CST_OP_BAL CST_ADDITION CST_TRANSFER CST_DISPOSAL COST_CLOSING_BALANCE
    24108 0 0 0
    24109 12000
    24110 0 0 0
    24111 0 0 0
    in this table cst_op_balnce and cost_closing_balace is null
    i have display cost_op_bal and cost_closing_balnce
    cost_closing_balance=cst_op_bal+cst_addition+cst_transfer+cst_disposal
    for period 2408 op_balnce=0 closing_bal=0
    for period 2409 op_balnce=0 closing_balce=1200
    for period 2410 op_bal=1200 closing_bal=1200
    closing balance of dec will be opening bal of jan
    thanks and regards
    Edited by: user10664276 on Apr 19, 2009 11:08 PM
    Edited by: user10664276 on Apr 19, 2009 11:13 PM

    Hi,
    user11118871 wrote:
    Can you explain what that is? Thank you if you have one example.
    ROWS BETWEEN  UNBOUNDED PRECEDING AND 1 PRECEDING
    When you use the analytic SUM (c) function, then, on each row, it returns the values of column (or expression) c from several rows in the result set added together.
    Which rows? That depends.
    If the analytic clause (the part in parentheses after OVER) does not include ORDER BY, then it is all rows.
    If the analytic clause has an ORDER BY clause, but no windowing clause (that is, ROWS BETWEEN ... or RANGE BETWEEN ...), then the rows included in the sum are all rows up to and including the row where the function is being called (as sorted by the analytic ORDER BY).
    If the analytic cluase has both ORDER BY and a windowing clause "ROWS BETWEEN x PRECEDING AND y PRECEDING", then the rows included in the sum are the rows from x to y rows before the one where the function is called.
    Do some experiments with different values of x and y.
    First, create a table like the one in the problem above, but simplified a little.
    CREATE TABLE     test_sum
    (      period     NUMBER
    ,      new_amt     NUMBER
    INSERT INTO test_sum (period, new_amt) VALUES (24108,     1);
    INSERT INTO test_sum (period, new_amt) VALUES (24109,     4);
    INSERT INTO test_sum (period, new_amt) VALUES (24110,     2);
    INSERT INTO test_sum (period, new_amt) VALUES (24111,     8);
    INSERT INTO test_sum (period, new_amt) VALUES (25001,     32);
    INSERT INTO test_sum (period, new_amt) VALUES (25002,     16);
    COMMIT;The original problem above used names that were meaningful for its application, and columns that have nothing to do with the SUM function. Let's simplify the former and lose the latter.
    That problem involved the SUM of three columns added together. Since we just want to understand how the windowing clause works, let's simplify that to one column.
    With these simplifications, my original query is:
    SELECT       period
    ,       new_amt     
    ,       SUM (new_amt) OVER ( ORDER BY          period
                                         ROWS BETWEEN  UNBOUNDED PRECEDING
                                 AND          1            PRECEDING
                        ) AS opening_balance
    ,       SUM (new_amt) OVER ( ORDER BY          period
                        ) AS closing_balance
    FROM       test_sum
    ORDER BY  period;Given the data above, it produces these results:
    .   PERIOD    NEW_AMT OPENING_BALANCE CLOSING_BALANCE
         24108          1                               1
         24109          4               1               5
         24110          2               5               7
         24111          8               7              15
         25001         32              15              47
         25002         16              47              63So, for example, on the row where period=24110,
    opening_balance=5, which is the total of new_amt from all rows up to but not including that row: 5=1+4, and
    closing_balance=7, which is the total of new_amt from all rows up to and including that row: 7=1+4+2.
    To really understand how the windowing clause works, do some experiments. Change the definition of opening_balance to include " BETWEEN x PRECEDING AND y PRECEDING". You'll find that:
    (a) "UNBOUNDED PRECEDING" means the same as "n PRECEDING", where n is greater than the number of rows in your result set.
    (b) "CURRENT ROW" means the same as "0 PRECEDING"
    (c) x must be greater than or equal to y
    (d) neither x nor y can be negative (but you can use "FOLLOWING" instead of "PRECEDING" to get the same effect).
    For more, see the introduction to "Analytic Functions" in the [SQL Language manual|http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/functions001.htm#sthref972]
    When you're finished, don't forget to
    DROP TABLE     test_sum;

  • BPC 10.0 - Monthly closing balance - Brought forward happens at ECC or to be done at BPC end using BRs?

    Dear All,
    BPC 10.0 - Consolidation Project
    When performing consolidation, every month's closing balance is being brought forward from one month to next month. Would like to know the business practice on how this is being brought forward.
    My question is :
    Is this happening at ECC end? I.e. BPC side does NOT have to do that through business rules?
    Or,
    ECC just send month's data without closing balance and, BPC side will have to bring forward the month's closing balance to next month's opening balance?
    Which one is widely practiced?
    Thank you.
    Regards,
    Peri

    Thanks for your reply.
    I agree with you for business rules are first option. But my question is which option is best among Business Rules
    1) Balance Carryforward Business Rules
    2) Account Transformation business Rule.
    Few point in favor of Account Transformation BR :-
    As business rule account transformation needs few configuration against BCF rules.
    Account transformation uses Account, Category, Flow, Audittrail, Time (Periodic, YTD) and  Sign Reversal.
    Please help me in understanding the scenario which BFC can do but Account Transformation can not ?
    Thanks,
    Vish

  • HOW TO CARRY FORWARD RG1 CLOSING BALANCE TO OPENING BALANCE FOR NEW FISCAL

    Hi Experts
    How to carry forward the RG1 closing stock at the year end to opening balance of Rg1 for new year.
    Wt are the steps required for closing activity of RG1 and carry forward closing balance of last year to opening balance of  new year.
    Thanks

    Hi Rohan,
    For RG1 and RG23 A Part I and RG23 C Part I
    Go to SE16, here enter Table Name - J_2IRG1BAL and Click on "Create" button in initial screen, it will give the maintenance screen. Here mainatin following;
    For each of these materials, you have maintained the material form in table J_2IRG1BAL as below. Do not make any entries in fields that are not listed below:
    EXGRP - Materialu2019s excise group
    DATUM - Date from which RG1 report is required, normally the date of going live
    MATNR - Material
    FORM - Enter P (Packed) or L (Loose). Do not leave this field blank.
    WERKS - Leave this field blank.
    OP FN UOM, OP BN UOM, CB FN UOM - Leave these fields blank. All quantities in this table are updated in the base unit of measure of the material
    USNAM - User ID of the person filling out the table.
    CPUDT - Date of entry
    CPUTM - Time of entry
    Note: - This is to be done before J1I5, J2I5.
    Also refer link;
    Update of Registers RG 1 and RG 23 (Part I)
    For RG23 A Part II, RG23 C Part II and PLA
    Go to SE16, here enter Table Name - J_2IACCBAL and Click on "Create" button in initial screen, it will give the maintenance screen. And maintain following;
    Excise Group
    Data element for Register names
    Date
    Plant
    Basic duty (OP BAL)
    Basic duty (CL BAL)
    Basic duty (EXAMT)
    Extract Indicator
    User name
    Entry Date
    Entered at
    Note: -
    1. Enter OP BAL, CL BAL and EXAMT all as same as opening balance. For e.g. opening balance for RG23ABED is 1400 then this value is to be entered in all the 3 fields.
    2. You have to enter separate line items for all the accounts;
    RG23ABED
    RG23ASED
    RG23AAED
    RG23CBED
    RG23CSED
    RG23CAED
    PLABED
    PLASED
    PLAAED
    PLACESS
    RG23AECS
    RG23CECS
    PLAECS
    RG23AAT1
    RG23CAT1
    PLAAT1
    3. Enter Date is one day before of the opening. For e.g. if opening date is 01.04.2008 then enter it in 31.03.2008
    Then go for J2I5 - Extract and J2I6 - Print Utility
    use following
    http://help.sap.com/bp_bblibrary/470/Documentation/J33_BPP_32_CHEM_EN_IN.doc
    http://help.sap.com/saphelp_erp60_sp/helpdata/en/18/8e113999724854e10000000a11405a/content.htm
    Reefer this link for complete Excise transactions
    http://help.sap.com/saphelp_erp60_sp/helpdata/en/09/ebf138cdd78a4be10000000a114084/frameset.htm
    Re: Excise -initial upload
    Hopefully this will helpfull to resolve your answer.
    Thanks & regards,
    Pankaj Mahajan

  • Query to find closing balance.

    Dear All,
    I have a tables like
    ACCOUNT_BALANCE:
    ACT_CODE     ACT_DATE ACT_OPENING_BAL
    A     5/1/2013     10000
    B     5/1/2013     20000
    C     5/1/2013     30000
    DAILY_TRANSACTION:
    TRN_DATE     ACT_CODE     TRN_TYPE     TRN_AMOUNT
    5/2/2013     B     W     2000
    5/3/2013     C     W     5000
    5/2/2013     B     D     4000
    5/3/2013     B     W     5000
    Condition is if tran_type = 'D' Then Act_opening_Bal + Trn_Amt and tran_type = 'W' Then Act_opening_Bal - Trn_Amt,
    I want output like this
    ACT_CODE ACT_CLOSING_BAL
    A 10000
    B 17000
    C 25000
    Pls help me to write Query..
    Thanks..

    Start with this..
    select b.act_code,b.act_opening_bal+nvl(t.trn_amount,0)_act_closing_bal
    from account_balance b,
         select act_code,sum(case trn_type
                        when 'D' then 1
                        when 'W' then -1
                    end * trn_amount ) trn_amount
         from daily_transaction
         group by act_code
         ) t
    where b.act_code = t.act_code(+);

  • Sql Query - Update Closing Balance

    Hi
    I am trying to write  a SQL Query , for the following table , I want to update Closing Balance in the table during Query refresh and it should update Closing Balance.
    First Row Cl Balance : Op Balance + Receipt - Issue = Cl Balance
    From Second row      :  Last row Cl Balance + Rec - Issue = Cl Balance up to the end of row .
    Date
    Code
    Op Balance
    Rec
    Issue
    Cl Balance
    01/04/2014
    10001
    5000
    0
    0
    5000
    01/04/2014
    10001
    2000
    7000
    01/04/2014
    10001
    200
    6800
    01/04/2014
    10001
    2500
    9300
    05/04/2014
    10001
    300
    9600
    05/04/2014
    10001
    400
    10000
    05/04/2014
    10001
    2000
    8000
    05/04/2014
    10001
    100
    8100
    09/04/2014
    10001
    50
    8050
    10/04/2014
    10001
    250
    8300
    11/04/2014
    10001
    3000
    5300
    Thanks in advance
    Sandy

    Hi
    Thanks for Instant Solution .
    while running the script its been found that all the entries are not calculating correctly , Kindly find here below Calculated Cl Balance and the correct cl.balance
    select trandate,productcode,nvl(opbal,0)opbal,
                                nvl(ptnqty,0)ptnqty,
                      nvl(waybillqty,0)waybillqty,
                    nvl(clbal,0)ClBal,nvl(first_value(opbal)
    over (partition by productcode order by productcode,trandate), 0 )
    + nvl(sum(ptnqty) over (partition by productcode order by productcode,trandate), 0 )
    - nvl(sum(waybillqty) over (partition by productcode order by productcode,trandate), 0 )
    clbalance_calculated
    from fgaging where productcode = 499001
    order by productcode,trandate
    TRANDATE
    PRODUCTCODE
    NVL(OPBAL,0)
    NVL(PTNQTY,0)
    NVL(WAYBILLQTY,0)
    NVL(CLBAL,0)
    CLBALANCE_CALCULATED
    Correct Cl.Balance
    01-Apr-14
    499001
    812720
    0
    0
    0
    812720
    812720
    23-Apr-14
    499001
    0
    610800
    0
    0
    1423520
    1423520
    30-Apr-14
    499001
    0
    0
    1172590
    0
    250930
    250930
    31-May-14
    499001
    0
    1641750
    0
    0
    27330
    1892680
    31-May-14
    499001
    0
    0
    1865350
    0
    27330
    27330
    30-Jun-14
    499001
    0
    1231250
    0
    0
    729110
    1258580
    30-Jun-14
    499001
    0
    0
    529470
    0
    729110
    729110
    30-Jul-14
    499001
    0
    1767500
    0
    0
    2496610
    2496610
    31-Jul-14
    499001
    0
    0
    1304260
    0
    1192350
    1192350
    19-Aug-14
    499001
    0
    702000
    0
    0
    1894350
    1894350
    30-Aug-14
    499001
    0
    0
    958785
    0
    935565
    935565
    30-Sep-14
    499001
    0
    0
    743943
    0
    495622
    191622
    30-Sep-14
    499001
    0
    304000
    0
    0
    495622
    495622
    31-Oct-14
    499001
    0
    895500
    0
    0
    566322
    1391122
    31-Oct-14
    499001
    0
    0
    824800
    0
    566322
    566322
    26-Nov-14
    499001
    0
    617300
    0
    0
    1183622
    1183622
    30-Nov-14
    499001
    0
    0
    837560
    0
    346062
    346062
    29-Dec-14
    499001
    0
    891000
    0
    0
    1237062
    1237062
    31-Dec-14
    499001
    0
    0
    518000
    0
    719062
    719062
    31-Jan-15
    499001
    0
    0
    1116060
    0
    334002
    -396998
    31-Jan-15
    499001
    0
    731000
    0
    0
    334002
    334002

  • FBCJ How to transfer available closing balance to main bank

    Hi,
    May I know how to transfer the available closing balance in the cash journal back to the main bank?
    Thank you

    Dear:
              Create a new Transaction type in FBCJC2 with type B and give in you main bank account number there. Save it. Now you can transfer the balance from your respective Cash journal to main bank account.
    Regards

  • Opening and closing balance logic

    How to get opening and closing balances for a material and chapter-id for tarif-wise report for sales and captive consumption...
    Edited by: vijetasap on Apr 13, 2009 2:25 PM

    Hi Vijeta...
    Try posting this question related to the functional domain forum of your requirement.. you might have more luck there..

  • Calculating Opening & Closing Balances

    Hi Experts.
    I want to know how to calculate Opening & closing Balances of stock Like MB5B transaction using reports.
    I am giving Material N0, Posting date,Plant as Input
    & want to extract Material Document Number, Quantity, Issues & receipts seperately, Opening & Closing Balance of Stock.Also it should be performed day wise.
    This report should be a normal report without using ALV's.
    Can Some Body Help me. Also let me know which tables & fields are being used.
    Thanks.
    Ravi S

    Hi,
    There are various t. code to check line items for vendor like: S_ALR_87012103 but Any table is not helping to check opening/closeing balance for vendor.
    Table BSIK and BSAK are having are records for open items and close items for vendor and system calculate the balance by using these tables.
    Regards,
    Vinod

  • Opening Balance and closing balance

    Dear All,
                 Can i create a calculated field for ledger opening balance and closing balance. we are using  epicor. I dont know the exact table which captures opening balance and closing balance, where as i got credit balances and debit balances for the segments, i could not find opening and closing balances in this table. table name is GLjrntdtl . Any ideas on this subject please.
    Thanks & Regards,
    Akram

    hi Akram,
    this is a question that you may wish to ask at the epicor forums
    -jamie

  • General Ledger report with Op Bal , Trans Line Items and Closing Balance

    Hi Experts,
    My clients needs a General Ledger report which should show Opening balance and all transactions line items with closing figure in a single report for a fiscal year in the given date range wise. Can I get a report in standard sap. Waiting for your reply.
    Thanks in Advance,
    Arabinda Parida

    Hi Parida,
    There is no such report in SAP. Basically all standard report gives line items not with opening and closing balances. Anyway check mentioned transaction which may help to you.
    S_ALR_87012309....It is cash journal report. Anyway you can enter GL account get opening and closing balances with all relavent transactions.
    Regards
    Suma

  • TABLE  for Opening & closing Balance of G/L

    Hi all,
    I would like to know the name of the TABLE from where i can get the closing balance of previous fiscal and the opening balance of this fiscal year.(As there is a mismatch between the c/f balance.)
    Thanks for your Patience & Time
    Regards
    SAP4ME

    Pankaj
    Thanks for the reply.
    But i am not able to get the closing balance in GLT0 table.
    We have the opening balance only.
    My issue is that the C/F balance has not been moved properly to the new fiscal year for a particular G/L code.
    Now i want to check what made the discrepancy.
    If you have any other inputs,kindly provide.
    Thanks for you time
    Regards
    SAP4ME

  • Table name of Customer opening balance & Closing balance

    Hi Gurus.,
                           I want to know the tables in to which the customers opening balance and closing balance is posted,
    VERY VERY URGENT
    Thanks & Regards
    Narayana
    Message was edited by:
            manam narayana

    Hi Manam,
    You cann't find opening/ closing balance in any table.
    T. Code for opening/closing baloance is FBL5N.
    SAP calculate opening/closing balance by using table BSID (Open items) and BSAD (Closed items).
    Regards.
    PS: Assign points if useful.

  • How to query uncommited transactions

    Hi Does anyone know how to query Oracle database from SQL*Plus to view uncommitted transactions?
    Thanks

    I noticed after I posted that I had used a package I found on the web called list that includes several useful functions. So in case someone wants it, here are the package and body:
    ***PACKAGE***
    CREATE OR REPLACE PACKAGE list AUTHID CURRENT_USER IS
    -- All of these functions and procedures have the following parameters:
    -- list_in - A delimited list to be parsed.
    -- delimiter - The delimiter to be used for parsing the list. Defaults
    -- to a comma.
    -- null_item - What to do with null items in the list. A null item is created
    -- by consecutive occurances of the delimiter. Valid values are
    -- 'KEEP' to allow items in the list to be null, or 'SKIP' to ignore
    -- null items, ie. treat consecutive occurances of delimiters as a
    -- single delimiter. The default is 'KEEP'.
    -- delimiter_use - How the delimiter is to be interpreted. Valid values are
    -- 'ANY' to treat the entire delimiter string as a single occurance
    -- of a delimiter which must be matched exactly, or 'ANY' to treat
    -- the delimiter string as a set of single character delimiters, any
    -- of which is a delimiter. The default is 'ANY'.
    -- Return the first item in a list.
    FUNCTION head(
    list_in IN VARCHAR2,
    delimiter IN VARCHAR2 DEFAULT ',',
    null_item IN VARCHAR2 DEFAULT 'KEEP',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY') RETURN VARCHAR2;
    PRAGMA RESTRICT_REFERENCES (head,WNDS,WNPS);
    -- Return the remainder of a list after the first item and its delimiter.
    FUNCTION tail(
    list_in IN VARCHAR2,
    delimiter IN VARCHAR2 DEFAULT ',',
    null_item IN VARCHAR2 DEFAULT 'KEEP',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY') RETURN VARCHAR2;
    PRAGMA RESTRICT_REFERENCES (tail,WNDS,WNPS);
    -- Return the nth item in a list.
    -- The parameter, item_num, denotes which item to return.
    FUNCTION item(
    list_in IN VARCHAR2,
    item_num IN INTEGER DEFAULT 1,
    delimiter IN VARCHAR2 DEFAULT ',',
    null_item IN VARCHAR2 DEFAULT 'KEEP',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY') RETURN VARCHAR2;
    PRAGMA RESTRICT_REFERENCES (item,WNDS);
    -- Append an item to a list and return the new list.
    -- The parameter, item_in, contains the new item to append.
    FUNCTION append_item(
    list_in IN VARCHAR2,
    item_in IN VARCHAR2,
    delimiter IN VARCHAR2 DEFAULT ',') RETURN VARCHAR2;
    PRAGMA RESTRICT_REFERENCES (append_item,WNDS);
    -- Return the number of items in a list.
    FUNCTION num_items(
    list_in IN VARCHAR2,
    delimiter IN VARCHAR2 DEFAULT ',',
    null_item IN VARCHAR2 DEFAULT 'KEEP',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY') RETURN INTEGER;
    PRAGMA RESTRICT_REFERENCES (num_items,WNDS);
    -- Search a list for an item, and give its location in the list,
    -- or zero IF not found.
    -- The parameter, item_in, gives the item to be found in the list.
    FUNCTION in_list(
    list_in IN VARCHAR2,
    item_in IN VARCHAR2,
    delimiter IN VARCHAR2 DEFAULT ',',
    null_item IN VARCHAR2 DEFAULT 'KEEP',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY') RETURN INTEGER;
    PRAGMA RESTRICT_REFERENCES (in_list,WNDS);
    -- Convert an array to a delimited list.
    -- The array to be input is a DBMS_UTILITY.uncl_array so that
    -- the LIST package is compatible with the comma_to_table and
    -- table_to_comma built ins.
    -- In this function, delimiter is always treated as a single
    -- string.
    FUNCTION array_to_list(
    array_in IN DBMS_UTILITY.UNCL_ARRAY,
    arrlen_in IN INTEGER,
    delimiter IN VARCHAR2 DEFAULT ',') RETURN VARCHAR2;
    PRAGMA RESTRICT_REFERENCES (array_to_list,WNDS,WNPS);
    -- Print a list using DBMS_OUTPUT.
    PROCEDURE print_list(
    list_in IN VARCHAR2,
    delimiter IN VARCHAR2 DEFAULT ',',
    null_item IN VARCHAR2 DEFAULT 'KEEP',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY');
    -- Convert a list to an array and return the array and its size.
    -- This is a procedure because it returns more than one value.
    -- The array to be returned is a DBMS_UTILITY.uncl_array so that
    -- the LIST package is compatible with the comma_to_table and
    -- table_to_comma built ins.
    PROCEDURE list_to_array(
    list_in IN VARCHAR2,
    arrlen OUT BINARY_INTEGER,
    array_out OUT DBMS_UTILITY.uncl_array,
    delimiter IN VARCHAR2 DEFAULT ',',
    null_item IN VARCHAR2 DEFAULT 'KEEP',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY');
    -- Sort a list
    -- Null items are always skipped when sorting lists, since they would sort
    -- to the end of the list anyway. CMPFNC is the name of a function to compare
    -- two items. The default of '>' sorts in ascending order, '<' in descending order.
    -- If you write your own function to be used for sorting, it must:
    -- 1. Take two parameters of type VARCHAR2
    -- 2. Return an INTEGER
    -- 3. Return a negative number if the first item is to sort lower than
    -- the second, a zero if they are to sort as if equal, or a positive
    -- number if the first item is to sort higher than the second.
    -- 4. Be executable by the user running the sort. Normal naming rules apply.
    FUNCTION sort_list(
    list_in IN VARCHAR2,
    delimiter IN VARCHAR2 DEFAULT ',',
    cmpfnc IN VARCHAR2 DEFAULT '>',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY') RETURN VARCHAR2;
    PRAGMA RESTRICT_REFERENCES (sort_list,WNDS);
    end;
    ***END PACKAGE SPEC***
    ***BEGIN BODY***
    CREATE OR REPLACE PACKAGE BODY list IS
    current_list VARCHAR2(32760) DEFAULT '';
    current_delim VARCHAR2(30) DEFAULT ',';
    TYPE list_array IS TABLE OF VARCHAR2(2000)
    INDEX BY BINARY_INTEGER;
    current_array list_array;
    current_arrlen BINARY_INTEGER DEFAULT 0;
    current_null_item VARCHAR2(4) DEFAULT '';
    current_delimiter_use VARCHAR2(3) DEFAULT '';
    -- Find the first delimiter.
    FUNCTION find_delimiter(
    list_in IN VARCHAR2,
    delimiter IN VARCHAR2 DEFAULT ',',
    null_item IN VARCHAR2 DEFAULT 'KEEP',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY') RETURN BINARY_INTEGER IS
    delimiter_loc BINARY_INTEGER;
    BEGIN
    IF upper(delimiter_use) = 'ALL' THEN
    delimiter_loc := INSTR(list_in,delimiter);
    ELSIF upper(delimiter_use) = 'ANY' THEN
    delimiter_loc := INSTR(TRANSLATE(list_in,delimiter,ltrim(RPAD(' ',LENGTH(delimiter)+1,CHR(31)))),CHR(31));
    END IF;
    RETURN delimiter_loc;
    END find_delimiter;
    -- Return the first item in a list.
    FUNCTION head(
    list_in IN VARCHAR2,
    delimiter IN VARCHAR2 DEFAULT ',',
    null_item IN VARCHAR2 DEFAULT 'KEEP',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY') RETURN VARCHAR2 IS
    delimiter_loc BINARY_INTEGER;
    BEGIN
    delimiter_loc := find_delimiter(list_in,delimiter,null_item,delimiter_use);
    IF delimiter_loc > 1 THEN
    RETURN SUBSTR(list_in,1,delimiter_loc-1);
    ELSIF delimiter_loc = 1 THEN
    RETURN NULL;
    ELSE
    RETURN list_in;
    END IF;
    END head;
    -- Return the remainder of a list after the first item and its delimiter.
    FUNCTION tail(
    list_in IN VARCHAR2,
    delimiter IN VARCHAR2 DEFAULT ',',
    null_item IN VARCHAR2 DEFAULT 'KEEP',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY') RETURN VARCHAR2 IS
    start_ch BINARY_INTEGER;
    BEGIN
    start_ch := find_delimiter(list_in,delimiter,null_item,delimiter_use);
    IF start_ch = 0 THEN
    RETURN NULL;
    ELSE
    IF upper(delimiter_use) = 'ALL' THEN
    start_ch := start_ch + LENGTH(delimiter);
    ELSE
    start_ch := start_ch + 1;
    END IF;
    IF start_ch > LENGTH(list_in) THEN
    RETURN NULL;
    ELSE
    RETURN SUBSTR(list_in,start_ch);
    END IF;
    END IF;
    END tail;
    -- Convert a list to an array.
    PROCEDURE parse_list(
    list_in IN VARCHAR2,
    delimiter IN VARCHAR2 DEFAULT ',',
    null_item IN VARCHAR2 DEFAULT 'KEEP',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY') IS
    list_to_parse VARCHAR2(32760);
    BEGIN
    IF list_in = current_list AND
    delimiter = current_delim AND
    null_item = current_null_item AND
    delimiter_use = current_delimiter_use THEN
    NULL;
    ELSE
    current_list := list_in;
    current_delim := delimiter;
    current_null_item := upper(null_item);
    current_delimiter_use := upper(delimiter_use);
    list_to_parse := list_in;
    current_arrlen := 0;
    WHILE list_to_parse IS NOT NULL LOOP
    IF current_null_item <> 'SKIP' OR
    head(list_to_parse,delimiter,null_item,delimiter_use) IS NOT NULL THEN
    current_arrlen := current_arrlen + 1;
    current_array(current_arrlen) := SUBSTR(head(list_to_parse,delimiter,null_item,delimiter_use),1,2000);
    END IF;
    list_to_parse := tail(list_to_parse, delimiter,null_item,delimiter_use);
    END LOOP;
    END IF;
    END parse_list;
    -- Convert a list to an array and return the array and its size.
    PROCEDURE list_to_array(
    list_in IN VARCHAR2,
    arrlen OUT BINARY_INTEGER,
    array_out OUT DBMS_UTILITY.uncl_array,
    delimiter IN VARCHAR2 DEFAULT ',',
    null_item IN VARCHAR2 DEFAULT 'KEEP',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY') IS
    BEGIN
    parse_list(list_in,delimiter,null_item,delimiter_use);
    arrlen := current_arrlen;
    FOR i IN 1..arrlen LOOP
    array_out(i) := SUBSTR(current_array(i),1,240);
    END LOOP;
    END list_to_array;
    -- Print a list using DBMS_OUTPUT.
    PROCEDURE print_list(
    list_in IN VARCHAR2,
    delimiter IN VARCHAR2 DEFAULT ',',
    null_item IN VARCHAR2 DEFAULT 'KEEP',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY') IS
    BEGIN
    DBMS_OUTPUT.ENABLE(100000);
    parse_list(list_in,delimiter,null_item,delimiter_use);
    FOR i IN 1..current_arrlen LOOP
    dbms_output.put_line(SUBSTR(current_array(i),1,240));
    END LOOP;
    END print_list;
    -- Return the number of items in a list.
    FUNCTION num_items(
    list_in IN VARCHAR2,
    delimiter IN VARCHAR2 DEFAULT ',',
    null_item IN VARCHAR2 DEFAULT 'KEEP',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY') RETURN INTEGER is
    BEGIN
    parse_list(list_in,delimiter,null_item,delimiter_use);
    RETURN current_arrlen;
    END num_items;
    -- Return the nth item in a list.
    FUNCTION item(
    list_in IN VARCHAR2,
    item_num IN INTEGER DEFAULT 1,
    delimiter IN VARCHAR2 DEFAULT ',',
    null_item IN VARCHAR2 DEFAULT 'KEEP',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY') RETURN VARCHAR2 is
    BEGIN
    parse_list(list_in,delimiter,null_item,delimiter_use);
    IF item_num NOT BETWEEN 1 AND current_arrlen THEN
    RETURN NULL;
    ELSE
    RETURN current_array(item_num);
    END IF;
    END item;
    -- Append an item to a list and return the new list.
    -- The parameter, item_in, contains the new item to append.
    FUNCTION append_item(
    list_in IN VARCHAR2,
    item_in IN VARCHAR2,
    delimiter IN VARCHAR2 DEFAULT ',') RETURN VARCHAR2 IS
    BEGIN
    IF list_in IS NULL THEN
    RETURN item_in;
    ELSE
    RETURN list_in || delimiter || item_in;
    END IF;
    END append_item;
    -- Search a list for an item, and give its location in the list,
    -- or zero IF not found.
    FUNCTION in_list(
    list_in IN VARCHAR2,
    item_in IN VARCHAR2,
    delimiter IN VARCHAR2 DEFAULT ',',
    null_item IN VARCHAR2 DEFAULT 'KEEP',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY') RETURN INTEGER is
    BEGIN
    parse_list(list_in,delimiter,null_item,delimiter_use);
    FOR item_num IN 1..current_arrlen LOOP
    IF current_array(item_num) = item_in THEN
    RETURN item_num;
    END IF;
    END LOOP;
    RETURN 0;
    END in_list;
    -- Convert an array to a delimited list.
    FUNCTION array_to_list(
    array_in IN DBMS_UTILITY.UNCL_ARRAY,
    arrlen_in IN INTEGER,
    delimiter IN VARCHAR2 DEFAULT ',') RETURN VARCHAR2 IS
    list_out VARCHAR2(32760):= '';
    BEGIN
    FOR item_num IN 1 .. arrlen_in LOOP
    EXIT WHEN LENGTH(list_out) +
    LENGTH(array_in(item_num)) > 32760;
    list_out := list_out||array_in(item_num);
    IF item_num < arrlen_in THEN
    list_out := list_out||delimiter;
    END IF;
    END LOOP;
    RETURN list_out;
    END array_to_list;
    -- Sort a list
    FUNCTION sort_list(
    list_in IN VARCHAR2,
    delimiter IN VARCHAR2 DEFAULT ',',
    cmpFnc IN VARCHAR2 DEFAULT '>',
    delimiter_use IN VARCHAR2 DEFAULT 'ANY') RETURN VARCHAR2 IS
    temp_array list_array;
    temp_len PLS_INTEGER := 0;
    temp_item VARCHAR2(2000);
    list_out VARCHAR2(32760);
    PROCEDURE swap (
    first_item IN OUT VARCHAR2,
    second_item IN OUT VARCHAR2) IS
    temp_item VARCHAR2(2000);
    BEGIN
    temp_item := first_item;
    first_item := second_item;
    second_item := temp_item;
    END swap;
    FUNCTION cmp (
    first_item IN VARCHAR2,
    second_item IN VARCHAR2,
    cmpfnc IN VARCHAR2 DEFAULT '=') RETURN INTEGER IS
    return_value INTEGER;
    BEGIN
    IF cmpfnc = '>' THEN
    IF first_item < second_item THEN
    return_value := -1;
    ELSIF first_item = second_item THEN
    return_value := 0;
    ELSIF first_item > second_item THEN
    return_value := 1;
    END IF;
    ELSIF cmpfnc = '<' THEN
    IF first_item > second_item THEN
    return_value := -1;
    ELSIF first_item = second_item THEN
    return_value := 0;
    ELSIF first_item < second_item THEN
    return_value := 1;
    END IF;
    ELSE
    EXECUTE IMMEDIATE 'BEGIN :I := '||cmpfnc||'(:A,:B); END;'
    USING OUT return_value, IN first_item, IN second_item;
    END IF;
    RETURN return_value;
    END cmp;
    BEGIN
    parse_list(list_in,delimiter,'SKIP',delimiter_use);
    FOR item_num IN 1..current_arrlen LOOP
    temp_item := current_array(item_num);
    FOR i IN 1..temp_len LOOP
    IF cmp(temp_array(i),temp_item,cmpfnc) > 0 THEN
    swap(temp_array(i),temp_item);
    END IF;
    END LOOP;
    temp_len := temp_len + 1;
    temp_array(temp_len) := temp_item;
    END LOOP;
    FOR item_num IN 1..temp_len LOOP
    EXIT WHEN LENGTH(list_out) +
    LENGTH(temp_array(item_num)) > 32760;
    list_out := list_out||temp_array(item_num);
    IF item_num < temp_len THEN
    list_out := list_out||delimiter;
    END IF;
    END LOOP;
    RETURN list_out;
    END sort_list;
    END;
    *** END BODY***
    Carl

Maybe you are looking for

  • Charactersitic values to be used in IFTHEN ELSE STATEMENT IN QUERY

    scenario: i need to use the characteristic values(not the attributes) to be used in an IF THEN ELSE STATEMENT in query. so i created a formula variable for the characteritic of processing type replacement path, replace with key.The values are not fet

  • How to highlight text in a screen grab?

    I did a screen grab from imdb (Internet Movie DataBase) off the Internet.  It's currently in .png format. I want to highlight part of the text in the text in this picture as if I were using a yellow highlighter marker.  I've tried everything I can th

  • Payment terms requirement

    Hi All, plz have look on my clent requirement In Account payables. Regarding the Payment terms for different vendors following are the scenarios:- · For Material o 25% payment advance against corporate guarantee, 65% with in 30 days after receipt of

  • Quantity column is not updating in YR02 report

    Dear Experts, While doing download the asset data into excel through t.code YR02 the field quantity is not updating. If i checked in asset master data, there i am getting asset quantity 1 for each asset but in YR02 report i am not getting. Please hel

  • Problem in -Reception of CANopen Data in PXI

    Following are the steps carried out to transmission/recption code for CANopen message: 1.Transmission from cRIO(RT)9014 having 9853 card over CANopen to PXI 2.The data transmitted is visible in bus monitor of PXI. 3.Couldnot able to get the data usin