Why doesn't this case statement work?

SELECT
case when PRODUCTS.PRODUCT_NAME in
select case when rank() over(order by ( sum(ag.RX_CNT) ) desc) < 6 then ( p.PRODUCT_NAME ) else 'XXXX' END RankedProduct
FROM
PAP_MONTHLYTIME_DIM m,
PAP_PRESCRIPTIONS_DEMOG_AGG ag,
PRODUCTS p,
PAP_ENROLLMENT_FLAGS_DIM f
WHERE
( m.MONTHLYTIME_DIM_ID = ag.MONTHLYTIME_DIM_ID )
AND ( ag.ENROLLMENT_FLAGS_DIM_ID = f.ENROLLMENT_FLAGS_DIM_ID )
AND ( p.PRODUCT_ID = ag.PRODUCT_DIM_ID )
AND ( f.ACTIVE_FLAG = 'Y' )
AND m.CALENDAR_YEAR_MONTH = '2007-04'
GROUP BY
m.MONTH_END_DATE,
p.PRODUCT_NAME
then
( PRODUCTS.PRODUCT_NAME ) else 'All Other' end as ProdNm,
PRODUCTS.PRODUCT_NAME,
sum(PAP_PRESCRIPTIONS_DEMOG_AGG.RX_CNT)
FROM
PRODUCTS,
PAP_PRESCRIPTIONS_DEMOG_AGG
WHERE
( PRODUCTS.PRODUCT_ID=PAP_PRESCRIPTIONS_DEMOG_AGG.PRODUCT_DIM_ID )
GROUP BY
PRODUCTS.PRODUCT_NAME
The first case statement is not working properly. First off - I know I can do this without the subquery in the case statement, but it's then tied to the Month and I don't want that.
The result set of the subquery contains valid product_names that match EXACTLY (I added LTRIM RTRIM just in case), but the ProdNm field still evaluates to "All Other" for them. If I change the subquery to something basic and remove the rank function, it works, but of course I need that function. My understanding is that it shouldn't matter what function is in the subquery. I thought Oracle would get the result set of the subquery first, then evaluate the case statement based on the result set (the subquery is obviously not correlated).
Any ideas?
Thanks.

My understanding is that it shouldn't matter what function is in the subquery. I thought Oracle would get the result set of the subquery first, then evaluate the case statement based on the result set (the subquery is obviously not correlated). It looks like the queries ARE somehow correlated. Consider the two simplified queries:
michaels>  SELECT   ename, deptno,
         CASE
            WHEN deptno IN (
                   SELECT CASE
                             WHEN ROW_NUMBER () OVER (ORDER BY NULL) < 3
                                THEN deptno
                             ELSE 1000
                          END
                     FROM dept)
               THEN 'Found'
            ELSE 'NOT Found'
         END FOUND
    FROM emp
ORDER BY deptno
ENAME          DEPTNO FOUND   
CLARK              10 NOT Found
KING               10 NOT Found
MILLER             10 NOT Found
JONES              20 NOT Found
FORD               20 NOT Found
ADAMS              20 NOT Found
SMITH              20 NOT Found
SCOTT              20 NOT Found
WARD               30 NOT Found
TURNER             30 NOT Found
ALLEN              30 NOT Found
JAMES              30 NOT Found
BLAKE              30 NOT Found
MARTIN             30 NOT Found
michaels>  SELECT   ename, deptno,
         CASE
            WHEN deptno IN (
                   SELECT *
                     FROM (SELECT CASE
                                     WHEN ROW_NUMBER () OVER (ORDER BY NULL) < 3
                                        THEN deptno
                                     ELSE 1000
                                  END
                             FROM dept))
               THEN 'Found'
            ELSE 'NOT Found'
         END FOUND
    FROM emp
ORDER BY deptno
ENAME          DEPTNO FOUND   
CLARK              10 Found   
KING               10 Found   
MILLER             10 Found   
JONES              20 Found   
FORD               20 Found   
ADAMS              20 Found   
SMITH              20 Found   
SCOTT              20 Found   
WARD               30 NOT Found
TURNER             30 NOT Found
ALLEN              30 NOT Found
JAMES              30 NOT Found
BLAKE              30 NOT Found
MARTIN             30 NOT FoundSo in the first query ROW_NUMBER() evaluates to NULL (not sure why) so the condition will never be satisfied! This is easily proofed when actually testing for nullity:
WHEN ROWNUM() OVER (ORDER BY NULL) IS NULL THEN
...will always show 'Found'!
Inlining the subquery »materializes« it, and ROW_NUMBER() gets the desired value.

Similar Messages

  • Why doesn't this simple applescript work any more in ML mail.app (as a rule)

    It works only when you right click on the mail message and choose "run rules", but not on incoming messages (without interaction).
    The first dialog is shown both when incoming or running manually, but the second dialog (with the id) is only shown when running manually. Nothing is shown in console.log
    Any ideas?
    using terms from application "Mail"
        on perform mail action with messages theMessages for rule theRule
            tell application "Mail"
                repeat with theMessage in theMessages
                    display dialog "inside"
                    set theId to id of theMessage
                    display dialog "the id is " & theId
                end repeat
            end tell
        end perform mail action with messages
    end using terms from

    Might it be that any incoming message doesn't have an ID yet ?
    Try this:
    using terms from application "Mail"
        on perform mail action with messages theMessages for rule theRule
            tell application "Mail"
                repeat with theMessage in theMessages
                    display dialog "inside"
                    set theTest to (exists id of theMessage)
                    display dialog theTest
                end repeat
            end tell
        end perform mail action with messages
    end using terms from

  • VirtualBox clipboard issue AKA why doesn't this restart script work?

    The host is Windows7, the guest is up-to-date Arch and everything I describe is for guest-to-host or host-to-guest copy and paste.  The clipboard within the guest never fails.  The VirtualBox Guest configuration has the clipboard set to 'bi-directional.'
    I'm starting the clipboard via .xinitrc which includes the following line
    VBoxClient-all &
    This is what gets launched
    oliver 211 1 0 15:33 ? 00:00:00 /usr/bin/VBoxClient --clipboard
    It all works perfectly for an indiscriminate amount of time, then suddenly, it stops updating the buffer.  If I try to copy/paste anything new, I get the last entry before it stopped working.  If I restart it (by killing the process and running VBoxClient --clipboard) it works again for an indiscriminate time.  Wash/rinse/repeat.
    I wrote a quick script to run from cron but it's having problems
    This is the script
    #!/usr/bin/bash
    PID="$(ps -ef|grep -i "[v]boxclient --clipboard" | awk '{print $2}')"
    kill $PID && /usr/bin/VBoxClient --clipboard
    exit 0
    I watched the cronjob and it appears to be doing what I want but a 'ps' doesn't show it running afterwards
    ++ grep -i '[v]boxclient --clipboard'
    ++ awk '{print $2}'
    ++ ps -ef
    + PID=3158
    + kill 3158
    + /usr/bin/VBoxClient --clipboard
    + exit 0
    I'm assuming cron runs the command in a shell that gets destroyed when the cronjob is done or something and this is tearing down the process.  I've tried modifying the command with nohup and ampersands to no avail.
    A fix for the underlying problem would be great but I'm assuming I'll be waiting on Oracle for that.  In the meantime, if I could restart this thing periodically it would help me out a bit.
    Any ideas?

    I have the same problem - VBoxClient stops working and restarting it from cron does not work.
    I run this from cron every 10 minutes:
    (killall VBoxClient && VBoxClient-all) || VBoxClient-all
    and VBoxClient is killed every time but is not launched again. How can you explain it?

  • Why won't this MERGE statement work?

    I am testing out a MERGE statement, which contains a subquery that will return no rows...on this condition, it should insert a record; however I get 0 records merged. Why is this?
    Ultimately, the hard-coded values will actually be passed in as parameters. If those a record with those four values is not found, then it should insert.
    MERGE INTO tb_slea_election_worksheet A
    USING 
    (SELECT i.slea_year,i.empid,i.bda_sum_sort,i.bda_dtl_sort FROM tb_slea_election_worksheet i
    WHERE  slea_year = '2008'
    AND empid = '6468T'
    AND bda_sum_sort = '30'
    AND bda_dtl_sort = '9999'
    ) B
    ON (A.slea_year = B.slea_year
    AND A.empid =B.empid
    AND A.bda_sum_sort  = B.bda_sum_sort
    AND A.bda_dtl_sort  = B.bda_dtl_sort) 
    WHEN MATCHED THEN
      UPDATE SET A.fa_proj_exp_amt  = 888
    WHEN NOT MATCHED THEN
      INSERT    (slea_year,empid,bda_sum_sort,bda_dtl_sort,act_exp_lst_yr,fa_proj_exp_amt)
      VALUES ( '2008','6468T','30','9999','0','55');

    A merge statement is just a much more efficient way of doing something like this pl/sql block
    DECLARE
       l_n NUMBER;
    BEGIN
       FOR r IN (SELECT pk, col1, col2 FROM source) LOOP
          BEGIN
             SELECT 1 INTO l_n
             FROM target
             WHERE pk = r.pk;
             UPDATE target
             SET col1 = r.col1,
                 col2 = r.col2
             WHERE pk = r.pk;
          EXCEPTION WHEN NO_DATA_FOUND THEN
             INSERT INTO target
             VALUES(r.pk, r.col1, r.col2);
          END;
       END LOOP;
    END;So, if the select from source returns no rows, nothing is going to happen.
    John

  • Why doesn't this simple AppleScript work?

    Hi. I'm trying to change my desktop background using some AppleScript from the command line:
    osascript -e 'tell application "Finder" to set desktop picture to POSIX file "~/Pictures/Some Picture.jpg"'
    But, I get this:
    33:48: execution error: Finder got an error: AppleEvent handler failed. (-10000)
    I also tried it this way:
    osascript -e "tell application \"Finder\" to set desktop picture to POSIX file \"~/Pictures/Some Picture.jpg\""
    ...and got the same result.
    So, I then tried this AppleScript (essentially the same thing?) from within AppleScript editor:
    tell application Finder
              set desktop picture to POSIX file "~/Pictures/Some Picture.jpg"
    end tell
    and got a syntax error:
    A class name can’t go after this application constant or consideration.
    I have reason to believe that this works for others, but I can't seem to make it work. Also, if anyone can suggest another way to change the desktop background from the cammand line, that would be helpful too.

    Thanks, that worked great in AppleScript Editor, and when I ran the .applescript file with osascript. However, when I tried to make the same changes from the commandline, I got this:
    33:48: execution error: Finder got an error: Can’t make "Pictures:Some Picture.jpg" into type file. (-1700)
    It would be easier if I could pass a command line argurment to my script, that is now working thanks to you (I know there is a way to do this but how?). Also it would have to be a a UNIX style path (like '/path/to/file.jpg' not 'path:to:file.jpg of home' or 'file.jpg of to of path').

  • Why doesn't this update work?

    Why doesn't this update work? Can't I sum up two select count(*) in such a subquery?
    Thanks
    update sales T
    set T.field2 = ((select count(*)
    from sales t
    where t.field1 = trunc(sysdate)) + (select count((*)
    from sales t2
    where t2.field2 is null));
    I get
    ERROR at line 4:
    ORA-00907: missing right parenthesis
    with the * under the +
    In other words I want to run
    update sales set field = ((select count(*) ..... ) + (select count(*) ..... ))
    Edited by: Mark1970 on 26-mar-2010 1.37
    Edited by: Mark1970 on 26-mar-2010 1.38

    My problem is to undestand why I got a syntax error about parenthesis.Because you cannot perform arithmatic operation with a value coming from a subquery in a SET clause of UPDATE
    SQL> update emp
      2  set sal=(select 1 from dual)+1;
    set sal=(select 1 from dual)+1
    ERROR at line 2:
    ORA-00933: SQL command not properly ended
    SQL> select sal from emp
      2  where deptno=(select 10 from dual)+10;
           SAL
           800
          2975
          3000
          1100
          3000
    SQL>  select deptno,sal from emp
      2   where deptno=(select 10 from dual)+10;
        DEPTNO        SAL
            20        800
            20       2975
            20       3000
            20       1100
            20       3000Try such few examples..
    Twinkle

  • Why Doesn't the XIRR function work?

    In Excel if you have 5 records from a1:b5 then XIRR looks like this:
    XIRR(A1:A5, B1:B5) you get a nice neat answer like .35
    Here is a version that works in Crystal that would require manual entry of any new quarters numbers and dates-- and if you plug this into Crystal it works:
    (XIRR([1000000,-100000,-100000,-100000,-100000,10277.49,-100000], [DateValue(1999,2,1),DateValue(1999,3,1),DateValue(1999,6,1), DateValue(1999,12,1),DateValue(2000,3,1),DateValue(2000,6,1),DateValue(2000,9,1)]))*.100
    You do get a nice answer of something like .035.  But this is all done manually and I need it to function automatically when the report is refreshed.
    So you have a range for the currency and a range for the date fields. I need to simulate this in crystal. Crystal has an XIRR function, and with the arrays, I should be able to fill in the range, but am having difficulty getting it to work.
    After building the arrays, I made another formula to combine the arrays in the XIRR formula.
    I am down to this error now after getting this formula this far  --
    "Numerical method did not converge; try another value for guess."
    Here's where I am with the formula, although they don't want to use the guess part of the XIRR function - they just want to use the XIRR(number/currency, date).  Maybe you could pass this on too?:
    /{@Reset} for the group header (NOT using a repeated group header):
    whileprintingrecords;
    numbervar array x := 0;
    datevar array y := date(0,0,0);
    numbervar i := 0;
    numbervar j := 0;
    //{@accum} for the detail section:
    whileprintingrecords;
    numbervar array x;
    datevar array y;
    numbervar i := i + 1;
    numbervar j := count({table.groupfield},{table.groupfield});
    if i <= j then (
    redim preserve x[j];
    redim preserve y[j];
    x<i> := tonumber({table.currency});
    y<i> := datevalue({table.datetime})
    //{@xirr calc} to be placed in the group footer:
    whileprintingrecords;
    numbervar array x;
    datevar array y;
    xirr(x,y)
    The array works correctly.  So why do I get that error and why doesn't the XIRR formula work like they say it should?  Has anyone used this successfully in Crystal--maybe you could shed some light?
    Thanks!

    Hi,
    I am receiving that same error when the last item in the array is 0, otherwise all works perfectly.
    When I run the same group of numbers and dates in Excel it returns without issue.
    -265500.00,-690000.00,-570000.00,16814.25,-855000.00,-619500.00,55293.46,30411.40,15183.76,  0.00
    01-25-2007,03-06-2007,05-02-2007,06-29-2007,08-01-2007,08-24-2007,09-17-2007,03-14-2008,05-28-2008,03-31-2010
    =XIRR(A2:J2,A1:J1,-0.1)
    Is there a known bug in Crystal's XIRR function when the last value is 0? 
    Or a hot-fix that will repair this?
    Thanks in advance,
    Gary
    PS. I am using Crystal XI Product Version: 11.0.0.2495

  • Why doesn,t  my mail iccon work?

    Why doesn't my mail icon work?

    If you moved Mail out of the Applications folder, then applied the security update, Mail has been disabled.
    It must stay protected in the Applications folder, or you risk the possibility that malware might change it and use it to send spam.
    Mac OS X v10.6: "You can't use this version of Mail…" alert after installing Security Update 2012-004

  • Why doesn't my VGA adapter work to connect my iPad2 to my projector. I haven't had any problems in the past?

    Why doesn't my VGA adapter work to connect my iPad2 to my projector. I haven't had any problems in the past?

    Hey MarieF-D,
    Thanks for the question. The following article provides basic troubleshooting steps that may help to resolve your issue:
    iOS: About Apple Digital AV Adapters
    http://support.apple.com/kb/HT4108
    Troubleshooting
    If you encounter an issue using the Apple Digital AV Adapter or VGA Adapter:
    Disconnect and reconnect the adapter from the iOS device and display.
    Connect directly to the TV, projector, or external display using a known-good VGA or HDMI cable.
    Remove any VGA or HDMI extension cables or converters.
    Note that accessories that convert a VGA or HDMI signal to other video formats (DVI, Composite, Component) are not supported.
    Ensure that you are using the latest version of iOS. Some Apple Digital AV Adapters require iOS 5.1 or later.
    Note: When using an Apple Digital AV Adapter manufactured before early 2012 with iPad (3rd generation), you may see the "This accessory is not supported" alert. Dismissing the alert will allow you to use the adapter.
    For optimal performance, you may need to adjust the video resolution or settings for your display. If your display offers an "auto detect" or "factory default" setting, you may be able to use these options to optimize video resolution and display.
    Thanks,
    Matt M.

  • Why doesn't the alt tag work in firefox to open a description of an image on mouseover

    In IE, when I roll my mosue over an image, it gives a tooltip description of the image contained in the html alt tag. Why doesn't this work in Firefox?

    The "alt" tag is meant to show text when the image isn't loaded, the "title" tag is meant for a description of an image on cursor hover. IE has been doing that wrong for many years, where Firefox follows W3C standards. A properly coded webpage should have both "alt" and "title" tags.

  • Why doesn't the "back" button work all the time in Safari?

    Why doesn't the "back" button work all the time in Safari?

    thanks for the reply. You prompted me to check and I realised it wasn't installed on my test laptop and opening in Microsoft Reader. I've installed it now and it works.
    My next challenge is to prevent the mailto: command opening Microsoft Mail instead of Outlook, but I guess every user will have a different default.
    Thank you

  • Lost my iPhone and why doesn't find my iPhone work

    Lost my iPhone and why doesn't find my iPhone work

    A friendly reminder: In order to use Find My IPhone Successfully, you need to 1. Turn on Location Services, 2. Lock Location Services (Using Restrictions in Settings, General, Restrictions) so that if some one else finds your IPhone, they can NOT turn off Find My IPhone And/Or Location Services itself! 3. Add your Mobile Me and/Or ICloud Account to your IPhone. 4. Lock Accounts (Again in Restrictions) from being changed or Deleted so that your Mobile Me And/OR ICloud Account can NOT be Deleted! 5. Look Up the Location of your IPhone Before Suspending Service to the IPhone, NOT after Suspending Service (simple common since applies here as well).

  • Just downloaded Numbers spreadsheet... I entered a simple "if" statement...If(c2=0,9,7) just to see how it works.... But I get an error message "Argument 1 of if expects a Boolean but found "c2=0....This if statement works fine in Excel

    Just downloaded the Apple Numbers spreadsheet app... I entered this simple 'if' statement to see how it works.... "if(c2=0,9,7)...
    I got an error message.. "Argument 1 of if statement expects a Boolean but found "c2=0".
    This if statement works fine in Excel.....What am I doing wrong ????

    Just downloaded the Apple Numbers spreadsheet app... I entered this simple 'if' statement to see how it works.... "if(c2=0,9,7)...
    I got an error message.. "Argument 1 of if statement expects a Boolean but found "c2=0".
    This if statement works fine in Excel.....What am I doing wrong ????

  • Question about this case statement...Never seen it written this way

    I have this case statement written by a developer and i am trying to understand what he was trying to accomplish with writing it in this manner
    CASE t_CELL
                    WHEN 'XML' THEN
                        'Mods'
                    ELSE
                        CASE WHEN t_CELL IS NOT NULL THEN
                            t_Cell
                        ELSE
                            CELL
                        END
                    END
                = CELL OR CASE t_CELL
                    WHEN 'XML' THEN
                        'Amps'
                    ELSE
                        CASE WHEN t_CELL IS NOT NULL THEN
                            t_Cell
                        ELSE
                            CELL
                        END
                    END = CELL);What is throwing me off is the = CELL that was included..Kindly note, this is just a sample code

    Hi,
    If x and cell are strings, then I trust you understand what it means to compare them by saying:
    x = cellx can be any kind of expression that returns a string.
    For example, do you understand what it means if x is a string literal, like this?
    'Amps' = cellDo you understand what it means when x is another string column, like this?
    t_cell = cellDo you understand what it means when x is a function that returns a string, like this?
    TO_CHAR (SYSDATE, 'Dy') = cellIn the code you posted, the CASE expression is just another way of specifying a string value for x:
    CASE ... END = cellA CASE expression is just another kind of expression, that is, another thing that can replace x on the left of the = sign.
    It looks like the condition you posted is equivalent to:
    (     (     t_cell     = 'XML'
         AND     cell     IN ('Amps', 'Mods')
    OR     (     t_cell     != 'XML'
         AND     cell     = t_cell
    OR          t_cell     IS NULL
    )

  • Why doesn't my duplicate frame work in photoshop 2014?

    why doesn't my duplicate frame work in photoshop 2014?
    I draw a figure in frame 0 then duplicate frame. After the frame is duplicated I move the figure over to make sure there are different frames but as soon as I check the first frame Ive noticed that both frames have moved together. So nothing has changed. Why?

    I always create the individual frames in layer groups first. So build what you need, break them up or duplicate them, position them where you want them and then create your frames by turning off all the layer groups or layers you don't need.
    Here is an example of one of my layer pallets:
    Each scene is a frame and I turn them on and off as I need them.

Maybe you are looking for