DAX Sum of children

Hi guys,
I'm working on a SSAS 2012 Tabular Model and am running into some difficulties with one of my measures.
What my setup looks like:
Dim Time hierarchy: Year - Season (Quarter) - Month
Fact Forecast: Account - Material - Month - Forecast Quantity - Bookings Quantity
I now need to calculate the Forecast accuracy but scoped to the period shown.
On a Month level, this is working by doing the following:
Forecast Accuracy:=1- (SUMX('Forecast',ABS(Forecast Quantity - Bookings Quantity))/Forecast Quantity)
My problem here starts on a higher grain, like Season or Year.
The biggest problem here is this part:
ABS(Forecast Quantity - Bookings Quantity)
Both quantities should first be aggregated to Account - Material - <Period> level and then subtracted from eachother but I'm not able to get this to work.
Has anyone encountered this before because I don't have a clue how to solve this after crawling the web for half a day...
Kind regards,
Jan

Hi Marco,
Thanks for your response, I first tried implementing the Forecast Error by slightly altering the measure as you suggested:
Forecast Error:=
SUMX (
VALUES ( Time[Business Season] ),
CALCULATE (
ABS (
SUM ( [Forecast Qty] ) - SUM ( [Bkgs Qty])
However, this does not give me the correct information either...
On the lowest level this works as expected like my measures tried beforehand.
Once I start rolling up, the calculations are happening incorrectly.
For example, in the image below, for the account *test* it gives Forecast Error 76450 total, but should return 482152 which is the sum of all the values on the lowest level (entire range selected in Excel here for demonstration).
Any thoughts on this?
Kind regards,
Jan

Similar Messages

  • Update parent status based on all children status and sum of children amount.

    Hi,
    I need to write sql query for the following scenarios.
    We have 3 financial systems (sys1, sys2, sys3) where a same transaction gets entered independently into each system OR entered into one and exported to the other system. Transaction need not be in all 3 systems.
    We need to create reconcile report to see the status of transaction and display if it is reconciled or not. For this, in our stored procedure we are pulling data from 3 systems into temp tables and using CTE and other logic marking each transaction status
    in each system temp table. One of the systems (eg sys1), we made it as source.
    Sys1 temp table has both parent and child records and are distinguished using type. Sys2 and sys3 has only children records.  When report is created, we are showing parent  from sys1 temp table and
    children from new temp table where children status is updated based on availability of it in all 3 systems.
    DECLARE
    @sys1 TABLE
    ID int,
    childID varchar(20),
    ParentID varchar(20),
    RecType decimal(3,0),
    SettleDate smalldatetime,
    Principal money,
    Sys3ID varchar(16)
    NULL,
    Sys2ID int
    NULL,
                            Status varchar(25) NULL
    DECLARE
    @sys2 TABLE
    TxID int
    PRIMARY KEY NOT
    NULL,
    CommonTransactionID varchar(16),
    SettleDate smalldatetime,
    Par money,
    Sys3ID varchar(16) NULL,
    Sys1ChildID,
    Sys1ParentID bigint
    DECLARE
    @sys3 TABLE
    Sys3ID varchar(16),
    REFERENCE
    varchar(16),
    VALUE_DATE datetime,
    DIRECTION char(1),
    AMOUNT money,
    RecSource varchar(2)
    Insert Into @sys1 (ID, childID, ParentID, RecType, SettleDate, Principal)
    Select 172876, 217955, 217954, 100, ‘2015-03-01’, 100.00
    Union
    Select 172877, 217956, 217955, 50, ‘2015-03-01’, 15.00
    Union
    Select 172878, 217957, 217955, 50, ‘2015-03-01’, 25.00
    union
    Select 172879, 217958, 217955, 50, ‘2015-03-01’, 10.00
    Union
    Select 172880, 217959, 217955, 50, ‘2015-03-01’, 10.00
    union
    Select 172881, 217960, 217955, 50, ‘2015-03-01’, 40.00
    Insert Into @sys2(TxID, Sys1ID, settleDate, Par)
    Select 4336620, 217956, ‘2015-03-01’, 15.00
    Union
    Select 4336621, 217957, ‘2015-03-01’, 25.00
    union
    Select 4336613, 217958, ‘2015-03-01’, 10.00
    Union
    Select 4336614, 217959, ‘2015-03-01’, 10.00
    union
    Select 4336615, 217960, ‘2015-03-01’, 40.00
    Insert into @sys3(Sys3ID, Reference, Value_Date, Direction, Amount)
    Select 1, ‘5654471 4336620’, ‘2015-03-01’, ‘O’, 15.00
    Union
    Select 2, ‘5654481 4336621’, ‘2015-03-01’, 'O',25.00
    Union
    Select 3, ‘5654491 4336613’, ‘2015-03-01’, 'O',10.00
    Union
    Select 4, ‘5654501 4336614’, ‘2015-03-01’, 'O',10.00
    Union
    Select 5, ‘5654511 4336615’, ‘2015-03-01’, 'O', 40.00
    After going thru lot of other logic, final temp table will have only children with status assigned. The above temp table data is only for 1 scenario.
    The following are status of children.
    This is how status of children is determined:
    Not Settled – All child records start as Not settled in temp tables.
    Settled – when record exists in sys3 and other criteria is met.
    Partially settled – record exists in sys3 and either in sys1 or sys2 or other criteria is not met.
    Reconciled – child record should exist in all 3 systems and all criteria is match
    Mismatched – record has wrong amount when compared in any of 2 systems.
    **************** My Part below*******************
    My part is to update the status of parent based on children status and parent amount must match sum of child amounts. If amounts don’t match, then leave the status of parent as null.
    Determining the status of parent:
    Not Settled – None of children has yet settled.
    Settled – All children are settled.
    Partially settled – some of children are as settled OR 1+ children are partially settled.
    Reconciled – All children are reconciled.
    Partially Reconciled – some children are partially reconciled.
    Null – 1 or more childen has a status of mismatched.
    AND sum of children amount should match parent amount
    How can I update the status of parent based on all children and sum of amount of children equal to parent amount.
    Thanks,
    Spunny

    >> We have 3 financial systems (sys1, sys2, sys3) where the same transaction gets entered independently into each system OR entered into one and exported to the other system. Transaction need not be in all 3 systems. <<
    Your design is fundamentally wrong. In RDBMS, we want to have one fact, one way, in one place in the schema. The goal of all databases is to remove redundancy, not increase it. This not just SQL; this was true for hierarchical and network databases before them! 
    >> We need to create reconcile report to see the status of transaction and display if it is reconciled or not. For this, in our stored procedure we are pulling data from 3 systems into temp tables and using CTE and other logic marking each transaction
    status in each system temp table. One of the systems (eg sys1), we made it as source. <<
    You have re-invent the worst of 1970's file processing, but you want to use a temp table instead of scratch tape. This is not RDBMS or good SQL. 
    >> Sys1 temp table has both parent [sic] and child [sic] records [sic] and are distinguished using type. Sys2 and sys3 has only children [sic] records [sic]. When report is created, we are showing parent from sys1 temp table and children from new temp
    table where children [sic] status is updated based on availability of it in all 3 systems. <, 
    The terms “child” and “parent” are not part of RDBMS. They come from network databases. You are building fake pointer chains we do have referenced and referencing tables. Or do you mean to model weak and strong entities? Where is the DRI actions?
    These things are not tables! They have no keys, so they are called (garbage) piles. But even the garbage is wrong. There is no generic “id” in RDBMS; it has to be “<something in particular>_id” to be valid. Since you do not do math on it, it should not
    be a numeric. 
    A “rec_type” is a nominal scale, so it cannot be a numeric either! Likewise, we have no generic “status”, but a status is state of being so it has to have a temporal dimension. And did you know that “reference” is a reserved word in SQL as well as another ISO-11179
    violation. 
    The MONEY data type does not do correct math. Google it! It is another Sybase left-over that nobody should ever use. 
    Finally, you used the old Sybase INSERT INTO ..SELECT..), .. disaster instead of the ANSI/ISO Standard VALUES table constructor. 
    >> This is how status of children [sic] is determined: ..
    My part is to update the status of parent [sic] based on children [sic] status and parent [sic] amount must match sum of child [sic] amounts.<<
    Your narrative describes what Tom Johnston called a Non-Normal Form Redundancy. We do not put summary data in the strong entity; another basic data modeling principle. We build a VIEW that gives us the current summary. Your mindset is still in punch cards and
    magnetic tape files. 
    "No matter how far you have gone down the wrong road, turn around!" -- Turkish proverb. 
    Can you start over and do it right? 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Sum of children in a hierarchy

    I've got a query I can't wrap my head around - maybe you can help...
    I've got a table of ids and amounts and another table which gives me the hierarchy of the ids by using connect by prior on id and parent_id (two different tables). Given a list of ids as input parameter, I need to be able to generate output that lists each id and the sum of the id and all it's children's amounts. The hierarchy can be multi levels. I'll try to explain by example the input and output:
    Input:
    T1_id, T1_amt
    1, 5
    2, 10
    3, 5
    T2_id, T2_parent_id, T2.name
    1, null, "A"
    2, 1, "B"
    3, null, "C"
    Desired output:
    A, 15 (sum of ids 1+2's values)
    B, 10
    C, 5
    I'm not posting the query I'm trying to get working because it's so fundamentally not working that it's pointless - but I will say that I'm trying to use a subquery which does a connect by prior to determine the child ids of the row id it's joining with. There must be another, perhaps more simple way, that isn't jumping out at me.
    Thanks in advance.

    Something like this?
    SQL> with t1 as (
      2   select 1 T1_id,5 T1_amt from dual  union all
      3   select 2,10 from dual     union all
      4   select 3,5 from dual
      5  ),
      6  t2 as (
      7   select 1 T2_id,null T2_parent_id,'A' T2_name from dual  union all
      8   select 2,1,'B' from dual  union all
      9   select 3,null,'C' from dual
    10  )
    11  -- End test data
    12  select root,sum(t1_amt) amt from (
    13  select t1.t1_amt,T2_id,T2_parent_id,T2_name, connect_by_root(t2_name) root
    14  from t1,t2
    15  where t1.t1_id = t2.t2_id
    16  connect by prior t2_id = t2_parent_id
    17  )
    18  group by root
    19  order by root
    20  ;
    R        AMT
    A         15
    B         10
    C          5However, there are a lot of examples to this kind of calculation, you may find many different solutions if you search a little bit.
    Best regards
    Maxim
    Edited by: Maxim Demenko on Jul 13, 2009 9:17 PM
    I meant of course - here, on this forum - regarding the search

  • DAX: Sum unique values across columns

    Hello,
    How do I sum unique values of "Yes" across my columns in DAX?
    It should look like this with [Total Yes] being my calculated column:
    Name
    January
    February
    March
    Total Yes
    Bob
    Yes
    Yes
    No
    2
    Jim
    No
    Yes
    No
    1
    Mark
    No
    No
    Yes
    1
    Thanks!
    ~UG

    Simply this
    =IF([January]="Yes",1,0)+IF([February]="Yes",1,0)+IF([March]="Yes",1,0)
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Need help in member formula

    Hi All,
    i need a help in memberformula
    i've two sparce dimenions as below:
    Dim1:
    A
    --B
    --C
    Dim2:
    a
    ---b
    ---c
    d
    ---e
    ---f
    i need to write member formula on C from Dim1 if member is parent level member from dim2 then its to sum up with its childen values against B from dim1.
    If member is parent level memer from dim2 ex:d
    C->d = B->e + B->f
    Thanks in advance,
    Kiran
    Edited by: kirannch on Oct 16, 2012 4:16 PM

    Hi Tim,
    Thanks for your response.
    I'm using all HFM dimensions in Essbase Except Cust2 and Cust4.
    In my outline Account, Period and Year are dense dimensions and rest are Sparse.
    i'm comparing the data at parenttot with usdtot, contr as we are using flat members.
    Below script is not updating any parent level value of USDTOT combination. i'm running the aggregation with exclude elim data before executing this calc script.
    USDTOT,Contr are sparse dimension members and Entity also sparse.
    Please can you help on the below scripts.
    SET CALCPARALLEL 3;
    SET AGGMISSG OFF;
    SET FRMLBOTTOMUP OFF;
    SET CACHE HIGH;
    SET LOCKBLOCK HIGH;
    EXCLUDE ( "Elim")
    /Calculation "USDTOT" at Parent level of Entity Dimension with sum of children same parent entity with Contr member */
    SET UPDATECALC OFF;
    FIX("ACT","FY12")
    "USDTOT"(
    IF(NOT @ISLEV("ENTITY", 0));
    "USDTOT" = @SUM(@CHILDREN(@CURRMBR("ENTITY"->"Contr")));
    ENDIF;);
    ENDFIX;
    ENDEXCLUDE;
    Thanks in advance,
    Kiran
    Edited by: kirannch on Oct 24, 2012 7:38 PM

  • Very Slow Query with CTE inner join

    I have 2 tables (heavily simplified here to show relevant columns):
    CREATE TABLE tblCharge
    (ChargeID int NOT NULL,
    ParentChargeID int NULL,
    ChargeName varchar(200) NULL)
    CREATE TABLE tblChargeShare
    (ChargeShareID int NOT NULL,
    ChargeID int NOT NULL,
    TotalAmount money NOT NULL,
    TaxAmount money NULL,
    DiscountAmount money NULL,
    CustomerID int NOT NULL,
    ChargeShareStatusID int NOT NULL)
    I have a very basic View to Join them:
    CREATE VIEW vwBASEChargeShareRelation as
    Select c.ChargeID, ParentChargeID, s.CustomerID, s.TotalAmount, isnull(s.TaxAmount, 0) as TaxAmount, isnull(s.DiscountAmount, 0) as DiscountAmount
    from tblCharge c inner join tblChargeShare s
    on c.ChargeID = s.ChargeID Where s.ChargeShareStatusID < 3
    GO
    I then have a view containing a CTE to get the children of the Parent Charge:
    ALTER VIEW [vwChargeShareSubCharges] AS
    WITH RCTE AS
    SELECT ParentChargeId, ChargeID, 1 AS Lvl, ISNULL(TotalAmount, 0) as TotalAmount, ISNULL(TaxAmount, 0) as TaxAmount,
    ISNULL(DiscountAmount, 0) as DiscountAmount, CustomerID, ChargeID as MasterChargeID
    FROM vwBASEChargeShareRelation Where ParentChargeID is NULL
    UNION ALL
    SELECT rh.ParentChargeID, rh.ChargeID, Lvl+1 AS Lvl, ISNULL(rh.TotalAmount, 0), ISNULL(rh.TaxAmount, 0), ISNULL(rh.DiscountAmount, 0) , rh.CustomerID
    , rc.MasterChargeID
    FROM vwBASEChargeShareRelation rh
    INNER JOIN RCTE rc ON rh.PArentChargeID = rc.ChargeID and rh.CustomerID = rc.CustomerID
    Select MasterChargeID as ChargeID, CustomerID, Sum(TotalAmount) as TotalCharged, Sum(TaxAmount) as TotalTax, Sum(DiscountAmount) as TotalDiscount
    from RCTE
    Group by MasterChargeID, CustomerID
    GO
    So far so good, I can query this view and get the total cost for a line item including all children.
    The problem occurs when I join this table. The query:
    Select t.* from vwChargeShareSubCharges t
    inner join
    tblChargeShare s
    on t.CustomerID = s.CustomerID
    and t.MasterChargeID = s.ChargeID
    Where s.ChargeID = 1291094
    Takes around 30 ms to return a result (tblCharge and Charge Share have around 3.5 million records).
    But the query:
    Select t.* from vwChargeShareSubCharges t
    inner join
    tblChargeShare s
    on t.CustomerID = s.CustomerID
    and t.MasterChargeID = s.ChargeID
    Where InvoiceID = 1045854
    Takes around 2 minutes to return a result - even though the only charge with that InvoiceID is the same charge as the one used in the previous query.
    The same thing occurs if I do the join in the same query that the CTE is defined in.
    I ran the execution plan for each query. The first (fast) query looks like this:
    The second(slow) query looks like this:
    I am at a loss, and my skills at decoding execution plans to resolve this are lacking.
    I have separate indexes on tblCharge.ChargeID, tblCharge.ParentChargeID, tblChargeShare.ChargeID, tblChargeShare.InvoiceID, tblChargeShare.ChargeShareStatusID
    Any ideas? Tested on SQL 2008R2 and SQL 2012

    >> The database is linked [sic] to an established app and the column and table names can't be changed. <<
    Link? That is a term from pointer chains and network databases, not SQL. I will guess that means the app came back in the old pre-RDBMS days and you are screwed. 
    >> I am not too worried about the money field [sic], this is used for money and money based calculations so the precision and rounding are acceptable at this level. <<
    Field is a COBOL concept; columns are totally different. MONEY is how Sybase mimics the PICTURE clause that puts currency signs, commas, period, etc in a COBOL money field. 
    Using more than one operation (multiplication or division) on money columns will produce severe rounding errors. A simple way to visualize money arithmetic is to place a ROUND() function calls after 
    every operation. For example,
    Amount = (Portion / total_amt) * gross_amt
    can be rewritten using money arithmetic as:
    Amount = ROUND(ROUND(Portion/total_amt, 4) * 
    gross_amt, 4)
    Rounding to four decimal places might not seem an 
    issue, until the numbers you are using are greater 
    than 10,000. 
    BEGIN
    DECLARE @gross_amt MONEY,
     @total_amt MONEY,
     @my_part MONEY,
     @money_result MONEY,
     @float_result FLOAT,
     @all_floats FLOAT;
     SET @gross_amt = 55294.72;
     SET @total_amt = 7328.75;
     SET @my_part = 1793.33;
     SET @money_result = (@my_part / @total_amt) * 
    @gross_amt;
     SET @float_result = (@my_part / @total_amt) * 
    @gross_amt;
     SET @Retult3 = (CAST(@my_part AS FLOAT)
     / CAST( @total_amt AS FLOAT))
     * CAST(FLOAT, @gross_amt AS FLOAT);
     SELECT @money_result, @float_result, @all_floats;
    END;
    @money_result = 13525.09 -- incorrect
    @float_result = 13525.0885 -- incorrect
    @all_floats = 13530.5038673171 -- correct, with a -
    5.42 error 
    >> The keys are ChargeID(int, identity) and ChargeShareID(int, identity). <<
    Sorry, but IDENTITY is not relational and cannot be a key by definition. But it sure works just like a record number in your old COBOL file system. 
    >> .. these need to be int so that they are assigned by the database and unique. <<
    No, the data type of a key is not determined by physical storage, but by logical design. IDENTITY is the number of a parking space in a garage; a VIN is how you identify the automobile. 
    >> What would you recommend I use as keys? <<
    I do not know. I have no specs and without that, I cannot pull a Kabbalah number from the hardware. Your magic numbers can identify Squids, Automobile or Lady Gaga! I would ask the accounting department how they identify a charge. 
    >> Charge_Share_Status_ID links [sic] to another table which contains the name, formatting [sic] and other information [sic] or a charge share's status, so it is both an Id and a status. <<
    More pointer chains! Formatting? Unh? In RDBMS, we use a tiered architecture. That means display formatting is in a presentation layer. A properly created table has cohesion – it does one and only one data element. A status is a state of being that applies
    to an entity over a period time (think employment, marriage, etc. status if that is too abstract). 
    An identifier is based on the Law of Identity from formal logic “To be is to be something in particular” or “A is A” informally. There is no entity here! The Charge_Share_Status table should have the encoded values for a status and perhaps a description if
    they are unclear. If the list of values is clear, short and static, then use a CHECK() constraint. 
    On a scale from 1 to 10, what color is your favorite letter of the alphabet? Yes, this is literally that silly and wrong. 
    >> I understand what a CTE is; is there a better way to sum all children for a parent hierarchy? <<
    There are many ways to represent a tree or hierarchy in SQL.  This is called an adjacency list model and it looks like this:
    CREATE TABLE OrgChart 
    (emp_name CHAR(10) NOT NULL PRIMARY KEY, 
     boss_emp_name CHAR(10) REFERENCES OrgChart(emp_name), 
     salary_amt DECIMAL(6,2) DEFAULT 100.00 NOT NULL,
     << horrible cycle constraints >>);
    OrgChart 
    emp_name  boss_emp_name  salary_amt 
    ==============================
    'Albert'    NULL    1000.00
    'Bert'    'Albert'   900.00
    'Chuck'   'Albert'   900.00
    'Donna'   'Chuck'    800.00
    'Eddie'   'Chuck'    700.00
    'Fred'    'Chuck'    600.00
    This approach will wind up with really ugly code -- CTEs hiding recursive procedures, horrible cycle prevention code, etc.  The root of your problem is not knowing that rows are not records, that SQL uses sets and trying to fake pointer chains with some
    vague, magical non-relational "id".  
    This matches the way we did it in old file systems with pointer chains.  Non-RDBMS programmers are comfortable with it because it looks familiar -- it looks like records and not rows.  
    Another way of representing trees is to show them as nested sets. 
    Since SQL is a set oriented language, this is a better model than the usual adjacency list approach you see in most text books. Let us define a simple OrgChart table like this.
    CREATE TABLE OrgChart 
    (emp_name CHAR(10) NOT NULL PRIMARY KEY, 
     lft INTEGER NOT NULL UNIQUE CHECK (lft > 0), 
     rgt INTEGER NOT NULL UNIQUE CHECK (rgt > 1),
      CONSTRAINT order_okay CHECK (lft < rgt));
    OrgChart 
    emp_name         lft rgt 
    ======================
    'Albert'      1   12 
    'Bert'        2    3 
    'Chuck'       4   11 
    'Donna'       5    6 
    'Eddie'       7    8 
    'Fred'        9   10 
    The (lft, rgt) pairs are like tags in a mark-up language, or parens in algebra, BEGIN-END blocks in Algol-family programming languages, etc. -- they bracket a sub-set.  This is a set-oriented approach to trees in a set-oriented language. 
    The organizational chart would look like this as a directed graph:
                Albert (1, 12)
        Bert (2, 3)    Chuck (4, 11)
                       /    |   \
                     /      |     \
                   /        |       \
                 /          |         \
            Donna (5, 6) Eddie (7, 8) Fred (9, 10)
    The adjacency list table is denormalized in several ways. We are modeling both the Personnel and the Organizational chart in one table. But for the sake of saving space, pretend that the names are job titles and that we have another table which describes the
    Personnel that hold those positions.
    Another problem with the adjacency list model is that the boss_emp_name and employee columns are the same kind of thing (i.e. identifiers of personnel), and therefore should be shown in only one column in a normalized table.  To prove that this is not
    normalized, assume that "Chuck" changes his name to "Charles"; you have to change his name in both columns and several places. The defining characteristic of a normalized table is that you have one fact, one place, one time.
    The final problem is that the adjacency list model does not model subordination. Authority flows downhill in a hierarchy, but If I fire Chuck, I disconnect all of his subordinates from Albert. There are situations (i.e. water pipes) where this is true, but
    that is not the expected situation in this case.
    To show a tree as nested sets, replace the nodes with ovals, and then nest subordinate ovals inside each other. The root will be the largest oval and will contain every other node.  The leaf nodes will be the innermost ovals with nothing else inside them
    and the nesting will show the hierarchical relationship. The (lft, rgt) columns (I cannot use the reserved words LEFT and RIGHT in SQL) are what show the nesting. This is like XML, HTML or parentheses. 
    At this point, the boss_emp_name column is both redundant and denormalized, so it can be dropped. Also, note that the tree structure can be kept in one table and all the information about a node can be put in a second table and they can be joined on employee
    number for queries.
    To convert the graph into a nested sets model think of a little worm crawling along the tree. The worm starts at the top, the root, makes a complete trip around the tree. When he comes to a node, he puts a number in the cell on the side that he is visiting
    and increments his counter.  Each node will get two numbers, one of the right side and one for the left. Computer Science majors will recognize this as a modified preorder tree traversal algorithm. Finally, drop the unneeded OrgChart.boss_emp_name column
    which used to represent the edges of a graph.
    This has some predictable results that we can use for building queries.  The root is always (left = 1, right = 2 * (SELECT COUNT(*) FROM TreeTable)); leaf nodes always have (left + 1 = right); subtrees are defined by the BETWEEN predicate; etc. Here are
    two common queries which can be used to build others:
    1. An employee and all their Supervisors, no matter how deep the tree.
     SELECT O2.*
       FROM OrgChart AS O1, OrgChart AS O2
      WHERE O1.lft BETWEEN O2.lft AND O2.rgt
        AND O1.emp_name = :in_emp_name;
    2. The employee and all their subordinates. There is a nice symmetry here.
     SELECT O1.*
       FROM OrgChart AS O1, OrgChart AS O2
      WHERE O1.lft BETWEEN O2.lft AND O2.rgt
        AND O2.emp_name = :in_emp_name;
    3. Add a GROUP BY and aggregate functions to these basic queries and you have hierarchical reports. For example, the total salaries which each employee controls:
     SELECT O2.emp_name, SUM(S1.salary_amt)
       FROM OrgChart AS O1, OrgChart AS O2,
            Salaries AS S1
      WHERE O1.lft BETWEEN O2.lft AND O2.rgt
        AND S1.emp_name = O2.emp_name 
       GROUP BY O2.emp_name;
    4. To find the level and the size of the subtree rooted at each emp_name, so you can print the tree as an indented listing. 
    SELECT O1.emp_name, 
       SUM(CASE WHEN O2.lft BETWEEN O1.lft AND O1.rgt 
       THEN O2.sale_amt ELSE 0.00 END) AS sale_amt_tot,
       SUM(CASE WHEN O2.lft BETWEEN O1.lft AND O1.rgt 
       THEN 1 ELSE 0 END) AS subtree_size,
       SUM(CASE WHEN O1.lft BETWEEN O2.lft AND O2.rgt
       THEN 1 ELSE 0 END) AS lvl
      FROM OrgChart AS O1, OrgChart AS O2
     GROUP BY O1.emp_name;
    5. The nested set model has an implied ordering of siblings which the adjacency list model does not. To insert a new node, G1, under part G.  We can insert one node at a time like this:
    BEGIN ATOMIC
    DECLARE rightmost_spread INTEGER;
    SET rightmost_spread 
        = (SELECT rgt 
             FROM Frammis 
            WHERE part = 'G');
    UPDATE Frammis
       SET lft = CASE WHEN lft > rightmost_spread
                      THEN lft + 2
                      ELSE lft END,
           rgt = CASE WHEN rgt >= rightmost_spread
                      THEN rgt + 2
                      ELSE rgt END
     WHERE rgt >= rightmost_spread;
     INSERT INTO Frammis (part, lft, rgt)
     VALUES ('G1', rightmost_spread, (rightmost_spread + 1));
     COMMIT WORK;
    END;
    The idea is to spread the (lft, rgt) numbers after the youngest child of the parent, G in this case, over by two to make room for the new addition, G1.  This procedure will add the new node to the rightmost child position, which helps to preserve the idea
    of an age order among the siblings.
    6. To convert a nested sets model into an adjacency list model:
    SELECT B.emp_name AS boss_emp_name, E.emp_name
      FROM OrgChart AS E
           LEFT OUTER JOIN
           OrgChart AS B
           ON B.lft
              = (SELECT MAX(lft)
                   FROM OrgChart AS S
                  WHERE E.lft > S.lft
                    AND E.lft < S.rgt);
    7. To find the immediate parent of a node: 
    SELECT MAX(P2.lft), MIN(P2.rgt)
      FROM Personnel AS P1, Personnel AS P2
     WHERE P1.lft BETWEEN P2.lft AND P2.rgt 
       AND P1.emp_name = @my_emp_name;
    I have a book on TREES & HIERARCHIES IN SQL which you can get at Amazon.com right now. It has a lot of other programming idioms for nested sets, like levels, structural comparisons, re-arrangement procedures, etc. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Custom subtotal

    Hello GURUs
    Here is my issue. No one has been able to solve this.
    I have two columns: Parent Company Limit (column A) , and Child Company Limit (column B)
    The subtotal of column B is actually not the REAL limit of the Parent (the sum of children don't equal the parent) ....
    So, I need a way to have the subtotal of column B POINT to the average of column A.
    Example:
    Database:
    Company,A,B
    MSTF,10000,50
    MSTF,10000,10
    MSTF,10000,40
    How I need it in Report
    Company,Limit
    MSTF,50
    MSTF,10
    MSTF,40
    Subtotal for MSTF,10000
    This was doable in MicroStrategy but haven't been able to reproduce in OBIEE.
    P.S.: I'm not looking for a level-based metric.
    THANKS

    HI....
    You cannot use Subtotal for this...
    USe Union reporting.
    in the first Union
    first Union : 1 , Company , B
    2nd Union : 2 , Distinct Company , Distinct A
    Here in the report, Sort by column 1 asc.
    You will get desired result.
    MArk if Correct/Helps
    fiaz

  • BPC 7.5 Upgrade - Unary Operator Issue

    We have been performing a large upgrade from a previous version of the software and are looking for some help on some of the issues with the upgrade. One of the issues we have been having is that some of our dimensions were using the property "Unary Operator" to have parent members ignore certain child members in their values. We have seen in 7.5 MS that the unary operator doesn't always perform the same and in one instance wouldn't allow other hierarchies to even roll up at all. I guess what i am looking for is a way to have the same affect (limit some children members from rolll up) that Unary Operators had in previous versions, in 7.5. I had looked at other forums and seen that dimension formulas were used to filter out the child members but i was wondering if there were any other viable options.

    Hi Kenton,
    as Nilanjan wrote if you have a hierarchy all the children will be rolled up to the parent, so works the OLAP.
    If you some parents don't correspond to the sum of his children then you must propcess the application to align the parent with the children.
    If you don't want to sum some children you must create another subparent with only the children you want or create a dimension member outside of the hierarchy using the dimension formula, but remember that this valur is not memorized, it's calculated during the evdre, that means that a lot of dimension formula will reduce the performance.
    Kind regards
         Roberto

  • Grand Total in Dimension Hierarchy

    Hello,
    I still have problem to get the correct Grand total. The Dimension "Project" goes down to Level 4  (some projects only to Level 3). First I solved summing up a calculated measure  with Isleaf() or SUM (currentmember.children).
    Then the grand total always summed up all members and not those which where filtered in Excel. Here i found the current solution with VisualTotals().  But now i still the problem that when expanding sublevels in excel the Grand total is wrong
    again:
    CREATE MEMBER CURRENTCUBE.[Measures].[Prognosekosten] AS
    CASE
    WHEN IsLeaf([Projekt].[Projekt Hierarchie].currentmember)
    THEN ...calculation....
    WHEN [Projekt].[Projekt Hierarchie].currentmember is [Projekt].[Projekt Hierarchie].[ALL]
    THEN sum(except(  VisualTotals(axis(0)), [Projekt].[Projekt Hierarchie].[All]), [Measures].[Prognosekosten])
    ELSE Sum([Projekt].[Projekt Hierarchie].currentmember.children, [Measures].[Prognosekosten])
    END

    Hi Wolfgang,
    According to your description, you create calculated member to calculate the grand total, now the problem is that the grand total is incorrect when you filter the data in Microsoft Excel, right? In this case, please refer to the links below which might helpful
    for you.
    http://wildwordz.wordpress.com/2008/11/21/not-so-grand-totals-in-ssas-cubes/
    http://vnu10.blogspot.com/2011/01/mdx-grand-total-sub-total.html
    Regards,
    Charlie Liao
    TechNet Community Support

  • Calculated Account by Entity but exlcude Parents

    I have an account in our outline (Calced Income Tax) which uses the following formula:
    If(@ISMBR("Actual")) "TAX";
    Elseif(@ISMBR(@LIST("Budget","Q1RF","Q2RF","Q3RF","Q4RF")))
    if(@ISMBR(@RELATIVE("Entity",0))) "Calced Earnings Before Income Tax"*"CorpTax%"->"Begbalance"->"No_deptCode";
    Endif;
    My problem is that the I would like the parent member of the dimension Entity (CONSOL) to be the sum of the children of the Entity dimension.
    What I am getting for the parent (CONSOL) is a multiple of Calced Earnings Before Income Tax * CorpTax%.
    How can I make the parent be a sum? This account is dynamic and stored in my outline.

    What I can think of as the safest solution would be to make the level 0 member a stored member, and put the calculation into a calc script, only running the calculation against the level 0 member.
    Then agg that up.
    I say this is a safe way because i know I have tried in the past on member formulas to say if level 0 calc, else sum of children. But I usually ran into a recursive error, so I would have to break out some part of the process and make it stored.
    Good luck,
    Robert

  • Unable to view ECA and PCA value dimension for Parent Entity

    Hi,
    Situation: There is a parent Enity in (INR) with about 5 children Entity ( also in INR). Application default currency is USD .
    Parent has ' allowadjfromchildren' selected and Children have 'allowAdjs' selected .
    When I pull up a data grid with Parent and children for a particular POV , I can see data in < Entity currency > , < Entitty curr Adj> , <parent curr> , <Parent Currency Adj> for all children , However I dont see the <Entity curr Adj > or < parent curr Adj> at the Parent Level .
    I can only see <entity currency> <entity curr total> and <parent curr>, <parent curr total> for the Parent .
    qs. 1 . is this standard functionality ? Since Adjustment was not made at parent level , those intersection of ECA and PCA for parent will remain empty ?
    qs 2 : Is there a way to roll up the sum of all children values in ECA into ECA at parent level ? rule change may be ?
    eg . If child 1 has 10 , child 2 has 20 and child 3 has 30 in ECA , then their Parent to have 60 in ECA.
    Currenty in our Appsettings we DO NOT have the Consolidationrules parameter selected .
    Not sure if i was clear , Will appreciate some thoughts and direction on this .
    Vik.

    Hi,
    Seeing that the currency is the same for the parent and children in your example, you will not see a difference between the children's <Entity Curr Adjs> and <Parent Curr Adjs>. In other words, if you post $10 to Child1 <Entity Curr Adjs>, you will also see that same amount in the <Parent Curr Adjs> - that is normal behavior and the child will only contribute the $10 to the parent. Because you have selected AllowAdjFromChildren HFM will allow you to post to [Parent Adjs] and [Contribution Adjs].
    Q1: Yes, the adjustments are made to the child and will form part of the <Entity Currency> amounts in the parent. The parent's adjustment value members will store journals to the parent.
    Q2: The sum of all the [Contribution Total] value members of the children will make up the <Entity currency> of the parent.
    Q3: No, you will see the 60 in <Entity Currency> of the parent -- the way it works in more detail below:
    EC + ECA = ECT;
    Trans to Parent currency and seperate journals to PCA;
    Security defines access to the [] nodes and if the parent has AllowAdjsFromChildren then [Parent Adjs] will be available;
    Rules apply to [Proportion] and [Elimination] giving [Contribution];
    Final adjustments allowed to [Contribution Adjs] to get to [Contribution Total]
    Parent <Entity Currency> is the sum of children [Contribution Total];
    Process starts again for the parent.
    Regards,

  • Dimension Members, modifying the formulas

    Hello, We want to modify this rule in order to have the "SUM" of fathers, not childrens.
    The main problem  the calculations are wrong in the column 2008.TOTAL.In otherds words,
    the value of 2008.ORC have to be the same in 2008.TOTAL.
    'Iif(Isleaf(.CurrentMember),IIF(Ucase(.CurrentMember.Name)="BOB",MIxAcabada*rebTotal,null),
    SUM(.CurrentMember.Children)), solve_order=1
    If we replace "CurrentMember.Children" for  "Current.Member.patern" it´s going to be right?
    Thanks

    First Solve Order is wrong.
    Solve Order should be bigger than 3 because 0 to 3 are used by measures.
    I don't understand what you would like to have. Sum of parents? A child can not have more than one parenth.
    Regards
    Sorin Radulescu

  • Bottom-up versions

    hi,
    the versions type bottom-up means that level0 must be for all the dimensions including entity or only the account?
    our customer wants to be able to adjust the numbers on higher entity level of lower entities levels, it is possible?

    Hi,
    The documentation gives a perfect description
    You can create target and bottom up versions. With bottom up versions, you enter data into bottom level members; parent level members are display-only and do not permit data entry. Parent member values are aggregated from bottom level members.
    For target versions, you can enter data for members at any level in the hierarchy. You can use business rules to distribute values from parent members to their descendants. Use target versions to set high-level targets for your plan. Planners working with bottom up versions can reference these targets when they enter plan data.
    Target versions use top-down budgeting. Workflow Tasks are not allowed, and children of target members must be blank (for example, #missing) to enable data input at the top level. Target members must be set to Store (Dynamic Calc overrides data input with sum of children).
    Cheers
    John
    http://john-goodwin.blogspot.com/

  • How to do product with sum using DAX

    Hi Everyone,
    How I can get the Value result using DAX:
    Calculation for Value on 3/1/2014: 6*20 + 10*10 + 4*30 = 340 
                                       4/1/2014: 8*30 + 2*10 + 0*40 = 260 .....
    so on...
    Please reply on this...
    Performance of the measure also the big concern

    Especially if you are worried of performance issues, you should use Power Query as a tool for preparing your data before loading into your Power Pivot data model.
    In this case: Unpivot both tables, join them on Date & Currency code and create a new column: CurrVal(from first table) * CurrVal (from second table). Then group on Date, Sum your new value and ignoare Curr-Columns: There
    goes your target value.
    Then directly load to PP data model if you’re using 2013.
    Imke

  • Trouble trying to replicate GROUP BY/DISTINCT and SUM in PowerPivot with DAX

    I have the following records table (ignore the commas)
    unqPath, Channel, PathLength, UnqPathLength
    8726, direct, 2, 2
    8726, direct, 2, NULL
    8726, organic, 1, 1
    28364, paid, 2, 2
    28364, display, 2, NULL
    287364, email, 4, 4
    287364, email, 4, NULL
    287364, direct, 4, NULL
    287364, email, 4, NULL
    Each record (unqPath) can have multiple channels. For each record I have Path length which is the number of channels associated with that record (this was achieved in SQL doing a count and partitioning it over record name). I have also created another column
    called UnqPathLength where I list the PathLength for each record only once (on the row associated with the 1st channel)
    In PowerPivot, I want to sum the PathLength of all records where a certain channel appears. So direct appears in 2 records which have Path Lengths 2 and 4 respectively so I'd like to have 6 for that.
    I have tried everything from using summarise, distinct but the path length is almost always double counted when the same channel appears twice in the same record. Also tried using unqPathLength (figured this would help with the duplicate counting) but it
    only works when the channel is on the same row and returns incorrect results.
    Here are some of my efforts
    # pathLengthChannel:=
    SUMX(
    SUMMARIZE(
    'query',
    'query'[unqPath],
    'query'[channel],
    'query'[pathLength],
    "pathLengthChannel0",
    SUM('query'[pathLength])
    ),[pathLengthChannel0]
    )OR# pathLengthChannel:=SUMX(
        DISTINCT([unqPath]),
        SUM('query'[pathLength])
    Any ideas would be greatly appreciated. Many thanks.

    This should work assuming that whenever the unqPath and channel are the same that the pathLength is too:
    =SUMX(
    SUMMARIZE(
    query,
    query[unqPath],
    query[Channel],
    "Path",
    MAX(query[PathLength])
    [Path]

Maybe you are looking for

  • Error while activating TCT and BI admin. Cockpit (Urgent)

    Hi Experts,                 We are configuring NW 04s BI system right now. We have followed the general settings on the system after Basis handed that over to us accrding to Best Practice config. document. Now to install BI administration cockpit, we

  • How to integrate BW with CRM?

    Dear All Experts, I need to integrate BW 7.0 with CRM 7.0. I have searched alot on forums regarding this. The more I search the more I got confused. some thread says that all CRM reporting is done from BW whereas some says standard crm reporting is d

  • Vista 64 and flash player....

    I just bought a computer and have vista 64...is impossible install flash player...so...what do I have to do it for watch videos online?...there is any solution or another program?...I really don't understand NOTHING about computer..

  • Working with clips, channels, and tracks

    This question was posted in response to the following article: http://help.adobe.com/en_US/premierepro/cs/using/WS1c9bc5c2e465a58a91cf0b1038518aef7-7f49a .html

  • EA4500 installation software for Mac 10.8 Mountain Lion

    I just bought EA4500. The CD come with it does not support Mac OS 10.8. How to go about it?