QUery retrieving based on previous and after rows.. pls help

  CREATE TABLE "POP"."RP06"
   (     "NUM" NUMBER(7,0),
     "SEQ_LINE" NUMBER(7,0),
     "CHMP" VARCHAR2(4000 BYTE)
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,1,'( ');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,2,'ORACLE  IS  GREAT');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,3,'AND ');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,4,'ORACLE  IS  GREAT');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,5,'OR ');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,6,'ORACLE  IS  GREAT');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,7,'AND /*4*/ ');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,8,'ORACLE  IS  GREAT');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,9,'OR ');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,10,'ORACLE  IS  GREAT');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,11,'AND ');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,12,'ORACLE  IS  GREAT');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,13,'OR ');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,14,'ORACLE  IS  GREAT');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,15,'OR ');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,16,'ORACLE  IS  GREAT');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,17,'AND ');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,18,'ORACLE  IS  GREAT');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,19,') ');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,20,'AND /*10*/ ');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,21,'ORACLE  IS  GREAT');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,22,'AND /*11*/ ');
Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,23,'ORACLE  IS  GREAT');after inserting the rows i want to retrieve the rows as follows
1 select the chmp which satisfied the condition if the chmp has previous row is  'AND'* and next row 'OR'* example: chmp with seq_line 4 which has previous 'AND' in seq_line 3 and 'OR' in seq_line 5. so retrieve the 4th seq_line chmp.
( CHMP WITH SEQ_LINE 8,12 ARE other EXAMPLES)
2) select the chmp which satisfied the condition if the chmp has previous row is *'OR' and next row 'AND'*
example: chmp with seq_line 10 which has previous 'OR' in seq_line 9 and 'AND' in seq_line 11. so retrieve the 10th seq_line chmp.
( CHMP WITH SEQ_LINE 6,16 ARE other EXAMPLES)
Kindly help
S

Hi,
You can use the analytic LAG function to get the value from the last row before a given row, and
you can use the analytic LEAD function to get the value from the next row after a given row.
For example:
WITH     got_neighbors     AS
     SELECT  num, seq_line, chmp
     ,     LAG  (chmp) OVER ( PARTITION BY  num
                       ORDER BY      seq_line
                     )     AS prev_chmp
     ,     LEAD (chmp) OVER ( PARTITION BY  num
                       ORDER BY      seq_line
                     )     AS next_chmp
     FROM     rp06
--     WHERE     ...     -- Any filtering goes here
SELECT  num, seq_line, chmp
FROM     got_neighbors
WHERE     prev_chmp     LIKE 'AND %'
AND     next_chmp     LIKE 'OR %'
;I assume that your real table can have many values for num, and that when you talk about the "earlier" or "next" row, you mean a row with the same num. If that's not the case, then remove "PARTITION BY num".
Analytic functions are computed after the WHERE clause is applied, so to use the results of analytic functions in a WHERE clause, compute them first in a sub-query (such as got_neighbors), and then use them in the WHERE clause of a super-query.

Similar Messages

  • How to get the query result of improvement (Before and After ) using sql de

    how to get the query result of improvement (Before and After ) using sql developer.

    Check
    http://www.oracle.com/technetwork/articles/sql/exploring-sql-developer-1637307.html

  • I have a new iphone6+  and have paired it to my 3 cars. When playing music from my iphone, the volume is very low and I have to turn the car volume to max to listen. I had no issues with previous iphone parings. Pls help.

    I have a new iphone6+  and have paired it to my 3 cars. When playing music from my iphone, the volume is very low and I have to turn the car volume to max to listen. I had no issues with previous iphone parings. Pls help.

    Sorry if this is too basic or confusing
    Apparently in iOS 8 there are different volume settings for different applications
    The setting on the home screen does not carry over to Pandora for example and it is different ( or at least appears to be) for the in-car experience.
    So I would try to stream the music when not in the car - see if you can turn the volume up and then try again in the car
    Please let us know what happens
    Thanks

  • How do I delete my old iMessage email and change to my current one, that Im using when I buy apps and so on. The old one wont go away when I turn iMessage on and of again. pls help

    How do I delete my old iMessage email and change to my current one, that Im using when I buy apps and so on. The old one wont go away when I turn iMessage on and of again. pls help
    Anyone had the same?

    How do I delete my old iMessage email and change to my current one, that Im using when I buy apps and so on. The old one wont go away when I turn iMessage on and of again. pls help
    Anyone had the same?

  • Adding rows based on current and next row

    I got some excellent help on multiplying rows based on start and end date in this
    thread, resulting in the query below. It helps me follow Vehicle activity and Vehicle allocation of our vehicles day by day. Now I would like to add another feature to the query, if it is possible.
    The problem is that in our database, only actual tasks are registered, which means that the time when the vehicle is between tasks is not showing. I could of course calculate total available time per vehicle and month, but that would not tell me where the
    vehicles are waiting, when during the day, etc.
    So I would like to insert rows for when the vehicles are standing still, and the logic would be something like this:
    If vehicle number on current row equals vehicle number on the next row and End (date/time) of current row < Start (date/time) of next row, insert row after current row. Set Start=End of current row and End=Start of next row. Set From=To
    of current row and To=To of current row. Set Vehicle activity to "Not active". Finaly copy all other fields from current row.
    Is this possible to achieve in Power Query?
    Brgds,
    Caj
    let
        Source = Sql.Databases("sql10"),
        SLM = Source{[Name="SLM"]}[Data],
        dbo_V_LKPI = SLM{[Schema="dbo",Item="V_LKPI"]}[Data],
        RenamedColumns = Table.RenameColumns(dbo_V_LKPI,{{"ActualDeparture", "Start"}, {"ActualArrival", "End"}}),
         Records = Table.ToRecords(V_LocoKPI),
          DateTime.IsSameDay = (x, y) => Date.Year(x) = Date.Year(y) and Date.Month(x) = Date.Month(y) and Date.Day(x) = Date.Day(y),
          Expand = (x) => List.Generate(
              () => Record.Combine({x, [End=Date.EndOfDay(x[Start])]}),
              (record) => record[Start] <= x[End],
              (record) => let
                  NextStart = Date.StartOfDay(Date.AddDays(record[Start], 1)),
                  NextEnd = Date.EndOfDay(NextStart),
                  ThisEnd = List.Min({NextEnd, x[End]})
              in
                  Record.Combine({record, [Start=NextStart, End=ThisEnd]})),
          Transformed = List.Transform(Records, each if DateTime.IsSameDay([Start], [End]) then {_} else Expand(_)),
          Combined = List.Combine(Transformed),
          Result = Table.FromRecords(Combined)
      in
          Result
    Csten

    Here's some sample code. Again, we use List.Generate to build either a record or a list of records and then use List.Combine to bring the results back together before converting them to a table.
    let
        CombineTwoRows = (x, y) =>
            let
                combine = x[Vehicle] = y[Vehicle] and x[End] < y[Start],
                added = Record.Combine({x, [Start=x[End], End=y[Start], Active=false]}),
                result = if combine then {added, y} else {y}
            in result,
        GenerateStandingRows = (table, combine) =>
            let
                Handle = (x, y) => {x, y},
                buffered = Table.Buffer(table),
                n = Table.RowCount(buffered),
                windows = List.Generate(
                    () => {1, {buffered{0}}},
                    (x) => x{0} <= n,
                    (x) => {x{0} + 1, if x{0} < n then combine(buffered{x{0}-1}, buffered{x{0}}) else {buffered{x{0}}}},
                    (x) => x{1})
            in
                windows,
        InsertInactivity = (table) => Table.FromRecords(List.Combine(GenerateStandingRows(table, CombineTwoRows))),
        TestData = Table.FromRows({
            {1, #datetime(2014, 2, 23, 13, 0, 0), #datetime(2014, 2, 23, 13, 10, 0), true},
            {1, #datetime(2014, 2, 23, 13, 20, 0), #datetime(2014, 2, 23, 13, 30, 0), true},
            {2, #datetime(2014, 2, 23, 13, 20, 0), #datetime(2014, 2, 23, 14, 0, 0), true},
            {2, #datetime(2014, 2, 23, 14, 20, 0), #datetime(2014, 2, 23, 14, 40, 0), true},
            {2, #datetime(2014, 2, 23, 16, 0, 0), #datetime(2014, 2, 23, 17, 0, 0), true},
            {2, #datetime(2014, 2, 24, 2, 0, 0), #datetime(2014, 2, 24, 3, 0, 0), true},
            {3, #datetime(2014, 2, 24, 1, 0, 0), #datetime(2014, 2, 24, 8, 0, 0), true},
            {3, #datetime(2014, 2, 24, 9, 0, 0), #datetime(2014, 2, 24, 10, 0, 0), true}
            }, {"Vehicle", "Start", "End", "Active"})
    in
        InsertInactivity(TestData)

  • I forgot my icloud email and my password pls help me ineed my phone fix

    i forgot my icloud email and password what can i do ? pls help me

    Welcome to the Apple community.
    Unfortunately, you cannot do very much with your phone unless you get assistance from the previous owner, they should either provide you with the password to unlock it or remove their account from the phone entirely remotely through iCloud.com > Find My Phone.

  • SAP MMC, DISPATCH AND DATABASE STOPPED ; PLS HELP

    Hi,
         <b> I was trying to stop JDBC connector in Visual Administrator and after that whn I restarted the server, in the SAP MMC it shows that database and dispatcher is stopped , can anyone guide me how to restart the database and dispatcher again,</b>
    Thanks in advance,
    Sunil K Shetty.
    Bangalore.

    Hi
    Go through these links for more info:
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/97a4f439-0d01-0010-d488-d29b45e2f5ab
    http://help.sap.com/bp_bpmv130/Documentation/Planning/HighAvailability.pdf

  • How to get date and time? pls help~   ~.~

    i tried to get time and date, but dint noe hw to get it.. anyone knows hw to get it? pls help mi ~.~
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.Calendar.*;
    public class Login extends JFrame
    private JFrame mainFrame;
    private JPanel p1;
    private JLabel lblUserId, lblPassword;
    private JTextField tf1, tf2;
    private JButton btnLogin, btnClear;
    public Login()
         mainFrame=new JFrame();
         mainFrame.setTitle("Student Attendance System");
         mainFrame.setSize(400,200);
         mainFrame.setLocation(100,100);
         mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         p1=new JPanel();
         p1.setLayout(new GridLayout(3,2));
         lblUserId=new JLabel("User ID");
         lblPassword=new JLabel("Password");
         tf1=new JTextField(20);
         tf2=new JTextField(20);
         btnLogin=new JButton("Login");
         btnLogin.addActionListener(new ButtonHandler());
         btnClear=new JButton("Clear");
         btnClear.addActionListener(new ButtonHandler());
         p1.add(lblUserId);
         p1.add(tf1);
         p1.add(lblPassword);
         p1.add(tf2);
         p1.add(btnLogin);
         p1.add(btnClear);
         mainFrame.add(p1);
    mainFrame.setVisible(true);
    //inner class event handler
    public class ButtonHandler implements ActionListener
         public void actionPerformed(ActionEvent evt)
              Calendar rightNow = Calendar.getInstance();
              if(evt.getSource()==btnLogin)
                   String login=tf1.getText();
                   String password=tf2.getText();
                   JOptionPane.showMessageDialog(mainFrame, "Student ID "+login+" Login at " + rightNow ,
                   "Response", JOptionPane.PLAIN_MESSAGE);
              if(evt.getSource()==btnClear)
                   tf1.setText("");
                   tf2.setText("");
    public static void main(String []args)
         JFrame.setDefaultLookAndFeelDecorated(true);
         Login l=new Login();
    }

    First off, from http://www.catb.org/~esr/faqs/smart-questions.html
    h1. How To Ask Questions The Smart Way:
    h3. Write in clear, grammatical, correctly-spelled language
    More generally, if you write like a semi-literate boob you will very likely be ignored. So don't use instant-messaging
    shortcuts. Spelling "you" as "u" makes you look like a semi-literate boob to save two entire keystrokes. Worse: writing like
    a l33t script kiddie hax0r is the absolute kiss of death and guarantees you will receive nothing but stony silence (or, at best,
    a heaping helping of scorn and sarcasm) in return.
    Next, use a SimpleDateFormat object. You can use it directly or use a date format string to tell it how you want your date string formatted. The API will give you lots of information on how to use this. Note that you'll have to translate the Calendar object to a date object via the getTime() method:
        class ButtonHandler implements ActionListener
            public void actionPerformed(ActionEvent evt)
                Calendar rightNow = Calendar.getInstance();
                //** use SimpleDateFormat
                SimpleDateFormat dateFormat = new SimpleDateFormat();
                String dateString = dateFormat.format(rightNow.getTime());
                if (evt.getSource() == btnLogin)
                    String login = tf1.getText();
                    String password = tf2.getText();
                    JOptionPane.showMessageDialog(mainFrame, "Student ID " + login
                            + " Login at " + dateString,
                            "Response",
                            JOptionPane.PLAIN_MESSAGE);
                if (evt.getSource() == btnClear)
                    tf1.setText("");
                    tf2.setText("");
        }Finally, when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, either use the "code" button at the top of the forum Message editor or place the tag &#91;code] at the top of your block of code and the tag &#91;/code] at the bottom, like so:
    &#91;code]
      // your code block goes here.
    &#91;/code]

  • HT4972 Can I upgrade my iPad 1 to the ios5, and can I upgrade my snowleapord to mountain lion on my Mac book pro so that I can icloud my iPad, Mac book and iPhone 4s.pls help

    Can I upgrade my iPad 1 to the ios5, and can I upgrade my snowleapord to mountain lion on my Mac book pro so that I can icloud my iPad, Mac book and iPhone 4s.pls help

    Can I upgrade my iPad 1 to the ios5,
    Yes.
    ... and can I upgrade my snowleapord to mountain lion on my Mac book pro
    Maybe.
    Read here for Mountain Lion's system requirements: http://support.apple.com/kb/HT5444

  • My gmail wont link up to my phone, it says invalid password,however i log in on my computer with this gmail acc and password. Pls help

    My gmail acc wont link up to my iphone it says invalid password..although I get in on my computer with that username and password.pls help!!

    double check the passowrd.  Failing that delete the account form the phone and carefully re enter all the information making sure the incoming and outgoing server names are correct as well as user name and password

  • My imac desktop wont boot up there is the logo and the timer pls help

    my imac desktop wont boot up there is the logo and the timer pls help

    What model iMac do you have and what operating system are you running? By Timer are you referring to a progress bar?
    Mac OS X: Gray screen appears during startup - Support - Apple
    Resolve startup issues and perform disk ... - Support - Apple

  • Split a column based on even and odd rows

    Table1
          Table2
     Col1
    Odd
    Even
      A
     A
      B
      B
     C
      D
      C
     E
      F
      D
     G
      H
      E
     I
    NULL
      F
      G
      H
      I
    I am using MS SQL v2005
    I want to split a column into two columns : -
    one column must have all the odd rows data while the other column must have even rows data
    in other words I want the data in Table1 to be displayed as data in Table2. 
    Col, Odd and Even are column names

    In SQL 2005 wont approach like what I suggested do only a single scan of the table?
    A major problem with your solution is that you assume that 1) the values are contiguous 2) they are numeric. Try the below:
    CREATE TABLE #t (id INT NOT NULL IDENTITY(1,1), Col1 CHAR(1))
    INSERT INTO #t VALUES ('A'),('B'), ('C'),('D'), ('E'),('F'), ('G'), ('H'), ('I')
    go
    SELECT MAX(CASE WHEN Col1 % 2 > 0 THEN Col1 END),
    MAX(CASE WHEN Col1 % 2 = 0 THEN Col1 END)
    FROM
    SELECT Col1,ROW_NUMBER() OVER (PARTITION BY (Col1 % 2) ORDER BY Col1) AS Rn
    FROM #t
    )t
    GROUP BY Rn
    go
    ; WITH numbering AS (
        SELECT Col1, row_number() OVER (ORDER BY Col1) AS rowno
        FROM   #t
    ), leading AS (
       SELECT Col1 AS odd, LEAD(Col1) OVER(ORDER BY rowno) AS even, rowno
       FROM   numbering
    SELECT odd, even
    FROM   leading
    WHERE  rowno % 2 = 1
    go
    DROP TABLE #t
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Is it possible to use a content query web part to pull and display rows/items from an Excel spreadsheet saved in a SP library?

    I have an Excel spreadsheet that I want to upload to an SP library. Is it possible to display these items (in a non-excel format, more like an SP list format) in a web part? 

    Have you tried using the Excel web part
    Display Excel content in an Excel Web Access Web Part

  • IPad 2 cannot connect to Wifi before and after updating  PLEASE HELP

    i have been using iOS 5.1.1 till today.. the connection to wifi stopped working.. it slowly faded away and today i woke up and could not connect to My wifi at all, i have decided to update my iPad to iOS 7.0.4 but the problem is there
    what should i doo ??

    It could be a problem with your WiFi router or your iPad.
    If you are having WiFi problems it is necessary to isolate whether the problem is with your network or your iPad. Note: Do NOT consider your network to be blameless if some other devices can connect to it.
    First, test your iPad on some other WiFi networks: a friends, Starbucks, Barnes & Noble, etc.
    If it works well there then the problem is probably with your network. Try restarting your WiFi router by removing power for 30 seconds. If that does not help check for a firmware update for your router. If none exists which corrects the problem consider replacing the router.
    If your iPad does not function well on other networks it possibly has a hardware problem. You could try Settings > General > Reset > Reset Network Settings to see if that corrects the problem. If not, contact Apple Support or visit an Apple store for evaluation. They can provide a replacement if your iPad is bad.
    If you need more help please give the make, model, and version of your WiFi router and how you have it configured.
    See also here: http://www.apple.com/support/ipad/wifi/

  • RMI and Threading: Urgent, pls help!

    Hi everyone,
    I read the previous topics in multithreading but i'm still confused about how RMI works in this case.
    I have a client server application with RMI where client runs some time-consuming executables on the server.
    (i use Process proc = Runtime.getRuntime().exec(cmd...)...)
    Basically I want to make sure that simultaneous requests from different clients execute concurrently, instead of waiting for each other to finish. So my questions are:
    1) When mutiple clients are making remote calls, does RMI map each client request to separate thread and execute them simultaneously (if yes, does it have some limit on number of threads that can be created?);
    Or will I have to take care of creating threads on the server side for each request myself? if the later is the case, how could I go about doing that?
    2) What if all (or some of) the clients are connected from the same VM? How can I ensure that they get executed in different threads, concurrently. Could you pls direct me to ways of implementing it.
    any help is greatly appreciated,
    yulduz

    1) When mutiple clients are making remote calls, does RMI map each client request to separate
    thread and execute them simultaneously (if yes, does it have some limit on number of threads
    that can be created?); Yes, RMI takes care of launching a thread on each remote call. It actually maintains a pool of threads from which, a free thread is assigned a new request. From then on, you have different threads running in server VM (one per each client call).
    Or will I have to take care of creating threads on the server side for each request myself? if the
    later is the case, how could I go about doing that?No, you dont have to create any thread just for the purpose of handling a remote call.
    2) What if all (or some of) the clients are connected from the same VM? How can I ensure that
    they get executed in different threads, concurrently. Could you pls direct me to ways of
    implementing it.You dont have to do anything extra for achieving this. It doesnt matter whether you are running clients in the same VM or different VMs. If you want concurrency on the client side, you have to make remote calls from different threads. The following code outlines the difference between concurrency and non-concurrency in client VM (and NOT server VM).
    class CallerThread extends Thread {
         public void run() {
              remoteRef.callMethod();
    public class Client {
        ... main() {
            // these are not concurrent in client VM bcos the second call happens only after first one       returns
            remoteRef.callMethod1();        
            remoteRef.callMethod2();
            CallerThread t1, t2;
            // these two calls are concurrent on the client side as they're called from two different threads
            t1.start();        
            t2.start();
    }regds,
    CA

Maybe you are looking for

  • Is not working my ipod?

    i go to internet or get some games and is not working.

  • HELP: Error (0xE8000065). I can't connect my iPhone 4 to iTunes!!

    Hey guys. I have an iPhone 4 and i recently wanted to upgrade to iOS 5. When i wanted to do it iTunes told me that it needed to restore my phone then update it, so i backed up my phone and clicked "Update". It went through the proccess, and succesful

  • Error message - "This computer is no longer authorized for apps installed on iphone"

    I started getting this message a couple of weeks ago.  I get it everytime i start itunes and try to sync with my iphone.  The computer is authorized.  After I resubmit my password, itunes tells me that the computer is already authorized and to contin

  • Leave request mail in different languages

    Hello, we are using the leave request functionality for different countries. The report RPTARQEMAIL is scheduled as a daily job, but sends the emails in english only (the schedule user is defined with language 'EN'). We changed the english text of th

  • Message error ORA-00936 when using JDBC adapter

    Hi all, I'm using the folow scenario: RFC --> XI --> JDBC RFC <-- XI <-- JDBC (response) It's a SYNCHRONOUS interface. RFC call without COMMIT WORK: CALL FUNCTION 'Y_TESTE_NEI'     DESTINATION 'RFC_XI' EXPORTING    DATE_FROM       =  v_data_from    D