Subtotal less than or equal to a max value

Hi,
I have the following values in a table:
drop table t;
create table t (key number, ind varchar2(1), num number);
insert into t (key,ind,num) values (1,'Y',2);
insert into t (key,ind,num) values (2,'Y',10);
insert into t (key,ind,num) values (3,'Y',12);
insert into t (key,ind,num) values (4,'Y',9);
insert into t (key,ind,num) values (5,'Y',1);
insert into t (key,ind,num) values (6,'Y',1);
insert into t (key,ind,num) values (7,'Y',8);
insert into t (key,ind,num) values (8,'Y',1);
insert into t (key,ind,num) values (9,'N',11);
insert into t (key,ind,num) values (10,'N',6);
commit;The values are:
test@ORA92> select * from t order by key;
       KEY I        NUM
         1 Y          2
         2 Y         10
         3 Y         12
         4 Y          9
         5 Y          1
         6 Y          1
         7 Y          8
         8 Y          1
         9 N         11
        10 N          6
10 rows selected.
test@ORA92>For all rows with ind = "Y", I want to add "num" as long as the subtotal is less than or equal to a max value (15). For all rows with ind = "N", I want the sum of "num".
It should be as follows:
       KEY I        NUM
         1 Y          2    <- consider this, as subtotal is now 2 which is < 15
         2 Y         10   <- consider this, as subtotal is now 12 which is < 15
         3 Y         12   <- ignore this, as subtotal would be 24 which is > 15; keep running total as 12.
         4 Y          9   <- ignore this, as running total would be (12+9=) 21, which is > 15; keep running total as 12
         5 Y          1   <- consider this, as running total is now (12+1=) 13, which is <= 15
         6 Y          1   <- consider this, as running total is now (13+1=) 14 which is <= 15
         7 Y          8   <- ignore this, as running total would be (14+8=) 22, which is > 15; keep running total as 14
         8 Y          1   <- consider this, as running total is now (14+1=) 15, which is <= 15
         9 N         11 <- add this to subtotal for ind = "N"; subtotal = 11
        10 N          6 <- add this to subtotal for ind = "N"; subtotal = (11+6=) 17
Return "ac" (subtotal for ind = "Y") = 15 - the one we got at key = 8
Return "dc" (subtotal for ind = "N") = 17 - the one we got at key = 10I have a pl/sql block that does the same:
test@ORA92>
test@ORA92> --
test@ORA92> -- To derive "ac" value:
test@ORA92> --   Loop through t, and for ind = "Y", keep on adding "num" as long as
test@ORA92> --   the subtotal is less than "maxnum". Disregard values of "num"
test@ORA92> --   that would make the subtotal greater than "maxnum".
test@ORA92> -- To derive "dc" value:
test@ORA92> --   Sum of "num" values for ind = "N"
test@ORA92>
test@ORA92>
test@ORA92> declare
  2    maxnum   number := 15;
  3    ac       number := 0;
  4    dc       number := 0;
  5    prev     number := 0;
  6  begin
  7    FOR i IN (SELECT ind, num
  8                FROM t
  9              ORDER BY key)
10    LOOP
11       IF (i.ind = 'Y') THEN
12          ac := i.num + prev;
13          IF (ac > maxnum) THEN
14             ac := prev;
15          ELSE
16             prev := ac;
17          END IF;
18       ELSIF (i.ind = 'N') THEN
19          dc := i.num + dc;
20       END IF;
21    END LOOP;
22    dbms_output.put_line('maxnum  = '||maxnum);
23    dbms_output.put_line('ac      = '||ac);
24    dbms_output.put_line('dc      = '||dc);
25    dbms_output.put_line('prev    = '||prev);
26  end;
27  /
maxnum  = 15
ac      = 15
dc      = 17
prev    = 15
PL/SQL procedure successfully completed.
test@ORA92>
test@ORA92>Is there a way to do this processing in SQL instead ? The database version is 9i R2 (9.2.0.8.0).
Thanks and appreciate any help and/or pointers.
pratz...

Rob, as it was mentioned here it can be done by Hierarichal Queries, disregarding a lot of drawbacks of such a way.
SQL> with temp as (select t1.*,
  2                 (select case  when t1.ind = 'Y' and sum(num) > 15
  3                               then  null
  4                               else  sum(num)
  5                         end
  6                    from t t2
  7                  connect by level <= t1.lvl
  8                         and t2.key =
  9                             regexp_substr(t1.path, '[^/]+', 1, t1.lvl - level + 1)
10                   start with t2.key = t1.key) summa
11            from (select t.*,
12                         level lvl,
13                         sys_connect_by_path(key, '/') path,
14                         sys_connect_by_path(rn, '/') path_rn
15                    from (select t.*,
16                                 lpad(row_number() over(partition by ind order by key),2,'0') rn
17                            from t) t
18                  connect by prior key < key
19                         and prior ind = ind
20                   start with (key, ind) in
21                              (select min(key), ind from t group by ind)) t1)
22  --
23        select ind, avg(summa) keep(dense_rank first order by path_rn) max_summ
24          from (select temp.*,
25                       decode(instr(lead(path_rn) over(partition by ind order by path_rn), path_rn),1, 0, 1) flag
26                  from temp
27                 where summa is not null)
28         where flag = 1
29         group by ind
30  /
IND   MAX_SUMM
N           17
Y           15
SQL>

Similar Messages

  • Less than or equal to broken?

    Download the vi and check out the internals, as they will explain exactly what I'm trying to do.
    Briefly, I am writing a deMUX for a signal that has digital components
    of 0.25V, 0.5V, 1V, 2V, and 4V. The max signal being 7.75V and the min
    being 0V. For example, if the input is 0.25V, the 5 bit digital output
    will be 00001; if the input is 0.50V, the digital output will be 00010;
    if the input is 0.75, then the digital output will be 00011; ... and if
    the input is 7.75, then the digital output will be 11111.
    In order to make the system realistic I have added tolerances to the
    search. So, the tolerance I picked is 0.1V (which is well less than the
    required 1/2 of the smallest voltage increment of 0.25V, which is
    0.125V). Thus, any of the 32 possible voltages +/- 0.1V should decode
    correctly according to the <= circuit I have set up toward the
    bottom of my while loop in the attached vi. It does work for most, but
    it does not work for 1.1V, 2.1V, and 3.1V... and possibly some others.
    For these listed numbers, the comparison acts as a less than, rather
    than a less than or equal to.
    Let me know if you need more information.
    Cheers,
    Joe
    Attachments:
    Full.vi ‏39 KB

    To solve your problem, all you need is to "quantize" the number to your smallest step (0.25 in your case) and convert it to an integer.
    The attached code will probably produce the output you want.
    Message Edited by altenbach on 12-21-2005 09:28 AM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    FullMOD.vi ‏16 KB
    FullMOD.png ‏3 KB

  • The initial heap size must be less than or equal to the maximum heap size.

    All,
    Please help!!
    I have tested my Application Client Project in WSAD on my pc and it works fine.
    I have 1gb RAM on my pc. When I deploy the same app on another xp pc(same as mine but 512mb RAM) I get a heap size error. Here is the exact error:
    Incompatible initial and maximum heap sizes specified:
    initial size: 268435456 bytes, maximum heap size: 267380736 bytes
    The initial heap size must be less than or equal to the maximum heap size.
    The default initial and maximum heap sizes are 4194304 and 267380736 bytes.
    Usage: java [-options] class [args...]
    (to execute a class)
    or java -jar [-options] jarfile [args...]
    (to execute a jar file)
    where options include:
    -cp -classpath <directories and zip/jar files separated by ;>
    set search path for application classes and resources
    -D<name>=<value>
    set a system property
    -verbose[:class|gc|jni]
    enable verbose output
    -version print product version
    -showversion print product version and continue
    -? -help print this help message
    -X print help on non-standard options
    Could not create the Java virtual machine.
    Press any key to continue . . .
    Here is the batch file that runs my app:
    @echo off
    SET appClientEar=C:\corp\apps\mts\jars\MTSClientEAR.ear
    set JVM_ARGS=-Xms256M -Xmx256M
    set CLIENT_PROPS=C:\corp\apps\mts\jars\medicalclient.properties
    set APP_ARGS=
    call C:\bnsf\IBM\WebSphere\AppClient\bin\launchClientBNSF.bat "%JVM_ARGS%" %appClientEar% "-CCpropfile=%CLIENT_PROPS%" %APP_ARGS%
    @pause
    I have changed the value of Xms and Xmx of JVM_ARGS to different size but I sitll get error. Anyone knows what the problem is. Thanks..

    Don't know why, but the "maximum heap size: 267380736 bytes" value is just slightly less than 256*1024*1024, wheras the reported initial size is equal to that.
    Try setting the initial value to 255MB.

  • Less than or Equal to Variable on Calquarter is not working in Webi

    Hi Guru,
    I have Variable on Calquarter which brings the query result for all the cal quarters which are LESS THAN or EQUAL to entered one.
    But, when we execute the Webi Report of this Bex Query, we get data for all the Calquarters in the infoprovider.
    Its a "Single Value, Optional" variable with operand as LE.
    Thanks in advance,
    Deepak Jain

    In BEx side, calquarter is mapped as key or text?
    Maybe it is mapped as text and the variable in BO doesn't work correctly.
    Regards.

  • Unable to create the Variable icon which shows Less than or equal to

    Hi Experts,
    when we create a variable normally will get a icon of the variable which say equal to symbol on the varaible icon. Hope everybody know that.
    Now how can we change that variable icon to less than or equal.
    Please can you provide me that information.
    Thanks alot !

    hi,
    when you are trying to restrict the char select range values instead of variable.
    then select the operator type (less than, greate than etc) and in place of value select variable and then give the variable name.
    regards,
    Arvind.
    Edited by: Arvind Tekra on Jun 15, 2011 4:57 PM

  • Synatax Query - Less than or Equal to

    Running on Linux, Apache, MySQL, PHP
    I have an issue with a date query - possibly created by the
    MySQL format YYYY-MM-DD
    I want to create a recordset where activities are less than
    or equal to today's date.
    I've managed most of it but the result seems only to show
    less than and not less than and equal to.
    This is the part of the query that is in question:
    CONTNOTES.ACTDATE<='coldatetil'
    I have tried =< without success
    Any ideas?

    That's pretty much what the core of mine is:
    SELECT CONTNOTES.ACTDATE, CONTACTS.CONTACTID, CONTACTS.LOGO,
    CONTACTS.COMPANY, CONTACTS.FULLNAME, CONTNOTES.NOTEUSER,
    CONTNOTES.STAGE, CONTNOTES.TYPE, CONTNOTES.NOTE, CONTNOTES.VALUE,
    CONTNOTES.COMPLETED
    FROM CONTACTS INNER JOIN CONTNOTES ON CONTACTS.CONTACTID =
    CONTNOTES.NOTESCONTACTID
    WHERE CONTNOTES.NOTEUSER='coluser' AND
    (CONTNOTES.ACTDATE<='coldatetil' OR CONTNOTES.ACTDATE is null)
    AND CONTNOTES.TYPE <>'10 note' AND CONTNOTES.COMPLETED=False
    ORDER BY CONTNOTES.ACTDATE DESC
    And yet it still only seems to return the less than part of
    <=

  • Problem with the operator less than or equal to in a weby query

    Hi all.
    The universe is a OLAP Universe
    When i created a query in webi and put the month in the filter area with the operator less than or equal to like this.
    Month (less than or equal to) 2010.01 for example. The all result brings also the all values like 2010.02, 2010.03, etc
    What is the problem and how can fix that ?
    Thanks

    Looks like you are using a less than or equal to with a Sting data type.
    I think you should change to your filter to Year <= 2010 And Month <= 1. Hope you have a month and year object in you BeX.
    Anil

  • Camel Query : Calender list : Get Items agains given date that must be greater than and eqaul to start date and greater less than or equal to end date ?

    Camel Query : Calender list : Get Items agains given date that must be greater than and eqaul to start date and greater less than or equal to end date ?
    A Snap of Employee holiday list
    Case : Anne juul Sondergaar is on leave from 05-06-2014 to 07-06-2014
    I need a query to check wheither Anne juul is on leave at 06-06-2014 ????
    I am using this query that return nothing
    SPQueryquery =
    newSPQuery();
                                query.Query =
    @"<Where>
    <And>
    <And>
    <Leq>
    <FieldRef Name='Til' />
    <Value Type='DateTime'>"
    + WorkingStartDate.ToString("yyyy-MM-dd")
    + @"</Value>
    </Leq>
    <Geq>
    <FieldRef Name='Fra' />
    <Value Type='DateTime'>"
    + WorkingStartDate.ToString("yyyy-MM-dd")
    + @"</Value>
    </Geq>
    </And>
    <Eq>
    <FieldRef Name='Medarbejdere' />
    <Value Type='Lookup'>"
    + EmployeeName.Trim() +
    @"</Value>
    </Eq>
    </And>
    </Where>"
                                query.ViewFields =
    " <FieldRef Name='ID' />";
    Ahsan Ranjha

    Hello,
    Download CAML query builder from below location and use it to build your query:
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/f7b36ebc-6142-404a-8b04-9c87de272871/where-can-i-download-the-u2u-caml-query-builder-for-sharepoint-2010may-i-know-the-exact-link?forum=sharepointgeneralprevious
    Hemendra:Yesterday is just a memory,Tomorrow we may never see
    Please remember to mark the replies as answers if they help and unmark them if they provide no help

  • DS/SAP - DATAFLOW - This is less than(or equal to) the virtual memory 1609564160 bytes available for caches.

    Hello,
    my project is displaying the following error, when you generate a TXT record with 3 million.
    I have a project that when executato DS goes to a Z table in SAP selects every record in this table (+ 3 million), and on DS it generates a TXT file separated by semicolons (;). But the DS is not getting serar this file with more than 3 million record, the DS displays the following error:
    (12.2) 02-21-14 10:06:27 (2996:2952) PRINTFN: INFO - Definicao da $G_FF_Diretorio_OUT = C:\DS_Neogrid\Upload\QAS
    (12.2) 02-21-14 10:06:27 (2996:2952) PRINTFN: INFO - Definicao da $G_FF_Diretorio_OUT = C:\DS_Neogrid\UpLoad\QAS
    (12.2) 02-21-14 10:06:27 (5928:3040) DATAFLOW: Process to execute data flow <DF_TransfArq_035> is started.
    (12.2) 02-21-14 10:06:27 (5928:3040) DATAFLOW: Data flow <DF_TransfArq_035> is started.
    (12.2) 02-21-14 10:06:27 (5928:3040) DATAFLOW: Cache statistics determined that data flow <DF_TransfArq_035> uses <0> caches with a total size of <0> bytes. This is less
      than(or equal to) the virtual memory <1609564160> bytes available for caches. Statistics is switching the cache type to IN
      MEMORY.
    (12.2) 02-21-14 10:06:27 (5928:3040) DATAFLOW: Data flow <DF_TransfArq_035> using IN MEMORY Cache.
    Can anyone help me...
    Thank you.
    at.
    Wagner

    Error of the border of error of job.
    (12.2) 03-06-14 08:41:54 (W) (1392:6492) SYS-170114: /JB_35_Neogrid_DimDemPrimaria/DF_TransfArq_035
      Warning: Your system is running low on process virtual memory space. Available virtual memory is <22> megabytes.
    (12.2) 03-06-14 08:41:55 (W) (1392:6492) SYS-170114: /JB_35_Neogrid_DimDemPrimaria/DF_TransfArq_035
      Warning: Your system is running low on process virtual memory space. Available virtual memory is <22> megabytes.
    (12.2) 03-06-14 08:41:56 (W) (1392:6492) SYS-170114: /JB_35_Neogrid_DimDemPrimaria/DF_TransfArq_035
      Warning: Your system is running low on process virtual memory space. Available virtual memory is <22> megabytes.
    (12.2) 03-06-14 08:41:57 (W) (1392:6492) SYS-170114: /JB_35_Neogrid_DimDemPrimaria/DF_TransfArq_035
      Warning: Your system is running low on process virtual memory space. Available virtual memory is <22> megabytes.
    (12.2) 03-06-14 08:41:58 (W) (1392:6492) SYS-170114: /JB_35_Neogrid_DimDemPrimaria/DF_TransfArq_035
      Warning: Your system is running low on process virtual memory space. Available virtual memory is <22> megabytes.
    Characteristics of our server.
    It will be necessary to increase the virtual memory virtual?
    at.
    Wagner

  • Condition for excluding Sales value less than or equal to 0

    Hello Experts,
    I have to create condition in the query designer to exclude Sales Value <=0, and that should be applied to all the column values and result values when we put active.
    Can anyone help ?
    Thanks in advance,
    Venky
    Duplicate Post
    Condition for excluding Sales value less than or equal to 0
    Edited by: Arun Varadarajan on Apr 13, 2010 8:57 PM

    Hello Naveen,
    Thanks for quick reply. I have created condition greater than zero and executed report, i can able to eliminate rows with sales value <=0, but we have other columns in the report say Quantity, Backlog... when we run the report without condition the values which showed are same when we put it in active aslo.
    After eliminating few rows which having some quantity value, that value should be deducted from the result of the quantity. I tried with applying apply to results opton, then also there is no change in the result value of the quantity.
    Our requirement is to apply condition to eliminate rows which are sales value <=0 and same the result values of the columns should effect.
    Is it possible in anyway, if yes please specify solution.
    Thanks,
    Venky

  • How to use not less than or equal to in condition

    I written a querry based on the below condition in sql querry
    b.key <= a.key
    Based on this it will return records.
    I need remaining records that not satisfy the above condition.
    That means not less than or equal to records...

    937506 wrote:
    I written a querry based on the below condition in sql querry
    b.key <= a.key
    Based on this it will return records.
    I need remaining records that not satisfy the above condition.
    That means not less than or equal to records...you mean
    b.key > a.key?

  • Are there symbols for greater than or equal, less than or equal?

    Hi,
    I have occasional references that mention things like "Adjust the Kd pot until the voltage is <= 2.0 v" or "Turn the screw until the clearance is => .005 inch."
    <= means less than or equal to.
    => means greater than or equal to.
    I looked the the installed Character Sets PDF file and could not find these symbols. Is there an ASCII or ANSI code or a special font that has these items as a single symbol?
    Yours,
    Michael F
    ========

    If you're using a FM8 or greater than you should use the Unicode values for these symbols:
    <= is /u2264
    >= is /u2265
    However, the font that you are using must contain the glyphs in these code points.
    With the ANSI Symbol and Dingbats sets, these symbols were coded at:
    0163 (\xa3) (ctrl-q #) less than or equal to
    0179 (\xb3) (ctrl-q 3) greater than or equal to

  • Date less than or equal to 60 days from sysdate

    Hi there!
    I have a doubt about an SQL query, which I don't have any idea on how to proceed.
    I need the SQL to bring data only when 'e.dt_vencimento' is less than or equal to 60 days from sysdate.
    Below you can see my query, and the line I stuck is the #24.
    Thank you already,
    Marcelo Melo
    SELECT b.nr_contrato,
      a.NM_PAGADOR,
      a.NR_SEQ_LOTE,
      a.dt_referencia,
      a.DT_VENCIMENTO,
      a.VL_PRE_ESTABELECIDO,
      a.VL_COPARTICIPACAO,
      a.VL_OUTROS,
      a.VL_TITULO,
      e.dt_liquidacao,
      e.nr_titulo
    FROM pls_mensalidade_wcp_v a,
      pls_contrato b,
      PLS_CONTRATO_PLANO c,
      PLS_CONTRATO_PAGADOR d,
      titulo_receber e
    WHERE b.nr_sequencia  = c.nr_seq_contrato
    AND d.nr_seq_contrato = b.nr_sequencia
    AND a.nr_seq_pagador  = d.nr_sequencia
    AND a.nr_titulo       = e.nr_titulo
    AND c.NR_SEQ_PLANO IN (17, 18, 25, 47, 50, 51,54,56,57,58)
    AND d.cd_pessoa_fisica IS NOT NULL
    and e.dt_liquidacao is null
    --and e.dt_vencimento ***here I intend to write the condition***
    AND a.dt_referencia     =:dt_referencia
    ORDER BY 2

    It sounds like you want
    and e.dt_vencimento <= (sysdate - 60)
    That assumes that you really mean "60 days before sysdate" when you say "from sysdate".  You might intend to say "60 days after sysdate".  And you might mean trunc(sysdate) rather than sysdate in order to ignore the time component.

  • Decode Statement Less Than or Equal To

    Hi,
    I want to use a decode statment to search a range of accounts, and return a text statement:
    Here is my original statement it works but I need a range:
    DECODE(GL Standard Balances DX."Account 1",'00040501','OHIP Revenue(40501/40502)','00040502','OHIP Revenue(40501/40502)')
    What I want to do is, if the GL Standard Balances DX."Account 1" is greater than '00040501' and less than '00040502' then return the text "OHIP Revenue (40501/40502)".
    Any help would be great.

    Hi,
    Best for you is to use case rather than decode
    case when GL Standard Balances DX."Account 1" between '00040501' and '00040502'
    then 'OHIP Revenue(40501/40502)'
    else ''
    end;
    Tamir

  • Using less than or equal and greater or equal relational operators in BIP

    Hi,
    I have a query wherein I am using a relational operator '<=' and '>='. When I run my sql query in TOAD in works fine but when I put it in BIP using a Data Template, it says "Data Template XML is invalid". When I try to remove the '<' and the '>' signs the query is working but of course the output is incorrect.
    My question is, what's the syntax in BIP Data Template for operators '<=' and '>='.
    Will really appreciate anyone's help.
    Thanks :)
    Ann

    Yeah this was the first thing I tried when I began to suspect my soundcard was causing the freezing and screeching while playing MTW 2 but as you can see here, I managed to get my card on it's own IRQ but the problem persists as ever.
    [img"]http://img82.imageshack.us/img82/8908/wl6.gif[/img]
    Truly extrordinary.

Maybe you are looking for

  • Mixing 4:3 and 16:9 in one dvd project

    I have video that is in the 4:3 style and a 16:9 slideshow - is there anyway I can combine them on one iDvd Project. (It looks like everything should be one way or the other.

  • ODBC - SQLException

    Hi, I'm having a problem with an ODBC connection that tells: "SQLException:[Microsoft][ODBC Driver Manager] Error in function sequence". I do'nt have idea on what can be the mistake. Here is my code: public class LeerFila extends JFrame { MSConnectio

  • 5800 v50 software update problem

    I just updated my phone to this v50 firmware as it hadn't been done in a year or so and i wanted the newer features....it installed ok according to Ovi suite but now the phone is un-useable due to the screen scolling diagonally and being offset by 10

  • MacPro6,1 - Failing to wake from 'sleep'

    I have a MacPro6,1 which keeps failing to wake from 'sleep' is there a solution to stop this or is it a fault? considering I've only had it a few months i'm not impressed!

  • Like to Create PDF that includes portrait & Landscape pages

    I have a HP Scanner which allows me to create PDF documents. I have these very important documents about "My Learning Disability" the issue is that some pages are printed in Portrait and others are in Landscape. I really need to know if its possible