Selecting from many stages

dear oracle guru's
I have a process which has 5 stages stages are numbered as 1,2,3,4,5
A stage is completed either at 4 or some times at 5
Process Starts at 1 always
then we can proceed to stage 2 then to stage 3 then ....
otherwise after stage 1 we can jump to stage 4 and finish the process
for every stage processed there is start date and end date
if we reach process 4 or 5 but the end is null , then stage is incomplete and so the process . The process is complete only if stage is 4 or 5 and there is a end date .
The stage table has
appli_no, stage_Code,start_date , end _Date
consider a application number say 1455 , this application is pending since at the stage 4 there is no end date
where as application number say 1456 and 1457 is complete and 1458 is incomplete
the data might be as follows
appli_no stage_Code start_date end _Date
1455 1 01-Jan-2010 02-Jan-2010
1455 2 02-Jan-2010 02-Jan-2010
1455 4 02-Jan-2010
1456 1 01-Jan-2010 01-Jan-2010
1456 5 01-Jan-2010 01-Jan-2010
1457 1 03-Jan-2010 03-Jan-2010
1457 4 03-Jan-2010 03-Jan-2010
1458 1 03-Jan-2010 03-Jan-2010
1458 5 03-Jan-2010
i would like to select applino which are complete that is their stage code in 4 or 5 and end date is not null
and application numbers which are not complete that is they can be in any stage
i managed the first one . some how i am not able to manage the second one
kindly pull me out of things
with warm regards
ssr

Maybe
SQL> with t as (
select 1455 appli_no, 1 stage, '01-Jan-2010' start_dt, '02-Jan-2010' end_dt from dual union all
select 1455, 2, '02-Jan-2010', '02-Jan-2010' from dual union all
select 1455, 4, '02-Jan-2010', null from dual union all
select 1456, 1, '01-Jan-2010', '01-Jan-2010' from dual union all
select 1456, 5, '01-Jan-2010', '01-Jan-2010' from dual union all
select 1457, 1, '03-Jan-2010', '03-Jan-2010' from dual union all
select 1457, 4, '03-Jan-2010', '03-Jan-2010' from dual union all
select 1458, 1, '03-Jan-2010', '03-Jan-2010' from dual union all
select 1458, 5, '03-Jan-2010', null from dual union all
select 1459, 1, '03-Jan-2010', '03-Jan-2010' from dual union all
select 1459, 3, '03-Jan-2010', null from dual
select case
          when stage in (4, 5) and end_dt is null then 'Pending'
          when stage in (4, 5) and end_dt is not null then 'Finished'
          else 'In Progress'
       end
          status,
       appli_no,
       stage
from (select t.*, count (*) over (partition by appli_no order by stage desc) rn
      from t t)
where rn = 1
STATUS        APPLI_NO      STAGE
Pending           1455          4
Finished          1456          5
Finished          1457          4
Pending           1458          5
In Progress       1459          3
5 rows selected.

Similar Messages

  • Select from many tables of the same type

    Hi everybody!
    My problem is the next:
    I have many tables with big account of data (millions regs), so I did something like that:
    The regs dated 1999 are in the table XXX_1999, those dated 2000 - in XXX_2000, and so on.
    Now, if I want to make query from date1 to date2 (could be some years of difference), I don't know the number of tables I have to query in execution time.
    I want to make a procedure that returns 1 recordset (or cursor) with all the data in it without using temporary tables.
    Is it possible and how?
    Thanks

    SQL> r
      1  declare
      2    c_CRLF constant varchar2(2) := chr(13)||chr(10);
      3
      4    v_date1 date := to_date('15.03.2001', 'DD.MM.YYYY');
      5    v_date2 date := to_date('17.08.2003', 'DD.MM.YYYY');
      6
      7    cursor c_years is
      8      select to_number(to_char(v_date1, 'YYYY')) + rownum-1 year
      9      from user_tables
    10      where rownum <= to_number(to_char(v_date2, 'YYYY')) -to_number(to_char(v_date1, 'YYYY')) +1;
    11
    12    v_stmnt varchar2(2000);
    13  begin
    14    for rec in c_years loop
    15      if c_years%ROWCOUNT > 1 then
    16        v_stmnt := v_stmnt || c_CRLF ||'UNION ALL' || c_CRLF;
    17      end if;
    18      v_stmnt := v_stmnt || 'select * from XXX_'||rec.year;
    19    end loop;
    20    dbms_output.put_line(v_stmnt);
    21* end;
    select * from XXX_2001
    UNION ALL
    select * from XXX_2002
    UNION ALL
    select * from XXX_2003
    PL/SQL procedure successfully completed.
    SQL>You will need to add some bounds checking to avoid "table or view does not exist'
    if date1 < 2001 -> date1=2001
    if date2 > current year -> date2=current year
    Message was edited by:
    Jens Petersen

  • Select from (too many) tables

    Hi all,
    I'm a proud Oracle Apex developer. We have developed an Interactive Report that is generated from many joined tables in a remote system. I've read that to improve performances we can do the following:
    1) Create a temporary table on our system that stores the app_user id and the colmun as a result of the query
    2) Create a procedure that does:
    declare
    param1:= :PXX_item
    param2:= :PXY_item.
    param3:= :V('APP_USER')
    insert into <our_table>
    (select param3, <query from remore system>)
    commit;
    3) Rediresct to a query page where IR reads from this temp table
    On "Exit" button there's a procedure that purge table data of that user (delete from temp where user=V('app_user'), so the temp table is only filled with necessary data.
    Do you see any inconvenience? Application will be used from about 500 users, about 50 concurrent users at a time.
    Thank you!

    1) We don't have a control on source syste, we can only perform query on itI was referring to a materialized view on the system where Apex is installed, not on the source database.
    2) There are many tables involvedI don't understand why this is a problem. Too much data I can see, but too many tables... not so much.
    3) Data has to be in real time, with no delayThis would a problem for MV or collections. The collections would store the data as of the initial query. Any IRs using the collection after the fact would be using stale data. If you absolutely have to have the data as of right now every time, then the full query must run on the remote system every time. Tuning that query is the only option to make it faster.
    4) There are many transactions on the source tables (they are the core of the source system) and so MV could not be refreshed so fastProbably could be with fast refresh enabled, but not necessarily practical to do so. As I indicated in 3, you have painted yourself into a corner here. You have indicated a need for a real-time query and that eliminates a number of possibilities for query-once use-many performance solutions.

  • How to transfer music files from sonic stage to a hard drive

    Hi all
    I need your help, I am pulling my hair out here for the past 3 weeks.  I purchased a hard drive from Apple and I want to transfer all my music files from Sonic stage which in on my old Fitjitsu laptop.
    I then want to transfer the music from the hard drive to iTunes to my new mac airbook
    Any help is appreciated at this present time I am hating Apple product big time.  Maybe it will restore once I am guided at present Apple customer services who sold me the product initially couldn't help me.
    Cheers

    I am guessing this Fitjutsu laptop is running Windows which uses NTFS format drives.  If you bought a hard drive from Apple it is probably formatted for Mac use. Anyway, I don't know why you are blaming Apple. Hard drives come in one of the other format and you need one that works with both.  Sales people at many kinds of stores rarely know much about things they sell outside of immediate application.  They are trained in the things they sell but are not technically minded.  If you had bought the drive anywhere else you would be like the 2 questions I answered yesterday where people got the music onto the NTFS drive but didn't know why it wouldn't work with the Mac.
    You haven't told us much about the Fitjutsu laptop.  You may be able to use Migration Assistant to transfer the entire contents to the Mac.  This will set up a separate user account with the content.
    About Windows Migration Assistant - http://support.apple.com/kb/ht4796 - Learn about how to use Windows Migration Assistant to migrate your files from a Windows PC to a Mac.
    If you need/want to use a drive to get the music off the other computer you will need a drive with either NTFS format or FAT32 (MS-DOS) format.  With NTFS format the Mac can read but not write to the drive.  You can use it for transferring the files but it will have to be re-formatted back to Mac format for use with the Mac.  Alternatively you can reformat your Mac drive to FAT32 (MS-DOS) format using Disk Utility. Macs can both read and write to this format but is isn't really a a Mac format (Macs can't repair a FAT drive) so eventually you may wish to reformat it too back to Mac format.  Formatting a drive erases all content so once you get the content onto your Mac you will have to store it there temporarily when you format the drive back to Mac format.
    I know this is sounding complicated but Apple's answer to transferring PC content is Migration Assistant.  If you don't want to do that then yes, you are entering the realm where there is fiddly hands-on things to do.
    If this is a brand new Mac you may still be in the 90 day period where you can get free help at an Apple Store from the "Genius" bar.  I'm guessing, however, this won't extend to their formatting and reformatting a drive and transferring select content.

  • Random MovieClip script not selecting from all possible outcomes

    i have a collection of movie clips (mc0, mc1, mc2...etc etc),
    and when motion is detected on a webcam, one of these clips is shown on the stage.
    however, for some reason only mc0, mc1 and mc2 are being displayed,
    and i cannot get mc3, mc4 or any more to be chosen.
    Code:
    import flash.filters.*
    // Assumes a Video object named "myVideoObject" is on the Stage
    active_cam = Camera.get();
    filterList = [
                     /* 0 */ "multiply",
                     /* 1 */ "multiply",
                     /* 2 */ "multiply",
                    /* 3 */ "multiply",
                    /* 4 */ "multiply"
    positionList = [
                     /* 0 */ {_x: 512, _y: 288},
                     /* 1 */ {_x: 512, _y: 288},
                     /* 2 */ {_x: 512, _y: 288},
                    /* 3 */ {_x: 512, _y: 288},
                     /* 4 */ {_x: 512, _y: 288}
    myVideoObject.attachVideo(active_cam);
    active_cam.setMotionLevel(95, 100);
    active_cam.onActivity = function(mode)
        trace(mode);
         var randId = Math.floor(Math.random() * 5);
         var init = positionList[randId];
         /* old init... {_x: Math.random() * _root._width, _y:Math.random() * _root._height}; */
         var depth = _root.getNextHighestDepth();
         var movieId = "mc" + randId;
         if(mode) {
              var mc = _root.attachMovie(movieId, movieId + depth, depth, init);
              mc.blendMode = _root.filterList[randId];
    I had the first three working fine, so when i added 2 more to the Filter and position Lists, and changed
    the Mathrandom mutliplier to 5 instead of 3, i thought that would work.
    Im really stumped, id like the script to choose from many more than 3 movie clips

    You should put a trace to check the movieId value to confirm that the code calls for movies > 2.
    The random selection code should be fine as is, so you may have to wait a bit to see one of the movies you say is not displaying.  If you were to increase the number of them, the chances of seeing some in the range > 2 is better.  The only thing I can think of from your code that might prohibit showing something > 2 is the mode value, since that's the only thing that prohibits display of anything.
    I am not at all familiar with video cams andactionscript regarding them, but would it be necessary to clear out the current mc# from being present/active before adding a new one?

  • How to perform multiple selection from dropdown list

    Hi,
           I have developed one application in which i have taken one dropdownbyindex and entered some values in it, now i need to have multiple selection of entries, can any one please suggest how to do these
    Regards,
    Prasanna

    A drop-down list is by definition a 1-from-many selector.
    Armin

  • How to get the select * from emp table output on the console  using java

    public class software {
          * @param args
         static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
         static final String DATABASE_URL = "jdbc:oracle:abc";
         private static Connection connection;
         private static Statement statement;
         public static void main(String[] args) {
              // TODO Auto-generated method stub
         try {
              System.out.println("-------THIS IS THE Class.forNameJDBC_DRIVER");
                   Class.forName(JDBC_DRIVER);
                   System.out.println("THIS IS THE Class.forNameJDBC_DRIVER");
                   connection = DriverManager.getConnection(DATABASE_URL, "abc",
                   "abc");
                   System.out.println("THIS IS THE connection abc ,abc");
                   statement = connection.createStatement();
                   //Query to find the values in the EMP table.
                   ResultSet resultSet = statement.executeQuery("SELECT * from EMP");
                   if(resultSet.next()){
                   System.out.println("THESE ARE THE VALUES IN EMP TABLE:"+resultSet);  /// How can i get all the values record wise on the  console ??????
                   resultSet.close();
         catch (ClassNotFoundException classNotFound) {
                   System.out.println("Driver not Found"+classNotFound.getMessage());
              } catch (SQLException sqlException) {
                   System.out.println("SQL Exception - bad sql");
                   System.out.println(sqlException.getMessage());
    }

    1sai
    Please assign the dukes here and in your previous threads.
    See [http://wikis.sun.com/display/SunForums/Duke+Stars+Program+-+How+it+Works]
    You are currently the all time career leader in un-awarded dukes, with including this thread 75 unawarded dukes for questions you marked as answered.
    It's even worse when you look and see that you have awarded many dukes as well. So you do know how to do it. You're just too lazy and rude to be bothered.
    Don't be a lazy wank.

  • How can I sync my iPad to a computer after syncing it to the iCloud? I have the option of setting it up new, or restoring to a sync from many months ago. I dont want to lose any apps but I would like to back up on computer. No auto sync like other devices

    How can I sync my iPad to a computer after syncing it to the iCloud? I have the option of setting it up new, or restoring to a sync from many months ago. I dont want to lose any apps but I would like to back up on computer. No auto sync like other devices.

    Plug it into your computer. Tell it to sync with "this computer" instead of iCloud. You shouldn't have to remove any apps. Otherwise, you can save the app data by using i-FunBox ( http://www.i-funbox.com/ ) just go to the "devices" tab and select 'user applications' and select all of your apps and tell iFunBox to "copy to pc" you're done! You have them all backed up.

  • How to populate a table based on a row selection from another table.

    Hi, i just started to use ADF BC and Faces. Could some one help me or point me a solution on the following scenario .
    By using a search component , a table is being displayed as a search result. If i select any row in the resulted table , i need to populate an another table at the bottom of the same page from another view. These two tables are related by primary key . May i know how to populate a table based on a row selection from another table. Thanks
    ganesh

    I understand your requirement and the tutorial doesn't talk about Association between the views so that you can create a Master-Detail or in DB parlance, a Parent-Child relationship.
    I will assume that we are dealing with two entities here: Department and Employees where a particular Department has many Employees and hence a Parent-Child relationship.
    Firstly, you need to create an Association between the two Entities - Department and Employees. You can do that by right clicking on the model's entity and then associating the two entities with the appropriate key say, DepartmentId.
    Once you have done that, you need to link the two entities in the View section with this Association that you created. Then go to AppModule and make sure that in the Available View Objects: 'EmployeesView' appears under 'DepartmentView' as "EmployeesView via <link you created>". Shuttle the 'DepartmentView' to the right, Data Model and then shuttle
    "EmployeesView via <link you created>" to the right, Data Model under 'DepartmentView'.
    This will then be reflected in your Data Controls. After that, you simply would have to drag this View into your page as a Master-Detail form...and then when you run this page, any row selected in the Master table, would display the data in the Detail table.
    Also, refer to this link: [Master-Detail|http://baigsorcl.blogspot.com/2010/03/creating-master-detail-form-in-adf.html]
    Hope this helps.

  • Transfering music from sonic stage to ipod?

    I prviously had a mp3 player that used Sonic Stage so I have many music files downloaded to Sonic Stage. I need to get the music files from Sonic Stage to the Itunes library or to my Ipod nano. Does anybody know how to do this or if this is even possible. I would appreciate any help.

    You need to check the format of your files but from what I have read, Sonic Stage uses ATRAC (the same encoding as MiniDisc). You would need to find a way to convert the ATRAC files to a format that iTunes can use such as MP3.
    What is SonicStage?
    ATRAC to MP3

  • Is it possible to ... SELECT * FROM my_table WHERE ssn IN (..arraylist..) ?

    Hi, I have a quick question I hope someone can help me with. I'm a student and what I'm looking for should be easy but I can't find any information on it.
    Here's my code, it's probably self-explanatory but to clarify I'm trying to get a list of "Captains" in the order of who has the most wins.
    The problem is that the database tables have thousands of "Captains" and I'm only supposed to look at 200 specific "Captains" which have their ssn in a specific arraylist and then return the top 80 "Captains" from that selection.
    Something like this...
    SELECT first 80 E.name, L.ssn, COUNT(L.wins) as Wins
    FROM log L, employees E
    where type matches "[Captain]"
    and E.ssn = L.ssn
    and L.ssn IN (...arraylist...) // How do I loop through the arraylist but still return a list of the top 80 winners?
    group by E.name, L.ssn
    order by Wins desc;
    Should I start by taking the list of social security numbers from the arraylist and insert them into a temporary table and then use that temporary table to base my selection on?
    For example:
    int rows = 0;
    PreparedStatement ps = conn.prepareStatement("INSERT INTO TEMP captainsTemp (ssn) VALUES(?)");
    Iterator i = myArrayList.iterator();
    while (i.hasNext())
         // Set the variables
         for (int pos = 1; pos <= 63; pos++)
              String s = (String)i.next();
              ps.setString(pos,s);
         // insert a row
         rows += ps.execute();
    ...and then below that I could use
    "SELECT * FROM captains
    WHERE ssn IN (SELECT * FROM captainTemp)..."
    This looks like an ugly solution and I'm not sure if it works, sessionwise..
    Everything's written in Java and SQL.
    If you have any thoughts on this I would be most grateful.
    I should add that this is NOT a school assignment but something I'm trying to figure out for my work...
    Many thanks,
    sincerely,
    JT.

    hi,
    Ignore my previous response. Try out this one. It should help you.
    Lets take the example of EMP table (in Oracle's SCOTT Schema). The following is the description of the table.
    SQL> desc emp
    Name Null? Type
    EMPNO NOT NULL NUMBER(4)
    ENAME VARCHAR2(10)
    JOB VARCHAR2(9)
    MGR NUMBER(4)
    HIREDATE DATE
    SAL NUMBER(7,2)
    COMM NUMBER(7,2)
    DEPTNO NUMBER(2)
    SQL> select ename from emp;
    ENAME
    SMITH
    ALLEN
    WARD
    JONES
    MARTIN
    BLAKE
    CLARK
    SCOTT
    KING
    TURNER
    ADAMS
    JAMES
    FORD
    MILLER
    Say, the ArrayList contains 3 names CLARK,KING & MILLER. You want to loop through the ArrayList for the ENAME values.
    First construct a string like below from the ArrayList.
    "ename in 'CLARK' OR ename in 'KING' or ename in 'MILLER'";
    Append this string to the normal SELECT Query
    Query :
    select ename from emp where ename in 'CLARK' OR ename in 'KING' or ename in 'MILLER'
    Here you get the desired output & thats pretty fast because you just do it once !!!
    SQL> select ename from emp where ename in 'CLARK' OR ename in 'KING' or ename in 'MILLER';
    ENAME
    CLARK
    KING
    MILLER
    you can extend this to your Query also.
    thanks,
    Sriram

  • I bought my i pod touch from us but i live in india .i have been using this from many days fr just a few days before something went wrong with it and the date and time has changed what do i do?

    i bought my i pod touch from us but i live in india .i have been using this from many days fr just a few days before something went wrong with it and the date and time has changed what do i do?

    Have you went to Settings>General Time&Date and correct the time.  Make sure the time zone is correct too.  Also go to Settings>General>Inernational and make sure the Gergorian calender is selected.

  • Select from 4 tables but include data from 3 even if 4th is null

    Hello -
    I'm quite new to oracle and apex, but enjoying learning - but sometimes I need a gentle nudge to know what I need to learn about.
    I have a select statement that works - selecting specific columns from 3 tables:
    SELECT
    "TERRITORIES"."TER_NAME" "TER_NAME",
    "TERRITORY_TYPES"."TTP_DESCRIPTION" "TTP_DESCRIPTION",
    "COUNTRIES"."CNT_DESCRIPTION" "COUNTRY"
    FROM
    "TERRITORIES", "TERRITORY_TYPES","COUNTRIES"
    WHERE
    "TERRITORIES"."TER_TTP_ID"="TERRITORY_TYPES"."TTP_ID"
    and
    "COUNTRIES"."CNT_TER_ID"="TERRITORIES"."TER_ID"
    I want to add in a 4th table for, you guessed it, States.
    However, many of the countries do not yet have states in the states table (and may never have any). Therefore, they do not appear in the results. I want them included in the query, so that I'll have the opportunity to add in the data via Apex.
    Is there a phrase I can insert in the 1st query so that I'll get data for Territory Type, Territory and Country, even if the State table is null?
    Or, do I need to insert records into the state table, such as: insert into states (state_ID, STATE_CNT_ID) values (state_seq.nextval,2). If so, do I just do that over and over, replacing the value? Or is this where I need to learn about bind variables? Or some other command?
    Thank you-
    Marion in NY
    Edited by: mtpaper on Oct 24, 2009 12:54 PM
    I FIGURED IT OUT! I DID IT! How do I mark myself as helpful???
    insert INTO states
    (state_ID, STATE_CNT_ID)
    SELECT state_seq.nextval, cnt_id
    FROM countries
    WHERE not exists (select * from states where states.state_cnt_id = countries.cnt_id)
    Edited by: mtpaper on Oct 24, 2009 1:10 PM

    You certainly could insert data into the STATES table, but I generally wouldn't advise inserting rows into a STATES table for states that don't actually exist. It would seem to make far more sense to just do an outer join when you include the STATES table in your query
    SELECT "TERRITORIES"."TER_NAME" "TER_NAME",
           "TERRITORY_TYPES"."TTP_DESCRIPTION" "TTP_DESCRIPTION",
           "COUNTRIES"."CNT_DESCRIPTION" "COUNTRY",
           s.state_name
      FROM TERRITORIES t ,
           TERRITORY_TYPES tt,
           COUNTRIES c,
           states s
    WHERE "TERRITORIES"."TER_TTP_ID"="TERRITORY_TYPES"."TTP_ID"
       and "COUNTRIES"."CNT_TER_ID"="TERRITORIES"."TER_ID"
       and c.cnt_id = s.state_cnt_id(+)The {noformat}(+){noformat} operator indicates that you want to do an outer join. So if there is no row in the STATES table that matches the join condition, a NULL is returned.
    From a purely stylistic standpoint, I would generally suggest using aliases (i.e. the T, TT, C, and S in the FROM clause) rather than having to constantly write out all the table names. And I wouldn't suggest putting double-quotes around everything-- that forces all your identifiers to be upper case and case sensitive.
    Justin

  • Sample PHP Service selecting from multiple tables

    Hi all!
    I have the following challange:
    How do I properly set up my PHP-service to insert, select, update and delete values from multiple tables?
    So far, the standard templates generated by Flash Builder is based on a single table.
    Example: I have 2 tables: [person] and [school]
    [person] has [person_id, first_name, last_name, birthdate]
    [school] has [school_id, person_id, school_name, city]
    One [person] can have multiple [schools]
    How should I define the selectByID function in PHP to be able to have
    First name: [TextInput /]
    Last name: [TextInput /]
    Birthdate: [DateField /]
    Schools:
    [TabBar: School1, School2, School3 /]
    [ViewStack1]
    School name: [TextInput /]
    Location name: [TextInput /]
    [/ViewStack1]]
    [ViewStack2]
    School name: [TextInput /]
    Location name: [TextInput /]
    [/ViewStack2]]
    [ViewStack3]
    School name: [TextInput /]
    Location name: [TextInput /]
    [/ViewStack3]]
    And even more interesting: How do I update all these fields back to the database?

    First, the relationship between school and person is many-to-many NOT one-to-many -- you will need to add a junction table.
    From the form you have given I would handle insertions like this:
    loop through all the schools and see if the school already exist in the DB. If so, then store the school_id. If not, then create a new record and store the id. You should have an array collection of store_ids by the end of the loop
    Check whether the student exists w/in the DB. If so, then you might consider aborting the operation or you could opt to do an update. If the student doesn't exist, then create a new student record and store the new student_id (mysql::insert_id)
    Loop through the school_id array and add new student_id/school_id records into the junction table.
    Retrieving records is much simpler -- it's just a join on the tables i.e. "SELECT * FROM student INNER JOIN school_student ON student.student_id = school_student.student_id INNER JOIN schools ON school_student.school_id = school.school_id WHERE student.first_name = 'John' AND student.last_name = 'Doe' (assuming there aren't more than one John Does of course!).
    - e

  • How to get result of Select from stored function.

    I need to get result of select from a stored function.
    In the end of my stored function I makes final select (four columns).
    How it can be retrived from function?

    Hi,
    A function can only return one value, but it sounds like you want to return 4 values.
    The one value that you return can be a record, with many columns, such as a ROWTYPE, or a TYPE that you define.
    You can return an XMLTYPE that has whatever elements you want.
    You can write a procedure that has several OUT parameters. (You can have OUT parameters in a function, but a lot of people find that confusing.)
    In very special circumstance, you might consider returning a string that is a delimited list of values, such as '7639,SMITH,,17-DEC-1980'.
    Someoneelse has a good point.
    We could give a better answer if you ask a specific question, like:
    "I have this table ...
    I want a function such that, if I call it with these parameters ... I get ...
    but if I call it like this ... then I get ..."

Maybe you are looking for