Use sequence for dynamic conditional grouping

Hi experts,
I have a simple(?) task - I want to number (assign) some groups (increasing group number) based on a condition.
Here an example: create numbered groups based on department number (actual the same grouping)
create table emp as
select * from scott.emp;
CREATE SEQUENCE group_no;
SELECT group_no.NEXTVAL FROM DUAL;
SELECT group_no.CURRVAL FROM DUAL;
/* automatic grouping - NOT WORKING!!!! */
  select ename, deptno, deptno_next, deptno_prev,
   case when (deptno_next > deptno) then group_no.nextval else 1 end grp
    from
      (select ename, deptno,
              lead(deptno) over (order by deptno) deptno_next,
              lag(deptno) over (order by deptno) deptno_prev
      from emp
PROBLEM:
It seems the sequence is increased, even when the condition for a new number is not met!
NAME      DEPTNO                 DEPTNO_NEXT            DEPTNO_PREV            GRP                   
CLARK      10                     10                                            1                     
KING       10                     10                     10                     1                     
MILLER     10                     20                     10                     130                   
JONES      20                     20                     10                     1                     
FORD       20                     20                     20                     1                     
ADAMS      20                     20                     20                     1                     
SMITH      20                     20                     20                     1                     
SCOTT      20                     30                     20                     135                  
WARD       30                     30                     20                     1                     
TURNER     30                     30                     30                     1                     
ALLEN      30                     30                     30                     1                     
JAMES      30                     30                     30                     1                     
BLAKE      30                     30                     30                     1                     
MARTIN     30                                            30                     1instead of else 1 I will use group_no.currval (same group number, when not changing department). I know, I need to cover the previous number as well, but I made it simple, because the problem here seems to be the sequence...
Looking forward to your support :-)
Duik
Edited by: user10939560 on 08.10.2012 07:42
Edited by: user10939560 on 08.10.2012 07:44
Edited by: user10939560 on 08.10.2012 07:45
Edited by: user10939560 on 08.10.2012 07:48
Edited by: user10939560 on 08.10.2012 07:49

Yes, your observation is correct.
You cant use a sequence this way.
May be the below gives you a hint to achieve your goal.
select
ename
,empno
,deptno
,case
when lag(deptno, 1, deptno) over (order by deptno) = deptno
then deptno
else 30*deptno
end mark
from emp
order by deptno
ENAME     EMPNO     DEPTNO     MARK
clark     7782     10     10
miller     7934     10     10
KING     7839     10     10
ford     7902     20     600
scott     7788     20     20
jones     7566     20     20
SMITH     7369     20     20
adams     7876     20     20
WARD     7521     30     900
martin     7654     30     30
...Example with consecutive ordering
select
ename
,empno
,deptno
,sum(grp) over (order by deptno) grp
from (
select
ename
,empno
,deptno
,case
when lag(deptno, 1, deptno) over (order by deptno) = deptno
then 0
else 1
end grp
from emp
order by deptno
ENAME     EMPNO     DEPTNO     GRP
clark     7782     10     0
miller     7934     10     0
KING     7839     10     0
ford     7902     20     1
scott     7788     20     1
jones     7566     20     1
SMITH     7369     20     1
adams     7876     20     1
WARD     7521     30     2
martin     7654     30     2
...Edited by: chris227 on 08.10.2012 08:08
consecutive ordering

Similar Messages

  • How to use i for if condition in a for i in loop?

    Hi friends,
    I have a question on how to use i for IF condition in a loop, in order to get an efficient programming and results. Here is outlined SQL:
    cursor is
    select c1,c2,c3 from table1; -- 100 rows returned.
    open cursor
    loop
    fetch c1,c2,c3 into v1,v2,v3;
    for i in 1..3 loop
    if 'v'||i between 90 and 100 then
    v_grade := 'Excellent';
    elsif 'v'||i between 80 and 89 then
    elsif 'v'||i between 50 and 59 then
    end if;
    end loop;
    close cursor;
    This way, I don't need to use a lot of if..then for hard code v1,v2,v3,.... actually I have more v..
    But Oracle gave an error of this usage of 'if 'v'||i' or 'v'||to_char(i).
    Thanks for any advice in advance!

    user508774 wrote:
    Thanks for comments and advices. But I didn't get your inputs clearly. Are you saying I don't need to use PL/SQL to achieve this?Correct. Ronel and John showed you the basic approaches. SQL is not a mere I/O language for making read and write calls. It is a very capable, flexible and powerful language. One can solve a problem with a few lines of SQL code, that will take 100's of lines of PL/SQL or Java code.
    So do not underestimate what can be done in SQL.
    v_cmd := 'UPDATE parts_categ_counts SET w1='||v1||', w2='||v2||...||v9||' WHERE seq='||vseq||';
    EXECUTE IMMEDIATE v_cmd;This code is also wrong. Besides the fact that there is no need for dynamic SQL, this approach creates a brand new SQL statement each loop iteration.
    SQL is source code. It needs to be parsed (compiled). The end result is an executable program that is called a cursor. This cursor needs to be stored in server memory (the SQL Shared Pool in the SGA).
    The problem with your code is that it is slow and expensive - it generates lots of unique SQL statements that need CPU for parsing and server memory for storage.
    These add up to a very significant performance overhead. That is the wrong approach. The correct approach is the same one that you would use in any other programming language.
    Let's say you need to use Java to process a bunch of CSV files - exact same CSV layout used by each file. A file needs to be read, processed, and a log file created.
    Will you write a Java program that loops through the files, for each file found, write a Java program for processing that file, compile it, then execute it?
    Or would you write a Java program that takes the name of the file as input, and then process that file and writes the log file?
    The 2nd approach provides a program that can process any of those CSV files - one simply needs to pass the filename as an input parameter.
    Your code and approach use the 1st method. Not the 2nd. And that is why it is wrong.
    To create a SQL program with parameters is done by using bind variables. Instead of
    v_cmd := 'UPDATE parts_categ_counts SET w1='||v1||', w2='||v2||...||v9||' WHERE seq='||vseq||';
    The following SQL source code should be created:
    v_cmd := 'UPDATE parts_categ_counts SET w1=:v1, w2=:v2 ..., w9=:v9 WHERE seq= :vseq';
    The tokens with the colon prefix (such as :v1), are bind variables. Think of these as the parameters to the SQL cursor.
    The server parses this SQL into a cursor. You can now execute the same cursor over and over again, using different bind variables. (just like the 2nd approach above that one would use in Java)
    In PL/SQL, this is made even easier as you can code native SQL code with PL/SQL code and use PL/SQL variables in it. The PL/SQL compiler is clever enough to do the SQL parsing, variable binding, and cursor execution for you. So in PL/SQL, you would use:
    UPDATE parts_categ_counts SET w1=v1, w2=v2 ..., w9=v9 WHERE seq= vseq;
    Where v1 and the others are PL/SQL variables.
    That all said - PL/SQL is only used for data crunching, when the processing of data is too complex for the SQL language to deal with. And this is very seldom the case.
    The main reason for using PL/SQL it to provide processing flow control, conditional processing and error handling, for SQL code. As the SQL language does not have these features.

  • Why we cant have access sequence for header condition ?

    hi ,
    i have one query in pricing.
    Can we assign access sequence for header condition ? if yes how ?
    if not why ? please explain

    Hi there,
    It is always possible to have work around to solve issue without refer to OSS to change any programming coding.
    We want to have a freight charge appear on each sales order automatically according to some condition. Most of the time, this freight charge is a flat rate (if it is depend on qty or value, then we're so easy to set it in item level).
    In order to do so, we'll have one assumption. The item line number of sales order is auto running number, like 10, 20 and etc created by system and not manually input.
    Then we create a pricing condition type like other discount or charge in ITEM LEVEL with your selected condition like customer, sales office, country and etc. However, remember to add the sales item line as part of the condition of this pricing condition.
    Update the pricing procedure and create price condition record with say "10" for the sales item line. Since you'll have line number 10 for all sales order as first line (no mater it is a free of charge item or not). This new condition will generate a "freight cost" in the pricing procedure. And it is only apply to first line, therefore, we only get once of this charge for one order.
    Hope this is your case and it works with ours.
    Michael

  • Please provide Solution for Customer Condition Group when defining 2 Chrt's

    Dear Guru's,
    Please provide Solution for Customer Condition Group when defining 2 Charecters or 2 digits.
    I have Completed all possible Combinations like AA,BA,1A,A1,01 to 99 etc.. Total Enteries reach upto 1200+ so I am unble to find no more Combinations( without Special Characters & no chance to increase other than 2 Char/digt)..
    Any body Suggest me any Good Combinations or Proper Alternative....
    Thanks,
    Panduranga

    Hi panduranga
    A Customer Condition Group is maintained in only 2 digits .If you want to go for more than 2 digits then you need to take the help of ABAP'er and you need to go for enhancement
    Regards
    Srinath

  • Changing the Sequence of the Access Sequence for Pricing Condition Type

    Hi Friends,
    We have an access sequence to determine the pricing. We have 8 key combinations for the same.
    Customer/Plant/Material/Batch
    Sales Org/ Dist Ch/ Cust Region/Plant/Material/ Batch
    Price List Type/Currency/Plant/Material/ batch
    Plant/Material/ Batch
    1st 4 is with batch. and 2nd 4 is without batch.  At the time of implementation ie., before 8 years the 1st 4 key combinations were used.  But now based on the business need we are not using the 1st 4 key combination rather we are using the 2nd 4 which is without batch.
    My question is that can we change the access sequence so that while the system fetches the price it need not go through the entire ( 91,02,401 ) records.
    If this is possible then
             Will there by any impact during viewing of past data?

    Hi,
    There are two options.
    1)Change the validity dates for those condition records to earlier date.
    2)Usually the sytem checks from top to bottom.If it finds the record in first table then it will return that value and stop searching.
    As your not required things are on the top,remove the condition records for them using VK12 T.Code.And maintain the records for what condition tables you are required.
    Regards,
    Krishna.

  • Help using Rules for aggregation conditions

    I am trying to utilize the application server rules engine to enforce validation on the XML payload. What I am trying to do is use it for a timesheet application, where after a user enters their hours, they submit and it gets some simple validation using the rules engine and gets returned if not valid according to the ruleset. The application supports multiple rows of hours entered, with each row specifying a unique task/activity worked that period. I have it working as I want using XML facts and RL Functions to determine the rules, but I want to take away the RL functions that need to iterate through each row and replace them with aggregate functions in the rule conditions themselves. Here are the rules I want to enforce:
    <ul>
    <li>An employee must not enter more than x hours of time worked per day, where x is a variable defined in the rules engine. As a constraint the number obviously cannot exceed 24. This rules must span all row entries submitted to sum the amount of hours entered for each day.</li>
    <li>An employee must enter at least y hours worked total each week, where y is a variable defined in the rules engine. Typically this will be defined as 40 hours. It must aggregate all hours entered in all rows for the week to determine how many have been submitted.</li>
    </ul>
    Currently I have 2 RL functions that each return true/false and check the above conditions, but each need to iterate through all rows entered and sum up the hours entered. This is probably satisfactory except my purpose is to show the power of using the rules engine to a client, and if I need to show them I had to develop custom RL code to support this I fear they may shy away from using it.
    Here is the general structure of my XML payload:
    <Timesheet>
      <EmployeeDetails>
        <FirstName>John</FirstName>
        <LastName>Doe</LastName>
        <EmployeeID>12345</EmployeeID>
      </EmployeeDetails>
      <WeeklyHoursEntries>
        <WeeklyHoursEntryRow>
          <TaskDetails>
            <Activity>TaskActivity1</Activity>
            <Description>Some description here</Description>
            <Category>REG</Category>
          </TaskDetails>
          <HoursEntries>
            <Day1>0</Day1>
             <Day2>8</Day1>
             <Day3>8</Day1>
             <Day4>9</Day1>
             <Day5>5</Day1>
             <Day6>10</Day1>
             <Day7>0</Day1>
           </HourEntries>
         </WeeklyHoursEntryRow>
         <WeeklyHoursEntryRow>
           <TaskDetails>
             <Activity>TaskActivity1</Activity>
             <Description>Some description here</Description>
             <Category>OVT</Category>
           </TaskDetails>
           <HoursEntries>
             <Day1>0</Day1>
             <Day2>2</Day1>
             <Day3>8</Day1>
             <Day4>0/Day1>
             <Day5>0</Day1>
             <Day6>10</Day1>
             <Day7>0</Day1>
           </HourEntries>
         </WeeklyHoursEntryRow>
       </WeeklyHoursEntries>
    </Timesheet>

    This is an administrators subforum. You might have more luck in some developers subforum here on OTN?

  • How do u use SDO_RELATE for dynamic theme

    Hi ,
    I have line geometry. For this line geometry I have to create a buffer using SDO_GEOM.SDO_BUFFER and I have to check whether the given point geometry is with in this buffer.
    How can i do it?
    i have used buffer and SDO_RELATE but its giving error as
    "SDO_RELATE can not be used with out Spatial Index". Here my buffer is a dynamic theme.
    Is there any possibility to create index for dynamic theme?
    Thanks and Regards
    Aravindan

    Hello
    We did something familiar in a sence.
    We used an analysis based sdo_NN.
    Also therefor the spatial index is required and used.
    We created a Materialized view containing the sdo_buffered result geometry, based on additional where clauses for the base table..
    We defined a spatial index on the materialized view result table, and an additional view containing the sdo_nn operator to this materialized view result table.
    So when we changed the requirements in which geometry had to be buffered in the first step, we refreshed to materialized view. This caused the de sdo_index being updated. this way the view with the operator was actualized.
    I hope this explained a little bit the way we did this, maybe this can help you out.
    Luc

  • Using -like operator to select recipients for Dynamic Distribution Group

    Dear Scriptor,
    I got few thousand of data and would like to select recipient according to the CustomAttribute1.
    Below is the sample data in my database.
    Name: User1, CustomAttribute1: aa, bb, cc
    Name: User2, CustomAttribute1: aa, bb
    Name: User3, CustomAttribute1: bb, cc, dd
    If I run the script as below,
    New-DynamicDistributionGroup -name "myDyna.bb" -RecipientFilter {(CustomAttribute1 -like 'aa*')}
    The return result is User1 and User2
    When I run the script as below,
    New-DynamicDistributionGroup -name "myDyna.bb" -RecipientFilter {(CustomAttribute1 -like 'bb*')}
    No result returned
    How can I overcome this issue?
    Thanks.

    Below are my sample data in O365.
    Type
    Identity
    UserPrincipalName
    DisplayName
    FirstName
    LastName
    CustomAttribute1
    Mailbox
    77771111
    [email protected]
    7777 #1
    7777
    #1
    a1, a2, a3
    Mailbox
    77772222
    [email protected]
    7777 #2
    7777
    #2
    a1, a2
    Mailbox
    77773333
    [email protected]
    7777 #3
    7777
    #3
    d4, a1
    Mailbox
    77774444
    [email protected]
    7777 #4
    7777
    #4
    a2, e5, f6
    Mailbox
    77775555
    [email protected]
    7777 #5
    7777
    #5
    g7, h8, i9
    Mailbox
    77776666
    [email protected]
    7777 #6
    7777
    #6
    g8, i9, a3
    I would like to create a DynamicDistributionList where CustomAttibute1 contain "a2".
    The expecting result are 77771111, 77772222 and 77774444.
    How can I write the script?
    I am using Windows Azure Active Directory Module for Windows Powershell. I run the $PSVersionTable.PSVersion and it returned me Major=4, Minor=0, Build=-1, and Revision=-1.
    This works for you case:
    New-DynamicDistributionGroup -name "myDyna.bb" -RecipientFilter {CustomAttribute1 -like '*a2*'}
    Do not use parens "()".
    ¯\_(ツ)_/¯

  • Cannot use alias for dynamic column name in SELECT statement

    Hi,
    I want to retrieve values from several tables by using dynamic column & table name as below:
    DATA: tbl_name(30) TYPE c VALUE '/bic/tbi_srcsys',  " staticly initialized for this example
               col_name(30) TYPE c VALUE '/bic/bi_srcsys'.  " staticly initialized for this example
    SELECT (col_name) INTO CORRESPONDING FIELDS OF TABLE it_values FROM (tbl_name).
    The internal table "it_values" does not contain a field named "/bic/bi_srcsys", instead it has another generic field "value" so that the above code can be applied to other tables. I tried to use alias (AS) as below:
    SELECT (col_name) AS value INTO CORRESPONDING FIELDS OF TABLE it_values FROM (tbl_name).
    But this cannot work. I know that there are other ways to solve this problem, such as by using a single field in SELECT .. ENDSELECT and subsequently appending it to the work area and internal table as below:
    SELECT (col_name)  INTO (lv_value) FROM (tbl_name).
      wa_value-value = lv_value.
      APPEND wa_value TO it_values.
    ENDSELECT.
    Just wonder if there is any other more elegant workaround, because I might have several other fields instead of only one?
    Thanks.
    Regards,
    Joon Meng

    Hi Suhas,
    thanks for the quick reply.
    Sorry that I have not well described the structure of the internal table "it_values". This internal table contains several other fields (key, type, value, etc.).
    I guess that the following code
    SELECT (col_name) INTO TABLE it_values FROM (tbl_name).
    works if the internal table only has one field (value) or the field "value" is in the first position, right?
    In this case, I need to fill the "value" field of internal table it_values (ignore the other fields like type, key) with values retrieved from (col_name) of the DDIC table.
    Looking forward to your reply.
    BR,
    Joon Meng

  • Using Java for dynamic web page content

    I've currently got a Perl program that I'd like to convert to Java. It merges two files that are stored on a web server and generates a "dynamic" HTML response.
    For example, if I have the following files on the server:
    File1:
    <Comment1>This stuff</Comment1>
    <Comment2>That stuff</Comment2>
    File2:
    <HTML>
    <Comment1><br><Comment2>
    </HTML>
    When I go to the URL
    www.mysite.com\cgibin\merge.pl?file1&file2
    the Perl program will produce a web page saying:
    This stuff
    That stuff
    The major obstical for the rewrite: NO JSP ALLOWED. It's not allowed by the ISP.
    Now for the questions:
    - Could this be done using Java?
    - How could I initiate the Java app and pass it the parameters? (applet tag, access Java inside Perl, use Java Script somehow)
    - Will an applet tag even work for this since the final page is generated completely from other files?
    Thank you very much for your help.

    If your ISP don't support JSP / Servlets,
    1.use any server side technolgy, something like ASP.
    2.Read the files and transform them as Strings (or StringBuffers).
    3.Pass these Strings as parameters to the applet (if you are forced to use java technology, otherwise you can do it using ASP itself).
    4.Construct the required format (content) in your applet.
    Don't forget that the stuff will be in applet but not a complete web page. The ideal solution is asking your ISP to provide JSP engine.

  • How to use SPEL for Dynamic View Objects?

    Hi Gurus,
    In Benefits Self Service particularly in the Designate Beneficiaries page, we have a requirement to set the row for Self designation as Read Only. What this means for any plan that you're eligible and that requires beneficiary designation, you are not allowed to designate yourself. Unfortunately this is an intended functionality and the only way to achieve our requirement is thru Personalization. I was able to accomplish this successfuly thru the SPEL functionality. However the view object corresponding to each plan that requires beneficiary designation is somewhat dynamic. For example, Plan A corresponds to BeneficiaryPeopleVO1, Plan B corresponds to BeneficiaryPeopleVO2, Plan C corresponds to BeneficiaryPeopleVO3, etc. The Personalization Page only allows me to use the SPEL for only one view object at a time. So if an employee is eligible for 3 plans that require beneficiary designation and my SPEL points to BeneficiaryPeopleVO1, it will only set the Read Only in Plan A. Plan B and Plan C would still allow self designation. Is there a way I could use the SPEL to work for all View Objects?
    Thanks,
    Ronaldo

    jeanluca wrote:
    I've seen things like this in scripting languages, so I was wondering if things like this are possible in java. Here is an not working example:
    Is something like this possible ?AFAIK, it is only possible in a very limited way as noted above and is nearly always not recommended and definitely not necessary. The variable name has little importance, but OTOH the object reference has great importance. Instead learn about arrays, Lists, and Maps.

  • Use the for-each to group the element across in output

    I have the report in XMLP for which we need to design the template to generate the output in excel. we need to group the element across the report. by default the for-each group the element top-down, is there any option to group the elements across. example:
    consider the xml data as
    <?xml version="1.0"?>
    <XXFA_TAL_REP_XMLP>
    <LIST_G_DAY_WE_EXECUTED>
    <G_DAY_WE_EXECUTED>
    <DAY_WE_EXECUTED>18-NOV-09</DAY_WE_EXECUTED>
    </G_DAY_WE_EXECUTED>
    <G_DAY_WE_EXECUTED>
    <DAY_WE_EXECUTED>19-NOV-09</DAY_WE_EXECUTED>
    </G_DAY_WE_EXECUTED>
    </LIST_G_DAY_WE_EXECUTED>
    </XXFA_TAL_REP_XMLP>
    if we group by the above data with group G_DAY_WE_EXECUTED and try to print the data element - DAY_WE_EXECUTED we will get two fields as below
    18-NOV-09 - in excel cell A1
    19-NOV-09 - in excel cell A2
    but we need to have these fields in excel cells - A1 & B1
    Please help me to achieve this.
    ~ Ashish | 630 487 9486

    Can you try with
    for-each@column

  • I want to use Java for dynamic web programming...

    And don't know what to learn, JSP or servlets or both. I'm guessing it would be best to learn both, but I don't want to buy two books. Are there any books that teach both fairly well?

    I don't know how it covers them I am not learning them at the moment.
    Why don't you try searching for JSP and/or Servlets at Amazon.co.uk, Doesn't the JSP and Servlet section of the java.sun.com also have recommended books?, I have just done that search at amazon.co.uk and found these three instantly...the top two have reviews and ratings from other people. There are MANY book websites out there, try searching on this as well.
    JSP, Servlets and MYSQL; Paperback ~ David Harms
    Java Servlet Programming (The Java Series); Paperback ~ Jason Hunter
    Java Servlet and JSP Cookbook; Paperback ~ Bruce W. Perry

  • Default Currency for freight condition type in sales order

    Hi Gurus,
    I have  Freight condition type, maintained condition record with combination of Customer, Incoterms & Material Group.
    In Customer Master Currency is USD or EURO.
    When we create Export sales order, so by default currency should come INR, not USD or EURO for Freight condition type from Customer master.
    How to get this requirement.
    Regards,
    Rakesh

    Hi Rakesh,
    I think you need a revision on condition table and access sequence for frieght condition records from SD >> basic functions >> pricing >> pricing control >> follow standard pricing configs. Actually, you need to add country ( ALAND ) and  destination country ( LLAND ) fields to your table and access sequence for export sales.
    After those configs,  you can create records in USD or EURO for domestic sales and create records INR currency for export processes.
    I hope you can neet your requirement by using this way.
    Regards,

  • Condition Group Routines

    Hello,
    I was asked by my functional analyst to implement the ABAP code for the following scenario:
    A header pricing condition type's amount, say ZHDR, needs to be populated by the largest amount found in certain item pricing condition type (say all ZDTL conds) on all items within a sales order.
    Is the solution for this condition group routines?
    Thanks,
    John

    Hi,
    This depends on your requirement. If you have defined the condition at the material pricing group level, then no need. The routine is used only if you want the condition to be read differently for each item (with the scale base value being total of all the items).
    You can find some help in the below link:
    http://help.sap.com/saphelp_erp2005/helpdata/en/de/7a8534c960a134e10000009b38f83b/frameset.htm
    There are some helpful SAP Notes if you need further clarifications:
    39034     Group condition routine
    854978     Function of cumulated scale base values (in SD)
    109708     Scale processing for group conditions
    Hope this helps.
    Regards
    Nikhilesh

Maybe you are looking for