SUM function to give NULL result

I am really lost on how I can force the SUM function to give me a NULL result when at least one of the elements is a NULL value. I would appreciate any help.

The short answer is "you can't". The slightly longer answer is the you can't because most aggregate functions work only on non-null values, so SUM silently ignores NULLS.
However, you can take advantage of that fact to do what you want.
SQL> SELECT * FROM t;
        ID GROUPCOL
        33 GROUPA
        50 GROUPA
         5 GROUPA
        21 GROUPA
        43 GROUPA
        58 GROUPB
        10 GROUPB
        29 GROUPB
        10 GROUPB
        37 GROUPB
           GROUPA
SQL> SELECT groupcol, SUM(id) sum_id, COUNT(*) count_all,
  2               COUNT(id) count_id
  3        FROM t
  4        GROUP BY groupcol;
GROUPCOL       SUM_ID  COUNT_ALL   COUNT_ID
GROUPA            152          6          5
GROUPB            144          5          5Note that count_all is different than count_id. So, we can wrap this query in another to return NULL for the sum of groupa.
SQL> SELECT groupcol, CASE WHEN count_all = count_id THEN sum_id
  2                        ELSE NULL END sum_id
  3  FROM (SELECT groupcol, SUM(id) sum_id, COUNT(*) count_all,
  4               COUNT(id) count_id
  5        FROM t
  6        GROUP BY groupcol);
GROUPCOL       SUM_ID
GROUPA
GROUPB            144Although, I too would be interested in the answer to 405764's question.
John

Similar Messages

  • Generated webservices give null result in Flex 3

    Hi there,  I have a web service on my localhost. Calling this from a PHP page works fine and it returns the expected results. (I pass 2 values and it returns a different string depending on the values passed).
    However, in Flex 3, I have generated the webservice proxy classes using the "Data" | "Manage Web Services" dialog.  I am consuming these services using the following code:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
         <mx:Button click="clickHandler(event)"/>
         <mx:Script>
              <![CDATA[
                   import generated.webservices.*;
                   import mx.controls.Alert;
                   import mx.rpc.events.FaultEvent;
                   public var _ws:SalesService = new SalesService();
                   private function clickHandler(_e:MouseEvent):void
                        _ws.addonsaleEventListener(resultHandler);
                        _ws.addSalesServiceFaultEventListener(faultHandler);
                        _ws.onsale(10,90);
                   public function resultHandler(_e:OnsaleResultEvent):void
                        if(_e.result == null)
                             Alert.show("result is: null");
                        else
                             Alert.show("result is: "+_e.result);
                   public function faultHandler(_e:FaultEvent):void
                        Alert.show(_e.message.toString());
              ]]>
         </mx:Script>
    </mx:Application>
    The "resultHandler" method is called and the "faultHandler" method is not called, which suggests a result is returned, but _e.result is null in the "resultHandler" method.
    Can anyone see if I am missing something in the actionscript?
    Andrew.
    p.s.
    I can post the generated proxy classes, or even the wsdl for the webservice if it helps.
    A.

    No, they're not exactly the same (see below).
    Calling the same web service; Flex 3 is generating a
    different result object than Flex 2, and therefore can/will not
    type the results as the Array my original app had come to expect.
    Is this by design?
    A suggested code revision would help, but...
    The question in my
    original post is still in play:
    Where would I have gone to learn this? The release notes are
    simply a cut list of changes. Is there a resource which summarizes
    the types of errors one is likely to see when porting a Flex 2 app
    to Flex 3, along with the most-likely changes as causes? When CFMX
    was first released, there was a helpful checklist of tags and
    syntax to help you audit your CF5 for the upgrade. Has one of your
    gurus blogged something like this for FX3 and I just can't find it?

  • Sum function on a column

    Hi,
    I created a report with few columns and one cash column where I gave the function as sum. when I dont do a sum for that column there are four rows coming up. Three rows for 'income' and one row for 'Principal'. The value for principal is coming correct when I tally with the sql query. But when I add the function sum to that column the 'income' total is summing up correct but for some reason the 'principal' amount is not showin the value that it showed when I did not add the sum function. It is showing a different value. I am not sure what's happening here. Any advices please.

    Hi Sandeep,
    I am not selecting any columns from fact table. I am just selecting columns from two dimesion tables. One dimension table has Account number, date and meaning. The other dimension table has cash column. When i pull these columns and run it gives correct values. For example for one account number we have two meanings income and principal. For that account number we have three values for income and one value for principal. When I run the query it is running good. But when I goto Critera and say edit formula on cash and put function as sum and then run the report it is not giving me the principal value correct. The sum of incomes are coming correct. The principal value was 2781.32 and after addig sum function it gives me 119596.76. Not sure why?

  • SUM function resulting WRONG values when some cell contains a string

    A very strange problem that can result in wrong financial calculations and big mistakes...
    If we have SUM function for some range of cells and one of them is treated as text string (I mean it's number in fact but Number is sure it's text string). than SUM function calulates ALL cells except this sell silently without errors and results in wrong result.
    For example we have cells and values
    A B
    =====
    1| 15 USD
    2| 0 USD
    3| 37 USD
    4| 1 USD
    5| 3 USD
    here the function SUM(B1:B5) should provide the result "56 USD"
    But if cell B5 is treated as text string (it can be still displayed as "3 USD" so we don't know it's treated as text string for some reason) than SUM(B1:B5) swill answer "53 USD".
    The problem is we DON'T know cell B5 is treated as text and we are fully sure that we have the correct sum of all 5 cells, in reality we see sum of 4 cells only....
    I think anybody working with financial or other important data can imagine how dangerous this SUM behaviour is.... I encountered several times that when importing data from Excel or by other ways numbers are imported as text strings. So if I have a lot of cells I'm not sure if all those cells are correctly styled or some of them for some unknown reason is treated as text string.
    In Microsoft Excel there is a very right solution. In MS Excel if any cell in the SUM is wrong format the SUM function simply provides error as a result. But in Numbers SUM doesn't tell us about error, it simply provides us with a wrong result!
    With formal logic the way SUM works in Numbers is total idiotism. If I ask to SUM B1:B5 than I definitely ask to sum ALL 5 cells, not 4, not 3, not 6 but 5 definite cells. If Numbers can't sum those exactly those 5 cells the only answer of the function should be ERROR.
    But Apple Numbers answers me some result of summing those cells that it's able to sum. Apple Numbers SUM function is not confused that I asked for SUM of 5 (not 4 or 3) cells and I expect to have this sum as a result.
    In fact Apple uses the right logic when we use another formula. If we use =B1B2+B3+B4B5 and any cell contains text string that we'll have error result the sam as in Microsoft Excel. So in this example Numbers behaves correctly.
    So why SUM (B1:B5) can provide totally different result as =B1B2+B3+B4B5?

    alexb2 wrote:
    So when I set format for my number as my local currency it's displayed as 123 XXX (XXX is my currency but it's not in latin). I see it's not only displayed but also stored as 123 XXX. That's different from Excel that stores only numbers in cells and shows number with prefix or suffix - Numbers storex number with prefix or suffix.
    No, you get this behavior because the original sheet is displaying values as currencies. I assumes that the import process pass it as a string because he doesn't recognize it as a currency value. As far as I know, Numbers stores the currency entries as a pure number and an indicator of the used currency.
    Here is an example.
    (a) the description of the numerical value (I underlined it: 456)
    <sf:number-cell sf:flags="4" sf:value="456" sf:col="1" sf:row="2">
    <sf:cell-style-ref sfa:IDREF="SFTCellStyle-46"/>
    <sf:content-size sfa:w="58.659881591796875" sfa:h="14"/>
    </sf:number-cell>
    (b) the description of the format (I underlined the used currency: XAM)
    <sf:cell-style sfa:ID="SFTCellStyle-46" sf:cell-style-default-line-height="12" sf:parent-ident="tabular-Basic-body-cell-style-id">
    <sf:property-map>
    <sf:SFTCellStylePropertyNumberFormat>
    <sf:number-format sfa:ID="SFTNumberFormat-23" sf:format-type="1" sf:format-string="#,##0.00 &#xA4;;-#,##0.00 &#xA4;" sf:format-decimal-places="2" sf:format-currency-code="XAM" sf:format-negative-style="0" sf:format-show-thousands-separator="true" sf:format-fraction-accuracy="-3" sf:format-use-accounting-style="false"/>
    </sf:SFTCellStylePropertyNumberFormat>
    <sf:SFTCellStylePropertyImplicitFormatType>
    <sf:number sfa:number="256" sfa:type="i"/>
    </sf:SFTCellStylePropertyImplicitFormatType>
    <sf:SFTCellStylePropertyFormatType>
    <sf:number sfa:number="257" sfa:type="i"/>
    </sf:SFTCellStylePropertyFormatType>
    </sf:property-map>
    </sf:cell-style>
    Of course, if the original currency string is not recognized, it can't be described as such a feature and the value is treated as a simple string.
    So may be at some moment my 123 XXX is treated like string value.
    Yes, find and replace is a nice tool when importing data - thanks for the tip. the last problem is with already Numbers files that were imported not today (or even createde as Numbers file) where some cell becomes string value after some editing.
    Here again, if you edit a currency string and replace it to a not recognized one, the result will be logically a string.
    There is an other way to give this result:
    copy a value from a cell formatted as XAM currency (just an example)
    paste it in a cell whose format is currency Euro (once again it's just an example).
    The result will be a string.
    The culprit is not the program, it's the user.
    I had several times this situation and last time I found error only because I have my budget in 2 programs - in Numbers and in another special budgeting program. As each program has advantages I have in fact 2 instances of the same budget.
    And when I changed some string in Numbers and another program I noticed the sum is different. I was sure it's another program somewhere buggy but noticed than Numbers simply ignores one of the budget strings and sums without it... In fact it was even not the string I changed, I remember I changed the buggy string about a week ago but I haven't compared budgets that time so my budget had a mistake for some time till I noticed it. If I used only Numbers without copy of budget in another program may be even today I won't notice the mistake.
    The same situation happened not once.
    I think that the choice made by Apple for SUM() is correct. You feel that it is wrong. It's useless to debate more, we will not change the behavior of the function.
    I try to give a workaround.
    The neater one is to add columns as I described in my first response.
    The given formula will clearly flag cells which aren't containing numerical values. If you move the SUM from the original range to the new one, the oddities will be flagged automatically.
    Here is an alternate workaround:
    The currency is XAM.
    In B4 I introduced a typo so the value is no longer a numerical one.
    Given that, the sum in the footer doesn't count the 34 (which is the normal behavior).
    In column C1 I entered =1*B
    which flagged the bad cell.
    The alternate is to use an auxiliary table like aux1
    In A1 I entered:
    =IF(ISERROR(INDIRECT(ADDRESS(ROW(),COLUMN(),,,"main"))),"",IF(ISBLANK(INDIRECT(A DDRESS(ROW(),COLUMN(),,,"main"))),"",1*INDIRECT(ADDRESS(ROW(),COLUMN(),,,"main") )))
    Exactly the same formula in B1, C1, D1, …
    So, the table will automatically grab the contents of the main table (just take care to insert more columns in aux1 than in main)
    In the footer row of aux1, insert a sum formula for columns where there is required.
    Looking at this footer will flag columns where a value may be "wrong" so, it will be necessary (but easy) to scan the column's content to find the red triangle(s).
    Yvan KOENIG (from FRANCE lundi 13 octobre 2008 13:27:40)

  • Incorrect sum function result in invoice

    I'm a Numbers noob, so apologies if this has been covered elsewhere, but I couldn't find it.This issue causes me no issues in Excel but doesn't work properly in Numbers, so I'm wondering what gives.
    I have an invoice for my clients where I have multiple rows, each with a service item, followed by the number of hours spent on that, followed by a cell with an EQUAL function, ie 2/3 of an hour x $40 per hour, which correctly EQUALs as $26.66. (The EQUAL cell is set to formatted as currency to 2 decimal places)
    If a second item appears that has say 1/3 of an hour x $40 per hour, this correctly EQUALs as $13.33.
    However when I total the EQUALs column with a SUM function, it shows $40, not $39.99. As the cells are only formatted to 2 decimal points, and all are formatted as currency, where could the error be happening?
    My clients accounting dept keeps coming back and complaining about my invoices being incorrect... I can't believe that Numbers can't do a SUM function.

    Hi Fritz,
    1/3 and 2/3 are not exact numbers. They go to infinity.
    Column B is formatted as Fraction
    Column C is formatted as Number (Decimals Auto)
    Formula in C2 (and Fill Down)
    =B2
    Formula in D2 (and Fill Down)
    =C2×40
    The Numbers app is correctly rounding to two decimal places.
    If you display Column C as Number to 2 decimal places,
    Again, correct.
    Your clients are quibbling about $0.0000000000000000000 (to infinity) then a infinitesimal part of 1 cent. Which is nonsense!
    Shops also round the total invoice up or down.
    If you work an extra 10 minutes, that will equal exactly 0.5 hours.
    If you work 5 minutes less, that will equal exactly 0.25 hours.
    No rounding needed, and no argument from your clients!
    Regards,
    Ian.

  • Count function on months column gives wrong result

    Hi,
    I am on OBIEE 11.1.1.7.150120.
    I used the count function on the month column and rather than getting 12 as the answer i get 365. (i used a filter on the year column to restrict it to one year)
    How could this happen?
    Any help would be appreciated.

    I was able to get the answer as 12 on the month column in the Dim_Time using the count distinct.
    The main reason i was trying this is because i have a VALUE column in VIew_A. I am trying to sum the values of these, but when i use the sum function, the output is quite huge and wrong. I dosen't match with the monthly figures.
    For eg:
    Month
    Income Cost
    JAN
    186.96
    FEB
    309.29
    MAR
    246.82
    APR
    247.95
    998.76
    1,462.74
    MAY
    160.27
    645.60
    1,643.84
    JUN
    172.19
    693.61
    927.12
    JUL
    150.27
    605.32
    855.89
    AUG
    133.61
    483.66
    538.20
    789.22
    SEP
    144.56
    412.42
    582.34
    824.84
    OCT
    264.96
    315.66
    364.00
    631.32
    1,067.32
    1,466.22
    NOV
    240.39
    832.10
    968.32
    1,058.73
    1,638.38
    DEC
    215.81
    857.30
    869.31
    24005.34
    But if i use the sum function on the Income/cost column, the value i get is
    C_MONTH
    SUM(INCOME_COST)
    JAN
    5,795.86
    FEB
    8,660.21
    MAR
    7,651.52
    APR
    81,283.62
    MAY
    75,941.13
    JUN
    53,787.67
    JUL
    49,955.96
    AUG
    60,285.39
    SEP
    58,924.80
    OCT
    127,394.01
    NOV
    142,137.76
    DEC
    60,215.18
    This just doesn't work out. I need the answer to be 24005 by using the sum function

  • What kind of input parameter is used in SUM function?

    Hi Everyone,
    As we know sum is a predefined oracle function. But what these oracle guys have used for the input parameters. How they have done this?
    I mean we can write this sum fuction like so many ways like as mentioned below. Please give me some ideas how to do that.
    SELECT SUM(salary) as "Total Salary" FROM employees;
    SELECT SUM(DISTINCT salary) as "Total Salary" FROM employees;
    SELECT SUM(income - expenses) as "Net Income" FROM gl_transactions;
    SELECT SUM(sales * 0.10) as "Commission" FROM order_details;Regards,
    BS2012

    BS2012 wrote:
    Hi Everyone,
    As we know sum is a predefined oracle function. But what these oracle guys have used for the input parameters. How they have done this?
    I mean we can write this sum fuction like so many ways like as mentioned below. Please give me some ideas how to do that.
    SELECT SUM(salary) as "Total Salary" FROM employees;
    SELECT SUM(DISTINCT salary) as "Total Salary" FROM employees;
    SELECT SUM(income - expenses) as "Net Income" FROM gl_transactions;
    SELECT SUM(sales * 0.10) as "Commission" FROM order_details;Regards,
    BS2012As others have said, your question is not quite clear.
    There are many aspects and angles to looking at what you are asking.
    Primarily, from a top-level, the sum function simply takes a number value as it's argument, so all those examples you have given have expressions in them that evaluate to a numeric value before being supplied to the sum function. (As someone else already mentioned you can have non-numeric datatypes, just so long as they can implicitly be converted to a numeric value).
    From a statement parsing and execution perspective, the contents of the expression inside the brackets will be evaluated before being passed to the sum function. It is not the sum function that itself takes the expression and evaluates it. The sum function just expects a single numeric value.
    Internally, what the sum function does, is more than just a single... call function and return value, because it has to deal with multiple values being passed in as part of the aggregating group. As such, it needs to have the ability to know when to start it's summing, to accept multiple values as input so it can sum them together, and to know when to stop summing inputs and pass the result back.
    If we write our own user defined aggregate function (other people have already provided a link to explain such) we can see what is happening internally. In this following example, we'll write a user defined function that multiplies the values rather than sums them...
    create or replace type mul_type as object(
      val number,
      static function ODCIAggregateInitialize(sctx in out mul_type) return number,
      member function ODCIAggregateIterate(self in out mul_type, value in number) return number,
      member function ODCIAggregateTerminate(self in mul_type, returnvalue out number, flags in number) return number,
      member function ODCIAggregateMerge(self in out mul_type, ctx2 in mul_type) return number
    create or replace type body mul_type is
      static function ODCIAggregateInitialize(sctx in out mul_type) return number is
      begin
        sctx := mul_type(null);
        return ODCIConst.Success;
      end;
      member function ODCIAggregateIterate(self in out mul_type, value in number) return number is
      begin
        self.val := nvl(self.val,1) * value;
        return ODCIConst.Success;
      end;
      member function ODCIAggregateTerminate(self in mul_type, returnvalue out number, flags in number) return number is
      begin
        returnValue := self.val;
        return ODCIConst.Success;
      end;
      member function ODCIAggregateMerge(self in out mul_type, ctx2 in mul_type) return number is
      begin
        self.val := self.val * ctx2.val;
        return ODCIConst.Success;
      end;
    end;
    create or replace function mul(input number) return number deterministic parallel_enable aggregate using mul_type;
    /So, our user defined aggregate function is based on an aggregate object type.
    This object holds a value ("val" in our example).
    It has an Initialize method, so when the SQL engine indicates that it's the start of an aggregation of values it can set it's value to an initial value (in this case null).
    It has an Iterate method, so as the SQL engine passes values to it as part of the aggregated set of values, it can process them (in our case it multiplies the input value with the value it already has for this set of aggregations (and takes a base value of 1 for the first iteration))
    It has a Terminate method, so when the SQL engine indicates that the aggregate set of values is complete, it can return the result.
    The last method in there is a Merge and is a mandatory requirement, so that when aggregation is done using parallel evaluation (to improve performance internally), the results of those parallelly executed aggregations can be combined together (see http://docs.oracle.com/cd/E11882_01/appdev.112/e10765/ext_agg_ref.htm#ADDCI5132). As we're multiplying numbers, in our case, it is simply a case of multiplying one result with the other.
    And to see it working...
    SQL> with t as (select 2 as x from dual union all
      2             select 3 from dual union all
      3             select 4 from dual union all
      4             select 5 from dual)
      5  --
      6  select mul(x)
      7  from t;
        MUL(X)
           120

  • SUM function issue

    Hi everyone,
    I have a problem with SUM function in SQL query on Oracle 11g database. Maybe you will be able to help me.
    Problem:
    I want to shows summary costs for shipments separately for each service provider and for each month they did the shipments.
    Data is stored in SHIPMENT AND SHIPMENT_COST table as shown below. The problem is that summary function I use sums base costs (marked as B in SHIPMENT_COST table) for each accessorial cost (marked as A in SHIPMENT_COST table). In example for shipment 10005031 we have 4 accessorial costs so it shows 6120 in BASE_COST column. I tried to use distinct in summary but then we have a problem with shipment id 201307133713_0383 which has 3 base costs equal to 221.54 so with distinct it will show 221.54 instead of 221.54x3.
    SHIPMENT table:
    START_TIME               SHIPMENT_GID               SERVPROV_GID
    2013-06-25                    10005031                         T222176
    2013-06-15                    201307133713_0383          T76180
    SHIPMENT_COST table:
    SHIPMENT_GID                        COST                                       COST_TYPE
    10005031                                 1530                                        B
    10005031                                  30.6                                        A
    10005031                                  120                                         A
    10005031                                  400                                         A
    10005031                                  100                                         A
    201307133713_0383                   221.54                                    B
    201307133713_0383                   221.54                                    B
    201307133713_0383                   221.54                                    B
    RESULT table:
    SHIPMENT_START_DATE
    SERVPROV
    BASE_COST
    CLAIM_COST
    06/2013
    T76180
    664.62
    null
    06/2013
    T222176
    6120
    650.6
    Query:
    SELECT DISTINCT TO_CHAR(SH.START_TIME,'MM/YYYY') AS SHIPMENT_START_DATE,
            SH.SERVPROV_GID AS SERVPROV,
            SUM(SHCOST.COST) AS BASE_COST,
            SUM(SHCOST_CLAIM.COST) AS CLAIM_COST
    FROM    SHIPMENT SH,
            SHIPMENT SHC
            LEFT OUTER JOIN SHIPMENT_COST SHCOST ON (SHC.SHIPMENT_GID = SHCOST.SHIPMENT_GID AND SHCOST.COST_TYPE = 'B'),
            SHIPMENT SHC_CLAIM
            LEFT OUTER JOIN SHIPMENT_COST SHCOST_CLAIM ON (SHC_CLAIM.SHIPMENT_GID = SHCOST_CLAIM.SHIPMENT_GID AND SHCOST_CLAIM.COST_TYPE = 'A')
    WHERE 1=1
            AND SHC.SHIPMENT_GID = SH.SHIPMENT_GID
            AND SHC_CLAIM.SHIPMENT_GID = SH.SHIPMENT_GID
            AND    SH.SHIPMENT_GID IN ('10005031','201307133713_0383')
            GROUP BY TO_CHAR(SH.START_TIME,'MM/YYYY'),
            SH.SERVPROV_GID
    Best Regards,
    Łukasz

    with SHIPMENT (START_TIME,SHIPMENT_GID,SERVPROV_GID) as
    select to_date('2013-06-25','yyyy-mm-dd'),'10005031','T222176' from dual union all
    select to_date('2013-06-15','yyyy-mm-dd'),'201307133713_0383','T76180' from dual
    SHIPMENT_COST(SHIPMENT_GID,COST,COST_TYPE)
    as
    select '10005031','1530','B' from dual union all
    select '10005031','30.6','A' from dual union all
    select '10005031','120','A' from dual union all
    select '10005031','400','A' from dual union all
    select '10005031','100','A' from dual union all
    select '201307133713_0383','221.54','B' from dual union all
    select '201307133713_0383','221.54','B' from dual union all
    select '201307133713_0383','221.54','B' from dual
    select *
      from (select to_char(t.START_TIME, 'mm/yyyy'),
                   t.SERVPROV_GID,
                   c.COST,
                   c.COST_TYPE
              from SHIPMENT t
              join SHIPMENT_COST c
                on t.SHIPMENT_GID = c.SHIPMENT_GID)
    pivot(sum(COST) for COST_TYPE in('A' CLAIM_COST,'B' BASE_COST))
    TO_CHAR(T.START_TIME,'MM/YYYY'
    SERVPROV_GID
    CLAIM_COST
    BASE_COST
    06/2013
    T76180
    664.62
    06/2013
    T222176
    650.6
    1530
    Ramin Hashimzade

  • Help with SUM function ??

    Hi,
    I am trying to build a SUM function into the following SELECT statement;
    SELECT   emp_code "EmployeeCode", trn_date "TransactionDate", project "ProjectCode",
    phase_code "PhaseCode", task_code "TaskCode", reg_hrs "RegularHoursAmt", rate_reg "RegularHoursRate", ot_hrs "OvertimeHoursAmt", rate_ot "OvertimeHoursRate"
    Currently when i do the extract to xls I manually compile the "RegularHoursAmt" and "RegularHoursRate" manually and it's quite a task. I'm sure it can be completed in teh SELECT but I'm not clear on how and it's been quite some time since my last foray into SQL. Any assistance appreciated.
    I need to sum "RegularHoursAmt" and "RegularHoursRate"
    per "EmployeeCode"
    by "TransactionDate"
    with unique combo of "ProjectCode", "PhaseCode", "TaskCode"
    Cheers, Peter

    Hi, Peter,
    PJS5 wrote:
    Thanks Frank for the quick response. Ok, here goes;
    The TABLES already exist and I am only pulling the data for the columns in my SELECT statement so no CREATE of INSERT as such.Post CREATE TABLE and INSERT statements so that the people who want to help you can re-create the problem and test their ideas.
    The data is in Oracle 10g 10.1.0.2.0Perfect!
    So you want totals that represent the entire day for a given employee.
    Yes, but rows are by the unique combo per employee of "ProjectCode", "PhaseCode", "TaskCode"So a row of output will represent a distinct combination of employee, day, ProjectCode, PhaseCode and TaskCode, and that one output row may correspond to more than one row of input; is that right?
    eg Tom works on 4 unique "ProjectCode/PhaseCode/TaskCode" efforts on "TransactionDate"What does "effort" mean here? If I could look at some actaul data (or actual fake data; don't post anything like real credit card numbers) and the results you want from that data, perhaps it would be clear.
    One of those unique "ProjectCode/PhaseCode/TaskCode" efforts however has 3 timesheet entries as he has added unique Descriptions of what his efforts were aimed at achieving.
    We are not extracting the Descriptions and thereby want to SUM those 3 timesheet entries into one row.
    Do you also want a total for each employee, over all days? No thanks
    Do you want a grand total for all employees and all days? No thanks
    Do you want the totals on the same output rows as your current reuslts? That would be handy
    If so, use the analytic SUM function. I'm not familiar with this
    Do you want separate rows for the the totals? That could helpPost the exact results you want from a small set of given data. It's fine to describe the results, as you did above, but describe them in addition to (not instead of) actually showing them.
    Does that make my questions easier to follow?It looks good, but without some sample data and the results you want from that data, I can't say for sure.
    Please post CREATE TABLE and INSERT statements (relevant columns only) for a little sample data, so that I (and the others who want to help you) can see exactly what your tables are like, and actually try our solutions. Simplify as much as possible. For example, if the data is actually coming from a multi-table join, but you already know how to join all the tables perfectly, then pretend all the data is in one table, and post CREATE TABLE and INSERT statements for that one table that looks sort of like your current result set. Post just enough data to show what you want to do. Based on what you've said so far, I'm guessing that 10 to 20 rows of raw data, resulting in 3 to 7 rows of output could give a nice example.
    Also, post the exact results you want from the sample data you post. Explain, with specific examples, how you get those results from that data.
    If parts of your desired output are optional (that is, if some parts "would be handy" or "could help") then post a couple of different sets of results from the same data, and explain, something like this:
    "What I'd really love to get for results is" ...
    but, if that makes things really complicated or inefficient, I don't absolutely need ... or ...,
    so I'd settle for these results: ..."
    I know it's a lot of work to post all this information, but it's really necessary. If I could help you without making you do all this, then I would. Unfortunately, I really don't have a good idea of where you're coming from or where you want to go.
    Edited by: Frank Kulash on Oct 19, 2010 8:01 PM

  • Dont want to use group by with sum function..

    Hi all
    I am using sum function but i dont want to use group by since my query give me following output which i dont want I want.
    0------------22---------(null)     Furniture
    0-----------     3700------     (null)     अनपेड बिल्स देणे
    15800-----14202-----(null)     Petty Cash
    (null)------     (null)------ 9109     Furniture
    (null)------ (null)------ 1789     Petty Cash
    (null)-------(null)------ 0     Checking In-Transfer
    I want like
    0------------22---------9109     Furniture
    0-----------     3700------     0     अनपेड बिल्स देणे
    15800-----14202-----1789     Petty Cash
    what should be the problem how I can handle the query my query is
    select  null as totalcr, null as totaldr, (sum(acct.amtsourcecr)-sum(acct.amtsourcedr)) as opening , ev.name as accountname
    from fact_acct acct right OUTER join  c_elementvalue ev on acct.account_id= ev.c_elementvalue_id
    where acct.dateacct < '01/04/2010'
    and ev.cr_account_base=2
    group by ev.name
    UNION
    select sum(acct.amtsourcecr) as totalcr, sum(acct.amtsourcedr) as totaldr, null as opening
    *,ev.name as accountname*
    from fact_acct acct right OUTER join  c_elementvalue ev on acct.account_id= ev.c_elementvalue_id
    where  acct.datetrx BETWEEN '01/04/2010' and '01/04/2010'
    group by  ev.name
    if I remove group by it shows me error .....not a single group by function ...
    please help me out ,,,
    thanking you

    This is one way you can do it without a group by:
    SQL> with t as
      2    (
      3      select 0 amt1, 22 amt2, null amt3, 'Furniture' tag from dual union all
      4      select 15800,14202,null, 'Petty Cash' from dual union all
      5      select null, null, 9109, 'Furniture' from dual union all
      6      select null, null, 1789, 'Petty Cash' from dual
      7    )
      8  select tag, amt1, amt2, amt3
      9  from
    10  (
    11    select sum(amt1) over (partition by tag) amt1
    12          ,sum(amt2) over (partition by tag) amt2
    13          ,sum(amt3) over (partition by tag) amt3
    14          ,first_value(t.tag) over (partition by t.tag order by rownum) tag
    15          ,row_number() over (partition by t.tag order by rownum) rn
    16    from t
    17  )
    18  where rn = 1
    19  /
    TAG              AMT1       AMT2       AMT3
    Furniture           0         22       9109
    Petty Cash      15800      14202       1789

  • Error when using SUM function in Excel template

    I am trying to use the XDO_METADATA to create a sum of a column from my XML data and I am getting the following error in the Template Viewer:
    [111412_104246459][][PROCEDURE] Log Level is changed to PROCEDURE
    [111412_104246553][oracle.xdo.common.xml.XSLTWrapper][ERROR] XSL error:
    Time: 0.125 sec.
    FO Formatting failed.
    <Line 317, Column 116>: XML-23029: (Error) FORG0001: invalid value for cast/constructor
    @Line 317 ==> <Cell Index="2" Style="R7C3" Field="XDO_?SUM_V_CR_MO_IDD1?"><xsl:value-of select="sum(.//G_CR_MST_D/V_CR_MO_IDD)"/>
    when I use:
    XDO_?SUM_V_CR_MO_IDD1?     <?sum(.//G_CR_MST_D/V_CR_MO_IDD)?>
    or
    [111412_104048508][][PROCEDURE] Log Level is changed to PROCEDURE
    [111412_104048554][oracle.xdo.common.xml.XSLTWrapper][ERROR] XSL error:
    Time: 0.078 sec.
    FO Formatting failed.
    <Line 317, Column 105>: XML-23029: (Error) FORG0001: invalid value for cast/constructor
    @Line 317 ==> <Cell Index="2" Style="R7C3" Field="XDO_?SUM_V_CR_MO_IDD1?"><xsl:value-of select="sum(.//V_CR_MO_IDD)"/>
    when I use:
    XDO_?SUM_V_CR_MO_IDD1?     <?sum(.//V_CR_MO_IDD)?>
    I believe the XSL to be correct because when I change it to a count it works and when I go into BI Publisher 11g and create the query in the data model and then create a summary from it, the summary is created.
    Can anyone help?

    I went back to basics and created reports (via EXCEL templates) like I was asking based on good old EMP and DEPT and I found exactly the same problems I was mentioning. I looked at the templates provided but they were not calculating totals, like me they were selecting them and then just displaying them on the page.
    Anyway, I have narrowed it down to the fact that when you do aggregates like sum(.//SAL) this works if you have a salary for every value. I did an outer join with DEPT so I did have empty rows and why I still experienced the problems.
    Basically XSL does not like adding (including using the sum function) values that effectively have nulls in them which is why I get the cast/constructor errors because it is trying to turn a NaN value to a number and does not (or cannot) do it.
    You need to either have a value in every row of your column (maybe possible by selecting nvl in your query) and make sure that you check the "create empty nodes" checkbox in the data model of BI Publisher.,
    the other solution is an xsl solution where you would have to make sure that you only added non null values and for that you would have to investigate xsl blogs.
    It is, by the way, why my count worked because it is just counting that the record exists it does not care what the element content is or isn't.
    Closing thread.

  • Issues using SUM Function in query

    I have pasted two queries Query1 (calculating counts for total_ships and ships_released) and Query2 (calculating the two same counts and then calculating SUM for total_shipments and I am having problem in this)
    Query 1:
    select  b.loc , b.week, b.vvalue2, b.Total_ships, nvl(a.up_date,'None') as datee , nvl( a.ships_rel_total,0) as Total_released
    from (
          SELECT l.loc  , sr1.vvalue1 as Week, sr.vvalue2 , to_char(ss.udate, 'YYYY-MM-DD') as up_date ,  count(distinct s.ship_id ) as ships_rel_total
          FROM ship s, loct l,
             ship_num sr1,  ship_num sr, ship_stat ss, ship_stat ss1
          WHERE ......
          Group by l.loc , sr1.vvalue1, sr.vvalue2 , to_char(ss.udate, 'YYYY-MM-DD')
          ) A,
    ( SELECT distinct l.loc  , sr1.vvalue1 as Week, sr.vvalue2 , count(s.ship_id ) as Total_Ships
          FROM ship s, loct l,
              ship_num sr1,  ship_num sr, ship_stat ss, ship_stat ss1
          WHERE ......
          Group by c.loc , c.week , c.vvalue2  ) B
    where a.loc (+) = b.loc
    and a.vvalue2  (+) = b.vvalue2
    order by b.loc, b.week , b.vvalue2,a.up_date; Query 1 Output:
    *OUTPUT*
    LOC         WEEK          VALUE2        TOTAL_SHIPS       DATEE         TOtAL_SHIPS_RELEASED
    AA          111              BB              12                  10-05-12            2
    AA          111              BB              12                  11-05-12            4
    AA          111              CC              2                    14-05-12            1Then I added sum function for total_ships and its not giving me result what I need :(
    Query 2:
    select  b.loc , b.week, b.vvalue2, b.sum_ships, nvl(a.up_date,'None') as datee , nvl( a.ships_rel_total,0) as Total_released
    from (
          SELECT l.loc  , sr1.vvalue1 as Week, sr.vvalue2 , to_char(ss.udate, 'YYYY-MM-DD') as up_date ,  count(distinct s.ship_id ) as ships_rel_total
          FROM ship s, loct l,
             ship_num sr1,  ship_num sr, ship_stat ss, ship_stat ss1
          WHERE ......
          Group by l.loc , sr1.vvalue1, sr.vvalue2 , to_char(ss.udate, 'YYYY-MM-DD')
    ) A,
    ( Select  c.loc, c.week , c.vvalue2 ,  sum(c.total_ships) sum_ships 
    from
        ( SELECT distinct l.loc  , sr1.vvalue1 as Week, sr.vvalue2 , count(s.ship_id ) as Total_Ships
          FROM ship s, loct l,
              ship_num sr1,  ship_num sr, ship_stat ss, ship_stat ss1
          WHERE ......
          Group by l.loc , sr1.vvalue1 , sr.vvalue2  ) C
    Group by c.loc , c.week , c.vvalue2  ) B
    where a.loc (+) = b.loc
    and a.vvalue2  (+) = b.vvalue2
    order by b.loc, b.week , b.vvalue2,a.up_date;  my query is giving me this :(
    Query 2 Output:
    LOC         WEEK          VALUE2        *SUM_SHIPS*       DATEE         TOtAL_SHIPS_RELEASED
    AA          111                BB              26                 10-05-12            2
    AA          111                BB              26                 11-05-12            4
    AA          111                CC              26                 14-05-12            1
    But I need a result like this:
    LOC         WEEK          VALUE2        SUM_SHIPS       DATEE         TOtAL_SHIPS_RELEASED
    AA          111                BB              14              10-05-12            2
    AA          111                BB              14              11-05-12            4
    AA          111                CC              14              14-05-12            1

    Hi,
    It sounds like you have a Fan Trap , where a one-to-many relationship is causing some items to be counted many times.
    The usual solution is to compute the aggregates before doing the one-to-many join. Analytic functions may make this simpler.
    Sorry, I can't show you exactly how to do it without the exact data.
    Post CREATE TABLE and INSERT statements for all tables involved, and also post the results you want from that data (if different from what you've already posted).
    Explain, using specific examples, how you get those results from that data.
    Simplify the problem as much as possible. If the problem only concerns the total_ships column, then only post the data needed to compute total_ships. This includes all the columns involved in the joins and GROUP BY clauses.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}

  • Crystal 2013 is casting a function with a date result as a string result, sometimes??

    I have an SQL Server function to take a JDEdwards numeric date and convert it to an SQL Date field. 
    CREATE FUNCTION [dbo].[date_ccyyddd_to_mmddyyyy]
      @JulianDate as Numeric(18,0)
    RETURNS Date
    AS
    BEGIN
    Declare @ResultDate as Date
    Set @ResultDate = DATEADD(YEAR, @JulianDate / 1000 + 1899, Cast('01/01/0001' as Date))
    Set @ResultDate = DATEADD(Day, @JulianDate % 1000 -1, @ResultDate)
    RETURN @ResultDate
    END
    In many query based reports we have used the function.  It works quite nicely for all but one user.  For this one user Crystal is casting the date result as a string, it will then display as a yyyy-mm-dd format instead of his default mm/dd/yyyy short date format.  It would generally be ok but since it is typed as a string if the user exports the results to excel it is not recognizing the column as a date either.  The strange piece of the equation is that if the user saves the report to the enterprise server and I open it, go to edit the SQL command, do nothing, close the edit box, it gives me the unmapped fields wizard where I can fix the report.  Thus when I open or generate a new report with this function it "knows" the result is a date but with a specific user it sees the result as a string.
    Has anyone had a similar situation or can lead me in the correct direction to fix this?  Unfortunately, this user is our power user, he writes more reports than anyone else.  It appeared as a problem when we upgraded from Crystal Enterprise 2008 to 2013.
    Current work around for user is to use a crystal CDate() function on the report side but I would like to get the correct solution.
    Any assistance appreciated,

    To add to Dell's suggestion:
    If OLE DB then use:
    MS SQL 2005 - OLE DB Provider
    MS SQL 2008 - SQL Native 10
    MS SQL 2012 - SQL Native 11
    MS SQL 2013 - SQL Native 11
    If ODBC then use:
    MS SQL 2005 - SQL Native
    MS SQL 2008 - SQL Native 10
    MS SQL 2012 - SQL Native 11
    MS SQL 2013 - SQL Native 11
    - Ludek
    Senior Support Engineer AGS Product Support, Global Support Center Canada
    Follow us on Twitter

  • Strange error in SUM function in XI

    Hi geeks,
    We are encountering a strange issue in SUM functionality in XI.
    The Scenario is :
    We have a pipe delimited source file and INVOIC01 idoc as target.  each line in the source file will create a segment E1EDP01 in the target IDOC.
    All the values given in the file should be summed and mapped to E1EDS01 segment in the idoc.
    In one such strange case the sum of the values generated by the SUM function in XI is 2 cents lesser what we manually calculate using Calculator or Excel . There are about 100+ items in the file.  This not the case always it happens once in a while.
    Have any of you faced such strange errors. If yes please throw some light on the solution for this issue.
    Thanks,
    Noorul

    Hi folks,
    Thanks for your help. I solved this by writing my own code
    double sum = 0;
    String value;
    for (int i= 0; i< a.length; i++)
    sum = sum + Double.parseDouble(a<i>);
    value = Double.toString(sum);
    BigDecimal  bg1 = new BigDecimal(value);
    BigDecimal bg2 = bg1.setScale(2, BigDecimal.ROUND_HALF_DOWN);
    result.addValue(bg2.toString());

  • Flex 4.5.1 Setting VideoPlayer source to null when it is already null results in a runtime error

    I moved my project from Flex 4.1 to Flex 4.5.1 and I noticed that setting VideoPlayer source to null when it is already null results in a runtime error. The same thing applies to the case where you specified as a source url some invalid location (no video found there) and then you try to set the source to null.
    Here is the error:
    TypeError: Error #1009: Cannot access a property or method of a null object reference.
        at spark.components::VideoDisplay/cleanUpSource()[E:\dev\4.5.1\frameworks\projects\spark\src \spark\components\VideoDisplay.as:1956]
        at spark.components::VideoDisplay/setUpSource()[E:\dev\4.5.1\frameworks\projects\spark\src\s park\components\VideoDisplay.as:1609]
        at spark.components::VideoDisplay/set source()[E:\dev\4.5.1\frameworks\projects\spark\src\spark\components\VideoDisplay.as:1073 ]
        at spark.components::VideoPlayer/set source()[E:\dev\4.5.1\frameworks\projects\spark\src\spark\components\VideoPlayer.as:1362]
    The problem is that in the VideoDisplay cleanUpSource function, in some of the cases there properties on the videoObject are modified like this:
    videoPlayer.displayObject.visible = true;
    without checking if displayObject is null which is done in the rest of the videoDisplay functions.
    So when it reaches this line: videoPlayer.displayObject.visible = true; it results in a runtime error.
    Is this supposed to work this way now ? I didn't have this problem on Flex 4.1. Not sure if it is a bug, but if it is please report it, I don't have the time right now to be checking in on this.
    I fixed it by checking if the source is set, of course... (that won't help me in cases where I provide a wrong or missing video url by mistake.. so it is important to be fixed!)
    F

    Hi
    I found the same error displaying video on flex !
    in my simple code, i have :
    videoInfoDataVideo.source = videoName;
    the full error is :
    TypeError: Error #1009: Il est impossible d'accéder à la propriété ou à la méthode d'une référence d'objet nul.
              at spark.components::VideoDisplay/cleanUpSource()[E:\dev\4.5.1\frameworks\projects\spark\src \spark\components\VideoDisplay.as:1956]
              at spark.components::VideoDisplay/setUpSource()[E:\dev\4.5.1\frameworks\projects\spark\src\s park\components\VideoDisplay.as:1609]
              at spark.components::VideoDisplay/set source()[E:\dev\4.5.1\frameworks\projects\spark\src\spark\components\VideoDisplay.as:1073 ]
              at spark.components::VideoPlayer/set source()[E:\dev\4.5.1\frameworks\projects\spark\src\spark\components\VideoPlayer.as:1362]
              at Function/item/private:updateVideo/anonymous/resultGetVideo()[C:\Users\randev\Adobe Flash Builder 4.5\visurbaCMS\src\item.mxml:800]
              at flash.events::EventDispatcher/dispatchEventFunction()
              at flash.events::EventDispatcher/dispatchEvent()
              at HTTPOperation/http://www.adobe.com/2006/flex/mx/internal::dispatchRpcEvent()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\http\HTTPService.as:993]
              at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::resultHandler()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\AbstractInvoker.as:318]
              at mx.rpc::Responder/result()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\Responder.as:5 6]
              at mx.rpc::AsyncRequest/acknowledge()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\AsyncR equest.as:84]
              at DirectHTTPMessageResponder/completeHandler()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\ messaging\channels\DirectHTTPChannel.as:451]
              at flash.events::EventDispatcher/dispatchEventFunction()
              at flash.events::EventDispatcher/dispatchEvent()
              at flash.net::URLLoader/onComplete()
    did you solve the problem or someone else?
    Thanks

Maybe you are looking for