Analytic Windowing - Positive/Negative Range

Hi,
In analytic functions, we can say
RANGE BETWEEN  x  PRECEDING
      AND      y  PRECEDINGwhere x and y are expressions (not necessarily literals), as long as x and do not evaluate to negative numbers. If we know when we write the code that x and/or y is negative, ithen we can use FOLLOWING instead of PRECEDING, and if we don't know until run-time whether x or y will be negative, we can compute the function both ways, and use a CASE expression to choose one or the other. I was just wondering if there was a more elegant way do RANGE BETWEEN when x and/or y might be negative.
Here's a specific example:
Yesterday, there was a question {message:id=10868410} about how to find how many children (immediate children, not descendants 2 or more levels down) each node in a tree has. OP specifically asked for an analytic solution. I don't believe analytic functions are the best solution to this particular problem, but I've been trying to find an analytic solution anyway, just for curiosity.
So, again, the problem is, using the standard scott.emp table (where empno is a unique postive number, and NULL mgr indicates no parent), is there a purely analytic query that can get the same results as
SELECT       ename           -- Query 1: no analytics
,       empno
,       mgr
          SELECT  COUNT (*)
          FROM     scott.emp
          WHERE     mgr     = m.empno
       )          AS children
FROM       scott.emp  m
ORDER BY  mgr          NULLS FIRST
,            empno
;Output:
ENAME           EMPNO        MGR   CHILDREN
KING             7839                     3
SCOTT            7788       7566          1
FORD             7902       7566          1
ALLEN            7499       7698          0
WARD             7521       7698          0
MARTIN           7654       7698          0
TURNER           7844       7698          0
JAMES            7900       7698          0
MILLER           7934       7782          0
ADAMS            7876       7788          0
JONES            7566       7839          2
BLAKE            7698       7839          5
CLARK            7782       7839          1
SMITH            7369       7902          0I would love to do something like this:
SELECT       ename          -- Query 2: ***** WRONG ! *****  raises ORA-01428
,       empno
,       mgr
,       COUNT (*) OVER ( ORDER BY         mgr
                  RANGE BETWEEN  empno - NVL (mgr, 0)  PRECEDING
                        AND       empno - NVL (mgr, 0)  PRECEDING
                )     AS children
FROM      scott.emp
ORDER BY  mgr, empno
;but negative RANGEs aren't allowed, so the best I could do using this approach was
SELECT       ename          -- Query 3
,       empno
,       mgr
,       CASE
           WHEN empno < mgr
           THEN COUNT (*) OVER ( ORDER BY      NVL (mgr, 0)
                            RANGE BETWEEN ABS (empno - NVL (mgr, 0))  PRECEDING
                                     AND     ABS (empno - NVL (mgr, 0))  PRECEDING
           ELSE COUNT (*) OVER ( ORDER BY         NVL (mgr, 0)
                             RANGE BETWEEN ABS (empno - NVL (mgr, 0))  FOLLOWING
                                  AND       ABS (empno - NVL (mgr, 0))  FOLLOWING
          END     AS children
FROM      scott.emp
ORDER BY  NVL (mgr, 0), empno
;Is there a more efficient and/or more elegant way to handle possibly negative ranges?
Can you think of other analytic solutions to this particular problem?
OP in {message:id=10868481} had one idea, that involved a CONNECT BY query.
I posted a soltuion using the aggregate COUNT function. Any query that uses an aggregate function (such as COUNT) which has an analytic twin can be re-written to use the analytic twin, and SELECT DISTINCT instead of GROUP BY.
Any other ideas?
I'm interested in any version of Oracle.
Thanks.

Hi,
I don't have a database at the moment but to solve the preceding or folowing problem, I think you can use one of the two always, and just sort ascending or descending as applicable.
So some thing like: (not tested)
SELECT       ename          -- Query 3
,       empno
,       mgr
,      COUNT (*) OVER ( ORDER BY      case when empno < mgr then NVL (mgr, 0) else -NVL (mgr, 0) end
                            RANGE BETWEEN ABS (empno - NVL (mgr, 0))  PRECEDING
                                     AND     ABS (empno - NVL (mgr, 0))  PRECEDING
     AS children
FROM      scott.emp
ORDER BY  NVL (mgr, 0), empno
;Regards,
Peter

Similar Messages

  • Window Position & Prefs "Gone"

    Every time I start up or restart, any window position, size, view etc info is gone, and I get a view very different than what I had set. I have tried to delete the Finder plist, but it did not help. I did notice something extremely weird as well.
    I noticed that the Finder plist is actually deleting itself about every 30 - 60 seconds when I open the ~user Library prefs, and cannot find anything that might be causing this. Repairing permissions, running utilities such as DiskWarrior etc have not helped. This condition actually exists identically on two Macs I am using. The only thing in common is that I ran an updater for Missing Sync for BlackBerry from Mark/Space Software, and took note of the condition being created on the second Mac immediately after doing this update.
    I don't really want to do a full reinstall of the System, as I suspect I will still end up with this "condition" after reinstalling my working applications.
    Any suggestions would be appreciated.

    A bit of troubleshooting .....
    On a full restart, any windows left open will retain their position, view, etc - but closed windows "forget" when reopened.
    During the safe boots, files were sent to the Trash, which are as follows:
    In a folder called 501.245359984
    and a folder called 501.245361007
    annex_aux
    annex.db
    filetoken.db
    FondResourceCache (only in the first folder above)
    fonts.db
    Local.fcache
    qdfams.db
    System.fcache
    User.fcache
    My startup items under my account are
    iTunesHelper
    Microsoft AU Daemon
    iKey
    MicrosoftMouseHelper
    MicrosoftKeyboardHelper
    Dashboard KickStart
    EEventManager
    iCalAlarmScheduler
    textsoapHelper
    Epson Scanner Monitor
    All of these items were already in place - for a long time - before this problem started.
    I cannot find /private in order to locate /private/var/run/StartupItems
    Nothing unusual (at least that I can see) in either of the other two locations.

  • External displays - browser window position when disconnected display

    I'm using a laptop, connecting one or two external displays, - one using the HDMI port, second using an USB "dock station" (Toshiba standalone). Second screen normally to the right, third screen (usb) above the laptop screen.
    Often when I have disconnected the USB external display, my Firefox browser window are still "on the third display" - position as if this display was still active.
    Even if I quit Firefox and restarts ( or even restarts windows ) the same position window is retained. The only way to fix it (when the USB connected display is not available), is to change the window position of the second (HDMI) display to cover the area of the USB one, then move Firefox window to my main laptop display, and then reposition the second screen back to the normal.
    Normally, I expect applications to automatically reposition the windows to the available display(s) under the conditions that an extra display is removed. However, this seems not to happen with Firefox. It's inconvinient, but possible to fix with the second screen available, but I'm lost when I am not able to connect an external display ...
    Is there any solution to this? Is it possible to change (reset) window positions directly in RegEdit ??

    Dear varkgirl:
    Thank you very much for your help and valuable suggestion.
    I've tried your suggestion but ran into some problems. The links I am trying to open in another window are actually PDF files that the viewer can download from my website.
    Since I was having problems I decided to try something else. After publishing the website to my desktop I then opened the pages where the links are in Dreamweaver. The layout view is great and displayed the image just the way it appears on the browser's window. I first selected the "link button" to the file and then in the inspector windows (bottom of the page) I chose under target the "_blank" option. This tells the software that the linked page or file is to be opened in a new blank browser window. I then saved the page (re-saved it over the existing file) to incorporate the changes. After this I proceeded to navigate through the website and everything works great.
    Thank you for your help and suggestions. I just thought I would post this here in case it may be of help to you as well as others.
    Best regards,
    Joseph Chamberlain

  • Remembering windows positions when switching from/to dual screen display

    Hello,
    Most of the time, a second LCD screen is plugged in my Macbook and configured as the main display. When I arrange the windows, I keep iTunes or my mail application maximized on the macbook screen and use the bigger external screen for all other windows.
    If I unplug the external display, all the windows are of course moved to the laptop display. When I plug again the external screen, all the windows are moved to the external display. But I would like the iTunes and mail application to remain on the laptop screen.
    Is there any utility to remember the windows positions and arrange them automatically when I switch from/to single/dual-screen display?
    Regards,
    Raph

    Would DisplayWatcher do what you want? I came across this a couple of weeks ago but haven't had the chance to try it out yet.
    - cfr

  • Auto-remember window positions switching from laptop to external screens

    Does anybody know of any utilities available that will automatically remember my app window positions when switching from laptop to external screens?

    'Stay' looks like the best solution found so far but it is not automatic Any more ideas are welcome!

  • How to re-center window positions

    Hi folks,
    I switched from 19" to a 27" screen. How can I tell LR to re-center it's window positions?
    The windos (like the Export window) are still on the old place (centered for 19").
    BRGDS!

    Just drag the top menu bar for either Lightroom or the Menu window. Or the bottom corner.
    I'm not sure what you are after though or where you are startibng from.........

  • Window position problem

    Hi everyone,
    I am having problems with window position.
    If my portal is set to english language, there are no problem.
    If my portal is set to hebrew language, I have troubles with position of windows. Some windows are moved to left, some are moved to right...and some are moved out of the screen.
    Code:
    IWDWindowInfo windowInfo = (IWDWindowInfo)wdComponentAPI.getComponentInfo().findInWindows("MyWindow");
    IWDWindow window = wdComponentAPI.getWindowManager().createWindow( windowInfo, true);
    window.setWindowPosition(WDWindowPos.CENTER);     
    window.open();      
    Can someone help ?
    Thanks in advance.

    David,
       turn down with:
       window.setWindowPosition(XXX,YYY);
    Could be usefull, find some CODE that give you MAX_WIDTH and MAX_HEIGHT of client browser and after
    window.setWindowPosition(func(MAX_WIDTH),func(MAX_HEIGHT));
    Message was edited by: Roberto Tagliento

  • Window position in sapscript

    Hi ppl,
    My requirement is to print the logo on right side for a particular company code. For other company codes, I need to print the logo on left side.
    Always the opposite side (left or right depending on company code) will have address printed.
    How can I achieve this in sapscripts ie. to change the window position dynamically.
    Please reply.
    Reward points guaranteed.
    Thanks,
    Shamoil.

    Hi,
    You must create two windows .
    And then try following code.
    in the text elemnt of first window write following.
    if BUKRS EQ 'PIIL'
    BITMAP 'ZSIGN2' OBJECT GRAPHICS ID BMAP TYPE BMON
    endif.
    and
    in the text elemnt of second window write following.
    if BUKRS EQ 'PIAG'
    BITMAP 'ZSIGN2' OBJECT GRAPHICS ID BMAP TYPE BMON
    endif.
    here
    - 'ZSIGN2' is the name of bitmap image uploaded by se78.
    - PIIL name of first company code.
    - PIAG name of second company code.
    reward points if helpful.
    Regards
    Rajesh

  • Sapscript window position

    Hello all.
    How can i determine the current X,Y window position so i can draw a BOX in the current line?
    Thank you
    Nuno Silva

    Additionally, determining the current key position of the window, usually trial and error method. You can use the 'Test Output' option to see the place where it draws the box.   Another thing, you don't need current line position as in the box command, you have to provide X and Y axis within the window. So it doesn't matter where you are, it will generate the box based on your X,Y inputs with the box command.
    Hope, it helps.
    Thanks
    Viswa

  • Mail Not Remembering Window Position of Previous Session (again)

    Everytime I relaunch Mail, I have to rearrange the viewer windows to the way that is most efficient to use them. Is there a way for Mail to remember window positions, and sort preferences for each viewer window?

    Interestingly, Mail does seem to remember the window positions, in its com.apple.Mail.plist, but it isn't applying the remembered positions. I tried a few times, and on at least one try it got the positions correct. Could it be that if you quit, restart then quit and restart again it will have them right on the second restart?
    AK

  • Mail Not Remembering Window Position of Previous Session

    Mail has started forgetting how its main window was sized when previously using the application.
    When I open Mail, the window dimensions are like those for a small screen - not as previously sized.
    Is this a known problem (could not find with discussion search) and is there a fix? Thanks!

    Interestingly, Mail does seem to remember the window positions, in its com.apple.Mail.plist, but it isn't applying the remembered positions. I tried a few times, and on at least one try it got the positions correct. Could it be that if you quit, restart then quit and restart again it will have them right on the second restart?
    AK

  • Get Info window position

    Lately my Get Info window has been opening with its upper left corner aligned with the upper left corner of the topmost Finder window. Previously it had placed its upper left corner at position (0,22) - the extreme left of the screen, just below the menu bar. The former position covers prime Finder window real estate. I prefer the latter position, as it obscures as little of the topmost Finder window as possible.
    How can I revert the behavior of the Get Info window position?

    That didn't do it. Turned out to be a conflict with the application FinderMinder.
    http://www.irradiatedsoftware.com/labs/
    FinderMinder is an old piece of freeware that I enable periodically when my windows become too "undisciplined." Once they've become fairly aligned again I disable it for awhile...mainly because I keep all extraneous process consumers and memory usurpers to a minimum. Hence I didn't notice the conflict until it appeared under 10.6.x.

  • Positive & Negative Time Management

    Dear Seniors,
    What is positive & negative time management? Which time management status do we use for these?
    What r time pairs & where can these be configured?
    Thx & Regards
    WARNED-> No more basic questions please.

    Hi,
    Positive time is plays the total role of workflow. All the processes related to time are automatically gets executed in the background. E.g., in our case it is done only partially to validate the attendance as per punches and other documents with shift timing and generate absence automatically in case of any discrepancy.
    .Negative Time (-ve Time) ? Where the all time related activities like validation of the attendance, posting of absence for wage deduction etc are done manually. It has less level of integration among the different components of time management.
    Positive Time Management we have two types of recordings:
    1. With Clock times - Complete time recording is captured
    2. With out Clock times - Only Number of hourse worked is captured
    Negative time Management:
    1. No clock times and assumed employee is working unless and until his or her absences are entered.
    Regards,
    Tarun

  • Setting window positions at startup of Labview

    Is there a way to set the window positions of the front pane and block diagrams when I start a new VI or when I look at an example (not at runtime of VI)?

    Hi JPDel,
    yes it's possible with VI Server functions.
    There are also some std vi's which will be called in defined situations. I don't know the link, but i know there exists a document written by Jim Kring about it.
    Hope it helps.
    Mike

  • Series Positive Negative

    Hello
    I am trying to address an requirement which involves showing the part of the data in stacked chart with color coding for positive and negative values. Can some one give me an idea how it can be addressed.
    I have seen an SAP Presentation PPT which is the exact requirement, but currently not able to create the same. Please look at the cost variances graph in the link below
    http://tumsaprouter.informatik.tu-muenchen.de/ugm/SAP%20University%20Alliances/SAP_Business_Objects_Example/xcelsius_slides.ppt

    Originally posted by: jaiemlop.isc.gmail.com
    Hi Ricardo,
    in that blog the author creates the coloring functionality using javascript
    in a report design. Can I create an event handler in a java application?
    In the API i see ColorDefinitionImpl, GradientImpl, ImageImpl,
    EmbeddedImageImpl and MultipleFillImpl. I don't know how to use the
    MultipleFillImpl, is it the equivalent to the "Positive/Negative" option in
    the report design palette?
    Jaime
    > Hi Jaime,
    > take a look at
    > http://www.birt-exchange.com/modules/wordpress/?cat=3&au thor=33
    > you'll find all answers there.
    > Greets, Ricardo.

Maybe you are looking for

  • I have 105 rows with alternating columns of No. sold

    I have 105 rows with alternating columns of No. Sold and Amount Sold, for six different dates.  I want the two totals columns on the right to sum every other column for the Total No. Sold and the same but one over for Total Amount Sold.  I know how t

  • Function that returns currently selected cell address or column

    Is there a function that returns the address (or just the column) of the currently selected cell? Simply put, something like =selectedcolumn. Background: I want to display help text in a cell, and I want that help text to change according to which ce

  • Rampradeep

    hi this is pradeep can anyone pls send me the whole transaction codes of sap bw i have some doubts in transaction codes. through ur answer i can know the transaction codes

  • Nested Repeat Loops in Applescript

    The following code has two lists: myURLs and myIMGs. I want to loop through the sites listed in myURLs, take a screenshot, then save them in my Shared folder as the file name listed in myIMGs. So, google.com's image will be saved as "google.jpg", and

  • Dead pixel on my Qosmio X300 screen

    Hello I have a problem that happened today. My laptop was fine yesterday. I took it up in its bag, Went with it to the college and I switched on on and I found a dead pixel - Not just one tiny one. it is a small one, about 3 x 3 square on 1440 x 900