Sum of first 50% of rows and remaining 50% of the rows seperately

Hi
I have a table
create table eresults
(student_name varchar2(20),
section_name varchar2(4),
exam_id NUMBER (4))
marks NUMBER (3))
Begin
insert into eresults values ('MOEED', 'A', 1, 20);
insert into eresults values ('SARAH', 'A', 1, 30);
insert into eresults values ('SAM', 'A', 1, 24);
insert into eresults values ('MOEED', 'A', 2, 65);
insert into eresults values ('SARAH', 'A', 2, 100);
insert into eresults values ('SAM', 'A', 2, 4);
insert into eresults values ('MOEED', 'A', 3, 34);
insert into eresults values ('SARAH', 'A', 3, 10);
insert into eresults values ('SAM', 'A', 3, 40);
insert into eresults values ('SARAH', 'A', 4, 33);
insert into eresults values ('SAM', 'A', 4, 99);
end;
/ I want to take a sum of marks, group by student name, for each student in such a way that their first 50% of exams (order by exam id) marks sum is shown seperately in a column and the remaining 50% of the exams summed marks are shown in another column. For students appearing in odd number of exams, like 1,3,5,7 etc - I want the calculation in such a way that first 50% sum will show marks obtained like this: For example a student appeared in 3 exams, so 50% exams shall be 1.5 exams - so the sum of first 50% should be his first exam marks + the 50% of the marks obtained by him in the 2nd or middle or tie breaker exam. And the remaining 50% exam marsk shall be: the 50% of the marks obtain in the 2nd exam + the marks obtained in the 3rd exam. Based on above data, Moeed appeared in 3 exams, and his marks were 20, 65 and 34. So his first 50% marks shall be 20 + 65/2 = 32.5 => 52.5 total marks. And his 2nd 50% marks shall be 65/2 = 32.5 + 34 = 66.5 total marks
I hope I've been able to clear my requiment.
I will appreciate the shortest and simplest possible query to achieve since I've a large data and then I also need to take average of first 50% sum marks divided by 50% of the exams.
Thanks in advance.
regards
Hamza
Edited by: Hamza on May 25, 2011 12:46 AM

TRy this
/* Formatted on 2011/05/24 16:23 (Formatter Plus v4.8.8) */
SELECT student_name, section_name, marks,
       SUM (marks) OVER (PARTITION BY student_name, section_name) sum_marks,
       CASE
          WHEN exam_id = 1
             THEN   marks
                  +   LEAD (marks, 1, 0) OVER (PARTITION BY student_name, section_name ORDER BY exam_id)
                    / 2
          WHEN exam_id = max_id_exam
             THEN   marks
                  +   LAG (marks, 1, 0) OVER (PARTITION BY student_name, section_name ORDER BY exam_id)
                    / 2
          ELSE marks
       END res
  FROM (SELECT student_name, section_name, exam_id, marks,
               MAX (exam_id) OVER (PARTITION BY student_name, section_name)
                                                                  max_id_exam
          FROM eresults)
STUDENT_NAME         SECT      MARKS  SUM_MARKS        RES
MOEED                A            20        119       52.5
MOEED                A            65        119         65
MOEED                A            34        119       66.5
SAM                  A            24        167         26
SAM                  A             4        167          4
SAM                  A            40        167         40
SAM                  A            99        167        119
SARAH                A            30        173         80
SARAH                A           100        173        100
SARAH                A            10        173         10
SARAH                A            33        173         38
11 rows selected.Edited by: Salim Chelabi on 2011-05-24 13:23

Similar Messages

  • How do I create a 1d array that takes a single calculation and insert the result into the first row and then the next calculation the next time the loop passes that point and puts the results in thsecond row and so on until the loop is exited.

    The attached file is work inprogress, with some dummy data sp that I can test it out without having to connect to equipment.
    The second tab is the one that I am having the problem with. the output array from the replace element appears to be starting at the index position of 1 rather than 0 but that is ok it is still show that the new data is placed in incrementing element locations. However the main array that I am trying to build that is suppose to take each new calculation and place it in the next index(row) does not ap
    pear to be working or at least I am not getting any indication on the inidcator.
    Basically what I am attempting to do is is gather some pulses from adevice for a minute, place the results for a calculation, so that it displays then do the same again the next minute, but put these result in the next row and so on until the specifiied time has expired and the loop exits. I need to have all results displayed and keep building the array(display until, the end of the test)Eventually I will have to include a min max section that displays the min and max values calculated, but that should be easy with the min max function.Actually I thought this should have been easy but, I gues I can not see the forest through the trees. Can any one help to slear this up for me.
    Attachments:
    regulation_tester_7_loops.vi ‏244 KB

    I didn't really have time to dig in and understand your program in depth,
    but I have a few tips for you that might things a bit easier:
    - You use local variables excessively which really complicates things. Try
    not to use them and it will make your life easier.
    - If you flowchart the design (very similar to a dataflow diagram, keep in
    mind!) you want to gather data, calculate a value from that data, store the
    calculation in an array, and loop while the time is in a certain range. So
    theres really not much need for a sequence as long as you get rid of the
    local variables (sequences also complicate things)
    - You loop again if timepassed+1 is still less than some constant. Rather
    than messing with locals it seems so much easier to use a shiftregister (if
    absolutely necessary) or in this case base it upon the number of iterations
    of the loop. In this case it looks like "time passed" is the same thing as
    the number of loop iterations, but I didn't check closely. There's an i
    terminal in your whileloop to read for the number of iterations.
    - After having simplified your design by eliminating unnecessary sequence
    and local variables, you should be able to draw out the labview diagram.
    Don't try to use the "insert into array" vis since theres no need. Each
    iteration of your loop calculates a number which goes into the next position
    of the array right? Pass your result outside the loop, and enable indexing
    on the terminal so Labview automatically generates the array for you. If
    your calculation is a function of previous data, then use a shift register
    to keep previous values around.
    I wish you luck. Post again if you have any questions. Without a more
    detailed understanding of your task at hand it's kind of hard to post actual
    code suggestions for you.
    -joey
    "nelsons" wrote in message
    news:[email protected]...
    > how do I create a 1d array that takes a single calculation and insert
    > the result into the first row and then the next calculation the next
    > time the loop passes that point and puts the results in thsecond row
    > and so on until the loop is exited.
    >
    > The attached file is work inprogress, with some dummy data sp that I
    > can test it out without having to connect to equipment.
    > The second tab is the one that I am having the problem with. the
    > output array from the replace element appears to be starting at the
    > index position of 1 rather than 0 but that is ok it is still show that
    > the new data is placed in incrementing element locations. However the
    > main array that I am trying to build that is suppose to take each new
    > calculation and place it in the next index(row) does not appear to be
    > working or at least I am not getting any indication on the inidcator.
    >
    > Basically what I am attempting to do is is gather some pulses from
    > adevice for a minute, place the results for a calculation, so that it
    > displays then do the same again the next minute, but put these result
    > in the next row and so on until the specifiied time has expired and
    > the loop exits. I need to have all results displayed and keep building
    > the array(display until, the end of the test)Eventually I will have to
    > include a min max section that displays the min and max values
    > calculated, but that should be easy with the min max function.Actually
    > I thought this should have been easy but, I gues I can not see the
    > forest through the trees. Can any one help to slear this up for me.

  • How to find accurate number of Rows, and size of all the tables of a Schema

    HI,
    How to find the accurate number of Rows, and size of all the tables of a Schema ????
    Thanks.

    SELECT t.table_name AS "Table Name",
    t.num_rows AS "Rows",
    t.avg_row_len AS "Avg Row Len",
    Trunc((t.blocks * p.value)/1024) AS "Size KB",
    t.last_analyzed AS "Last Analyzed"
    FROM dba_tables t,
    v$parameter p
    WHERE t.owner = Decode(Upper('&1'), 'ALL', t.owner, Upper('&1'))
    AND p.name = 'db_block_size'
    ORDER by 4 desc nulls last;
    ## Gather schema stats
    begin
    dbms_stats.gather_schema_stats(ownname=>'SYSLOG');
    end;
    ## Gather a particular table stats of a schema
    begin
    DBMS_STATS.gather_table_stats(ownname=>'syslog',tabname=>'logs');
    end;
    http://www.oradev.com/create_statistics.jsp
    Hope this will work.
    Regards
    Asif Kabir
    -- Mark the answer as correct/helpful

  • Displaying the Row and Column number in the report

    I am trying to show row and column number in the report (not just web preview). I am using Hyperion Reports Version 7.2.5.168

    use a formula column/row. use RANK function in that. (e.g. Rank([A], asc) will sort the rows based on column A values in ascending order)
    you can use this rank in your heading.
    But frankly this is not so easy. You have to do it in a very intelligent way, so that rank gives you column number/row number any how.
    Have a try and let see if you find a appropriate solution.
    Regards,
    Rahul

  • Getting the row and column number from the caretposition

    Howdy peeps
    Does anyone know how to find out the Line number and column in a JTextPane by using the caret position
    (you know like in text editors where it says 100:4 [line number:character position on row])
    is there a simple way of doing this in a JTextPane?

    im getting a bit confuzzled with this :(
    can someone help me out with a bit more code orientated help? :$
    i have a jTextArea and a JTextField, when i change the caret in the text area i want the JTextField to show the line number and charater position on the row (e.g. 100:4)
    so i assume i need to methods
    e.g.
    getPaneRow
    myint=myPane.getCaretPosition()
    do some wonderful magic code to get the line number
    return line number
    getPaneColumn
    myint=myPane.getCaretPosition()
    do some wonderful magic code to get the column number
    return column number
    is there a magician out there that can give me the magic powder? :)

  • Numbers Export to Excel adds 1 Row and 1 Column to the Freeze Header/Columns.

    Exporting a Numbers file to Excel, that has 1 Freeze Column and 5 Freeze Headers, somehow adds an additional Row & Column when opened in Excel.
    Thoughts?

    I found the answer to this question with help from SAP Support.
    In the Cross-Tab Expert, Customize Style tab, click "_Column Totals on Top_".
    Then, the Excel Data Only report will show the row titles Top-aligned for the row group.

  • TS1702 can not download any program from the App and I can not update any program downloaded in advance .. Seems to me just to wait and remain so throughout the day .. I want a solution to this problem

    can not download any program from the App and I can not update any programdownloaded in advance .. Seems to me just to wait and remain so throughout the day .. I want a solution to this problem 

    Any solution!!!!!!!

  • HT1325 Just brought the MacPro and first time using iTune and Yes I authorized the computer. But for a few purchased songs, only 30 seconds of the song plays and for one song off an album, a pop comes up saying I need to authorized the computer, but it is

    Just brought the MacPro and first time using iTune and Yes I authorized the computer. But for a few purchased songs, only 30 seconds of the song plays and for one song off an album, a pop comes up saying I need to authorized the computer, but I do this and it says it is authorized already. I click on the song to play it and this process repeat (saying it is not authorized, then saying it is already authorized)

    If your country's iTunes Store allows you to redownload purchased tracks, I'd delete your current copies of the dodgy tracks and try redownloading fresh copies. For instructions, see the following document:
    Downloading past purchases from the App Store, iBookstore, and iTunes Store
    Otherwise, I'd report the problem to the iTunes Store.
    Log in to the Store. Click on "Account" in your Quick Links. When you're in your Account information screen, go down to Purchase History and click "See all".
    Find the items that are not playing properly. If you can't see "Report a Problem" next to the items, click the "Report a problem" button. Now click the "Report a Problem" links next to the items.

  • HT1338 When turning on Macbook pro laptop I receive a blank screen for a few seconds, then a folder with a ? is displayed  and remains as if the computer is now Frozen. Mac book  Pro leopard operating system. What can I do to get past the freeze?

    When turning on Macbook pro laptop I receive a blank screen for a few seconds, then a folder with a ? is displayed  and remains as if the computer is now Frozen. Mac book  Pro leopard operating system. What can I do to get past the freeze?

    Could the disk have failed?
    Can you hear it?
    Boot from the install DVD and see what Disk Utility says.

  • Localization in OBIEE 10g(Error "start row is set higher than the row count

    Hi All,
    I m Working on Localization.
    I have used exteranize string and saved excel file and added language column and inserted data en and fr and loaded the file into the database.
    then i have created 2 variables
    one is for weblanguage SELECT 'VALUEOF(NQ_SESSION.WEBLANGUAGE)' FROM DUAL
    second is SELECT SESSION_VARIABLE, TRANSLATION FROM TAB_EXTERNAL WHERE LANGUAGE = 'VALUEOF(NQ_SESSION.LOCALE)' when i click on Test for the second variable it showing error
    "start row is set higher than the row count"
    i have seleted start row =10 and show some 10.then also it is showing same error.
    Please send me the solution ASAP.
    Thanks and Regards
    Kiran Kumar

    Hi Kiran,
    I am working in OBIEE localization. I created two variables and when press test i am getting vaules successfully. But in OBIEE application i am getting columns in english only. It seems there is some problem with values in DUAL table. It contains only 1 column called 'DUMMY' and value as 'X'.
    Please give me complete configuration steps to setup localization OBIEE 10g. Please drop me a mail to [email protected] if u have steps. I will call u if u provide contact number.

  • If there is no data for a specific row, please don't show the row at all.

    Hi,
    If there is no data for a specific row, please don't show the row at all.
    how can this be done??
    Thanks in advance.

    Not clear no data for row?
    Did you try with Pivot table? that should take care of it.
    Let us know updates

  • Problems copying a row and pasting it in the following row

    Hi all,
    In a Numbers table I have 400 rows with data separated each one by a blank row
    row 2 has data
    row 3 is blank
    row 4 has data
    row 5 is blank ... and so on.
    I have prepared a small script to copy row 2 into row 3, row 4 into row 5,... as follows:
    set dName to "Conta"
    set sName to "Movis"
    set tName to "Pruebas"
    set row_ini to 2
    tell application "Numbers" to tell document dName to tell sheet sName to tell table tName
    set selection range to row row_ini
    repeat
    if value of first cell of selection range = 0 then
    exit repeat
    else
    tell application "System Events"
    keystroke "c" using {command down}
    keystroke return
    keystroke "v" using {command down}
    end tell
    tell first cell of the selection range to set rowNum to address of its row
    set selection range to row (rowNum + 1)
    end if
    end repeat
    end tell
    The idea is:
    1 select the initial row (in this case row 2)
    2 check if the value of first cell of the row is cero, then exit the repeat loop
    3 else
    4 copy the entire row, move down a row and paste.
    5 move to the next row
    6 repeat
    The first time I run the script it worked until the row 124 and stopped. I tried again changing the inicial row and it worked only for 7 rows. The third time it erased all the cells with data. I've tried closing both the table and the script but the problems persists: in this case it stops after replacing 5 rows.
    Where am I wrong?
    Thank you in advance
    Ratz

    KOENIG Yvan wrote:
    There is not such a book.
    There is just on short chapter dedicated to iWork in :
    Hanaan Rosenthal & Hamish Sanderson, Learn AppleScript: The Comprehensive
    Guide to Scripting and Automation on Mac OS X, Third Edition, Apress (2010);
    ISBN 978-1-4302-2361-0
    You may find useful infos in my idisk :
    <http://public.me.com/koenigyvan>
    Scan the contents of the folder :
    For_iWork:iWork '09:for_Numbers09.
    I guess the problem is for using the tell application block without telling the process Numbers.
    No, I had to change a lot of things.
    the name of the document was wrong (at least on my machine on which I always use the name extension.
    set selection range … was wrong.
    Yvan KOENIG (VALLAURIS, France) dimanche 20 février 2011 23:02:35
    Thank you.
    Visiting your idisk I realise how much work I must do to become a decent scripter!
    The book you mention looks interesting. I'm going to include it in my bookcase (and read it, of course).
    Ratz

  • How to find out How many rows and coloumn exists in the Excel sheet at run

    hai gurus,
             iam uploading excel to application sever,. when i used gui_upload the data is non-readable. so.. i used alsm_excel_to_int fm .but the problem is user can upload any type of Excel to Application so i need to know the total no of rows and coloum at runtime .is there any possiblity to find out those values.
    Plz help me.
    if any one answered , rewards points,
    Thanks &Regards,
    Venu.T

    Hi kiran,
    i u case better to upload the data first to application server than u can run the bdc program that will helps u
    try these T-code for uploading data from prsentation server to application
    CG3Y and CG3Z this will helps.
    reward is usefull.
    thanks.
    patil.

  • Is there a way to BULK COLLECT with FOR UPDATE and not lock ALL the rows?

    Currently, we fetch a cursor on a few million rows using BULK COLLECT.
    In a FORALL loop, we update the rows.
    What is happening now, is that we run this procedure at the same time, and there is another session running a MERGE statement on the same table, and a DEADLOCK is created between them.
    I'd like to add to the cursor the FOR UPDATE clause, but from what i've read,
    it seems that this will cause ALL the rows in the cursor to become locked.
    This is a problem, as the other session is running MERGE statements on the table every few seconds, and I don't want it to fail with ORA-0054 (resource busy).
    What I would like to know is if there is a way, that only the rows in the
    current bulk will be locked, and all the other rows will be free for updates.
    To reproduce this problem:
    1. Create test table:
    create table TEST_TAB
    ID1 VARCHAR2(20),
    ID2 VARCHAR2(30),
    LAST_MODIFIED DATE
    2. Add rows to test table:
    insert into TEST_TAB (ID1, ID2, LAST_MODIFIED)
    values ('416208000770698', '336015000385349', to_date('15-11-2009 07:14:56', 'dd-mm-yyyy hh24:mi:ss'));
    insert into TEST_TAB (ID1, ID2, LAST_MODIFIED)
    values ('208104922058401', '336015000385349', to_date('15-11-2009 07:11:15', 'dd-mm-yyyy hh24:mi:ss'));
    insert into TEST_TAB (ID1, ID2, LAST_MODIFIED)
    values ('208104000385349', '336015000385349', to_date('15-11-2009 07:15:13', 'dd-mm-yyyy hh24:mi:ss'));
    3. Create test procedure:
    CREATE OR REPLACE PROCEDURE TEST_PROC IS
    TYPE id1_typ is table of TEST_TAB.ID1%TYPE;
    TYPE id2_typ is table of TEST_TAB.ID2%TYPE;
    id1_arr id1_typ;
    id2_arr id2_typ;
    CURSOR My_Crs IS
    SELECT ID1, ID2
    FROM TEST_TAB
    WHERE ID2 = '336015000385349'
    FOR UPDATE;
    BEGIN
    OPEN My_Crs;
    LOOP
    FETCH My_Crs bulk collect
    INTO id1_arr, id2_arr LIMIT 1;
    Forall i in 1 .. id1_arr.COUNT
    UPDATE TEST_TAB
    SET LAST_MODIFIED = SYSDATE
    where ID2 = id2_arr(i)
    and ID1 = id1_arr(i);
    dbms_lock.sleep(15);
    EXIT WHEN My_Crs%NOTFOUND;
    END LOOP;
    CLOSE My_Crs;
    COMMIT;
    EXCEPTION
    WHEN OTHERS THEN
    RAISE_APPLICATION_ERROR(-20000,
    'Test Update ' || SQLCODE || ' ' || SQLERRM);
    END TEST_PROC;
    4. Create another procedure to check if table rows are locked:
    create or replace procedure check_record_locked(p_id in TEST_TAB.ID1%type) is
    cursor c is
    select 'dummy'
    from TEST_TAB
    WHERE ID2 = '336015000385349'
    and ID1 = p_id
    for update nowait;
    e_resource_busy exception;
    pragma exception_init(e_resource_busy, -54);
    begin
    open c;
    close c;
    dbms_output.put_line('Record ' || to_char(p_id) || ' is not locked.');
    rollback;
    exception
    when e_resource_busy then
    dbms_output.put_line('Record ' || to_char(p_id) || ' is locked.');
    end check_record_locked;
    5. in one session, run the procedure TEST_PROC.
    6. While it's running, in another session, run this block:
    begin
    check_record_locked('208104922058401');
    check_record_locked('416208000770698');
    check_record_locked('208104000385349');
    end;
    7. you will see that all records are identified as locked.
    Is there a way that only 1 row will be locked, and the other 2 will be unlocked?
    Thanks,
    Yoni.

    I don't have database access on weekends (look at it as a template)
    suppose you
    create table help_iot
    (bucket number,
    id1    varchar2(20),
    constraint help_iot_pk primary key (bucket,id1)
    organization index;not very sure about the create table syntax above.
    declare
      maximal_bucket number := 10000; -- will update few hundred rows at a time if you must update few million rows
      the_sysdate date := sysdate;
    begin
      truncate table help_iot;
      insert into help_iot
      select ntile(maximal_bucket) over (order by id1) bucket,id1
        from test_tab
       where id2 = '336015000385349';
      for i in 1 .. maximal_bucket
      loop
        select id1,id2,last_modified
          from test_tab
         where id2 = '336015000385349'
           and id1 in (select id1
                         from help_iot
                        where bucket = i
           for update of last_modified;
        update test_tab
           set last_modified = the_sysdate
         where id2 = '336015000385349'
           and id1 in (select id1
                         from help_iot
                        where bucket = i
        commit;
        dbms_lock.sleep(15);
      end loop;
    end;Regards
    Etbin
    introduced the_sysdate if last_modified must be the same for all updated rows
    Edited by: Etbin on 29.11.2009 16:48

  • How to find out How many rows and coloumn exists in the Excel sheet

    hai gurus,
                 present iam uploading data from presentation server to application server.  when i use gui_upload the data is coming non-readable format.
    so i used alsm_excel_to_int fm for that . but the problem is user can give any type of excel so... i need to know how many rows and coloumn s existed in that Excel
    so is there any possiblity to get those values(Total rows and total coloumns).
    plz help me..
    if any one answered , appreciate with reward points,
    thanks&regards,
    Venu.T

    see you have to come into an agreement with other system before starting development..
    Please dont do unnecessary coding for impractical things ..you may solve this but this is not good way of working in eRP packages..
    Al least u can get final list of all Columns and which can be blank or non blank like this
    then u can  do coding for this scenerio
    regards...
    Message was edited by:
            Madan Gopal Sharma

Maybe you are looking for

  • In RG1 ,Unit of measurement is KG,User want to change as MR

    Hi Experts, In RG1,user want to change unit of measurement as KG to MR.Now its showing KG but in billing there is unit of measurement is MR .I have checked material master.I found following: base unit of measurement is KG sales Unit: SM while creatin

  • Edits FROM macbook pro TO NTSC monitor....how?

    Is there a less expensive monitor "bridge" than the Matrox where I can play my edit on an NTSC monitor from my Macbook Pro? Any recommendations would be appreciated! Thanks Mark

  • Csv file as source in OBI

    Hi, I am trying to use a csv file as a data source for OBI Answers where I will be updating the csv file daily and want to see the changes on the front end. These are the steps I am doing: 1) create csv file and save on local machine 2) create ODBC c

  • 11g TP2 and NamedStoredProcedureQuery

    OK, this has me baffled. Documentation on stored procedures and JPA is often unclear, missing, or less relevant (ie., lots of examples for Hibernate XML mapping files, but nothing re: annotations). However TP2 of TopLink now appears to provide some s

  • 10.3.9 Upgrading?

    Hello, I have just got my first mac its a powermac g4 733 40gb, 1.5gb of ram and i love it! But i want to install CS5 on it and other programs but it needs updating. What's the best way about upgrading? Thanks