# Logical Functions: IsAncestor(): Conditional Logic within Calculations

Monday Feb 5th 2007 by William Pearson
Share:

Use IsAncestor() to support conditional logic within calculations. BI Architect Bill Pearson introduces IsAncestor(), and then leads a hands-on practice session with this valuable MDX function.

This article is a member of the series, MDX Essentials. The series is designed to provide hands-on application of the fundamentals of the Multidimensional Expressions (MDX) language, with each tutorial progressively adding features designed to meet specific real-world needs.

For more information about the series in general, as well as the software and systems requirements for getting the most out of the lessons included, please see my first article, MDX at First Glance: Introduction to MDX Essentials.

Note: Current updates are assumed for MSSQL Server, MSSQL Server Analysis Services, and the related Books Online and Samples.

### Overview

In this lesson, we will expose another logical function which we can use for testing a member or level at which a cell is being calculated, the IsAncestor() function. The general purpose of IsAncestor() is to return whether or not a specified member is an ancestor of another member we specify. (By “ancestor,” of course, we mean a member from which the specified member is descended within a dimensional hierarchy.)

The IsAncestor() function, like other logical functions and operators, evaluates values and returns a Boolean value. The utility of IsAncestor() becomes clear when we realize the capability that it gives us to determine the “position,” together with the relationship to progenitors, of a member within a dimensional hierarchy. IsAncestor() more specifically allows us to test whether a member is an ancestor of another member that we specify within the dimension to which it belongs.

Similar to IsLeaf(), IsSibling(), IsChild(), IsGeneration(), and other MDX functions, IsAncestor() can best be employed to apply conditional logic within a couple of primary ways: as a component within a calculation, and as a component within a filter expression. In this article, we will concentrate upon IsAncestor() from the perspective of its use within a calculation. We will discuss the straightforward purpose of the function, to ascertain (and indicate) whether a member is the ancestor of another specified member; the manner in which IsAncestor() manages to do this; and ways we can leverage the function to support effective conditional logic to meet various business needs within our own environments.

Along with an introduction to the IsAncestor() function, this lesson will include:

• an examination of the syntax surrounding the function;
• illustrative examples of uses of the function within practice exercises;
• a brief discussion of the MDX results obtained within each of the practice examples.

### The IsAncestor() Function

#### Introduction

According to the Books Online, the IsAncestor() function “returns whether a specified member is an ancestor of another specified member.” A Boolean value of “True” is returned if the member expression to which the function is applied (to which I will refer as the “primary member expression” throughout this article) is an ancestor of the second specified member (the “secondary member expression”); otherwise IsAncestor() returns “False.” In its capacity, as a logical function, to “test” the nature / status of a member, IsAncestor() is often employed in conjunction with the IIF function to conditionally drive the return of data, such as a member or members, or values, based upon the relationship between members as ancestor / descendant.

We will examine in detail the syntax for the IsAncestor() function after our customary overview in the Discussion section that follows. Following that, we will conduct practice examples within a couple of scenarios, constructed to support simple, hypothetical business needs that illustrate a use for the function. This will afford us an opportunity to explore some the basic options that IsAncestor() can offer the knowledgeable user. Hands-on practice with IsAncestor(), where we will create queries that employ the function, will help us to activate what we have learned in the Discussion and Syntax sections.

#### Discussion

To restate our initial description of its operation, IsAncestor() returns “True” if a specified member expression represents an ancestor of another member (that is, lies between the secondary member and the top / “All” dimensional level) that we specify within a given use of the function; otherwise, the function returns “False.” We can use IsAncestor() to apply conditional logic based upon the location and / or existence of members. As we have noted to be the case with most MDX functions, pairing IsAncestor() with other MDX functions can help us to leverage its power much further than we might in an attempt to use it in standalone fashion.

Let’s look at syntax specifics to further clarify the operation of IsAncestor() .

#### Syntax

Syntactically, we employ the IsAncestor() function by specifying the primary member expression (the member which we are testing as to “ancestor status”) and the secondary member expression (the member in relation to which we are testing the primary member expression) within parentheses to the immediate right of the function. The function takes the member expressions thus appended to it as its arguments, and returns True if the member denoted by the primary member expression is an ancestor of the secondary member expression (or, in other words, if the primary member lies somewhere between the secondary member and the “top” of the dimensional hierarchy).

If the member specified by the primary member expression is not an ancestor of the secondary member (or if the primary member and the secondary member belong to different dimensions) a False is returned, as we might expect.

The general syntax is shown in the following string:

`IsAncestor(Primary_Member_Expression, Secondary_Member_Expression)`

Employing IsAncestor(), like most of the MDX logical functions, is, in the mechanical sense, straightforward. As we have noted, we simply place the primary and secondary member expressions, respectively, in the parentheses to the right of the function. As an example, within a query executed against the sample Adventure Works cube, for the dimension named Geography (with a hierarchy of the same name), the following pseudo-expression:

```IsAncestor([Geography].[Geography].[State-Province].[South Australia],
[Geography].[Geography].CurrentMember) ```

returns True for the current member of the Geography dimension / Geography hierarchy for each of the following:

• Cloverdale

• 6105

• Findon

• 5023

• Perth

• 6006

Each of the listed members is a descendant of South Australia in the cube, as shown in Illustration 1.

Illustration 1: Descendants of South Australia ...

Depending upon the structure of the query (and specifically upon whether the syntax defining axes, etc., eliminates nulls), if members of other dimensions, or members of levels higher than South Australia within the Geography hierarchy, were returned in, say, the row axis of the dataset, their values would be null.

NOTE: For information on several of the “relative” functions, of which .CURRENTMEMBER is an example, see my article MDX Member Functions: "Relative" Member Functions, within the Database Journal MDX Essentials series.

We will practice some uses of the IsAncestor() function in the section that follows.

#### Practice

Preparation: Access SQL Server Management Studio

To reinforce our understanding of the basics we have covered, we will use the IsAncestor() function within a couple of queries that illustrate its operation, focusing, within this article, upon scenarios where we use the function to support conditional logic within a calculation. (We examine its use in combination with the MDX Filter() function in another article of this series). We will undertake our practice exercises within scenarios that place IsAncestor() within the context of meeting basic requirements similar to those we might encounter in our respective daily environments. The intent is to demonstrate the use of the function in a straightforward, memorable manner.

We will turn to the SQL Server Management Studio as a platform from which to construct and execute the MDX we examine, and to view the results datasets we obtain. If you do not know how to access the SQL Server Management Studio in preparation for using it to query an Analysis Services cube (we will be using the sample Adventure Works cube in the Adventure Works DW Analysis Services database), please perform the steps of the following procedure, located in the References section of my articles index:

This procedure will take us through opening a new Query pane, upon which we will create our first query within the section that follows.

Procedure: Satisfy Business Requirements with MDX

Let’s assume, for purposes of our practice example, that we have received a request for assistance from representatives of our client, the Adventure Works organization. Analysts within the Controllers’ Group, with whom we have worked in the past to deliver solutions to meet various reporting and analysis needs, inform us that they have received a request to generate some simple values for a specific analysis task that has been discussed at a recent meeting with the Controllers.

The analysts tell us that the values under immediate consideration involve Internet Order Counts, but, as is typically the case in our collaborative sessions, they want to develop an approach that will work equally well with other measures that have similar analysis potential. (They often derive parameterized queries in Reporting Services from the basic MDX syntax we assemble together, and can thus create self-serve reports that allow information consumers to dictate what measure they wish to analyze, and myriad other options, at run time). The desired end is to simply return the Internet Order Count recorded for each day, month, quarter, and semester for a given operating calendar year.

While this basic need might be easily met a number of ways with an MDX query, the analysts throw a further twist into the requirement: In addition to being likely to parameterize the calendar year at runtime, they also want to be able to support parameterization of the level within the Date dimension (Calendar hierarchy) when executing the report (that is, to be able to change it from calendar year to a lower level, such as a quarter of a month, for example – and thus to “narrow” the member selection that appears within a given iteration of the report results, producing something akin to a selective “drilldown” effect.) Once again, the richness of MDX affords us a number of avenues to this objective. While parameterization is itself not a consideration in our current level of query design, we want to make it easy to accomplish within Reporting Services (the same concept would, of course, apply with other OLAP reporting tools that afford developer access to the MDX syntax that underlies them).

After we initially explain the use of the IsAncestor() function as one candidate for meeting the requirement, our client colleagues state that they are interested in understanding how they might apply conditional logic via this function, within the context of a practical scenario such as the immediate requirement. A method of testing whether or not a specified member is an ancestor to another specified member, or group of members, is something that they hope to be able to extrapolate to uses with other dimensions, as well. (Time / date dimensions are always good “starters” for introducing new functions: the relationships between the various levels are familiar to everyone, whereas the structures of other dimensions might not lend themselves to population accuracy and completeness “reasonability” testing undertaken by those not entirely knowledgeable of the corporate structure, geography, and so forth.)

We offer to illustrate the use of IsAncestor() to meet the immediate need, proposing to present a couple of examples, to solidify the analysts’ new understanding, as well as to assist in rounding their overall MDX “vocabularies.” We then set about the assembly of our examples to illustrate uses of IsAncestor().

Procedure: Use the IsAncestor() Function to Perform Conditional Logic within a Calculation

Per the request of our client colleagues, we will first construct a simple query to provide an illustration of the use of the IsAncestor() function within a common context, the definition of a calculation based upon conditional logic. Our initial example will serve as an introduction to a means of distinguishing the presence of a ancestor / descendant relationship between members of the Date dimension. (We will work with Calendar Year 2003, as the primary member, within our initial example), as requested by the analysts, as a basis for meeting the business requirement to present the simple Internet Order Counts at multiple levels.

1.  Type (or cut and paste) the following query into the Query pane:

```
-- MDX052-001 ISANCESTOR()Function: Conditional Logic in
--   the Definition of a Calculation

WITH
MEMBER
[Measures].[InternetSelectCount]
AS
'IIF(

ISANCESTOR([Date].[Calendar].[Calendar Year].[CY 2003],
[Date].[Calendar].CURRENTMEMBER),
[Measures].[Internet Order Count],

NULL)'

SELECT
{[Measures].[InternetSelectCount]}ON AXIS(0),
NON EMPTY{[Date].[Calendar].MEMBERS} ON AXIS(1)
FROM
```

The Query pane appears, with our input, as depicted in Illustration 2.

Illustration 2: Our Initial Query in the Query Pane ...

The above query returns the Internet Order Count for each member of the Date dimension (Calendar hierarchy) in the cube – whose ancestor is Calendar Year 2003 – regardless of the level the member inhabits; we use Non Empty to physically screen the results to show our “focus” Calendar Year, 2003, and the descendants of this specified, year-level primary member expression. Had we not inserted the Non Empty keyword, we would get all members of the Date dimension, Calendar hierarchy, with those non-descendant members simply indicating (null) as a measure value.

Recall that we have said that we might accomplish our ends through alternative methods. The approach we are taking here allows us to parameterize the primary member expression to accomplish the extended ends of our client colleagues. In doing so, we could set up a hierarchical picklist within Reporting Services, whereby information consumers might select a given date, month, quarter, and so forth, to drive the level below which values are returned. The obvious advantage is that consumers can dictate both the level of the date hierarchy and the specific “focus” member of the hierarchy itself, within the level (in our example, the year for which they wish to display the value for the corresponding descendants). In some circumstances such “double leverage” provided by a single parameter might be seen as a highly desirable efficiency – certainly within the realm of simulated dynamic drilldown effects and so forth.

In the Tentative Reseller Share calculation, we put the IsAncestor() function to work in applying conditional logic to generate the Internet Order Count value: if Calendar Year 2003 (the primary member expression of our function) is the ancestor of the secondary member expression (the Current Member of the Date dimension / Calendar hierarchy), then the corresponding Internet Order Count value is presented. Alternatively, we have directed (via the conditional logic of the IIF() function), that if the primary member expression (Calendar Year 2003) is not the ancestor of the secondary member expression (that is, the member is not a dimensional descendant of Calendar Year 2003), than the Internet Order Count value is returned as null. (Moreover, as we have noted, while we might have displayed all values, including nulls, we eliminated nulls in our present exercise by preceding the rows specification with the NON EMPTY keyword.)

NOTE: For more detail surrounding the IIF() function, see String / Numeric Functions: Introducing the IIF() Function and String / Numeric Functions: More on the IIF() Function. For more about the .CurrentMember function, see MDX Member Functions: "Relative" Member Functions. All articles are members of the Database Journal MDX Essentials series.

For more information about, and hands-on practice with, the sort of parameterization of MDX queries to which I refer within this article, see various member articles of my MSSQL Server Reporting Services series.

We have specified that the Calendar Date members are to populate the rows axis. This provides, to some extent, a quick means of “reasonability” testing out the logic within the calculation that we have defined, as we shall see.

2.  Execute the query by clicking the Execute button in the toolbar, as shown in Illustration 3.

Illustration 3: Click Execute to Run the Query...

The Results pane is populated by Analysis Services, and the dataset, partially depicted in Illustration 4, appears.

Illustration 4: Results Dataset (Partial View) – IsAncestor() Function within a Calculation

In the partial view of the returned dataset, we see that the calculation accomplishes the intended purpose - generating the Internet Order Count for the individual Date (Calendar hierarchy) descendants of Calendar Year 2003, which share the same ancestor (Calendar Year 2003). Again, the conditional test of “ancestry” is applied via a calculated member within which we have leveraged the IsAncestor() function.

3.  Select File -> Save MDXQuery1.mdx As ..., name the file MDX052-001, and place it in a meaningful location.

Our client colleagues express satisfaction with the contextual backdrop we have established for introducing the IsAncestor() function. We will use a similar query within another such example next, to confirm understanding of the concepts. This query will provide an illustration of the use of the IsAncestor() function within the context we have already seen, the definition of a calculated member based upon a comparison. As before, we will base our example upon a local, albeit slightly more sophisticated, scenario described by the client representatives.

The developers / authors within the group cite the following example as useful. They would like to create a query that returns a tentative calculation for Net Resale Revenues, based upon a recent proposal for determining Reseller share of a Product sale for operating Calendar Year 2003. The team provides the following, “example-only” details, as final details are currently being negotiated: for purposes of the example, we would like to calculate Reseller share for Bike (our primary product) sales as 7.5 percent of Reseller Sales Amount; Reseller share for all other Product sales would be calculated at 5.75 percent.

To refresh our memory of the dimensional structure under consideration, we examine the expanded Product Categories hierarchy of the Product dimension, within the Adventure Works cube. A partial view of this structure appears as shown in Illustration 5.

Illustration 5: Partial View of the Product Categories Hierarchy – Product Dimension

Our client colleagues state that the value we derive from the foregoing formula would ideally appear in our presentation at all levels of the Product Categories hierarchy of the Product dimension. They would like the Product levels and their associated members to appear in the row axis, with the calculation, to be called Tentative Reseller Share, to appear in the column axis along with, and to the right of, the Reseller Sales Amount (the value that already exists in the cube, upon which our calculation is to be based). Formatting of the new calculated value is to appear the same as for Reseller Sales Amount, simple U. S. currency. Finally, our colleagues tell us that they prefer to suppress nulls within the returned data.

We confirm our understanding of the requirement with a quick sketch and then take the following actions:

4.  Select File --> New from the main menu.

5.  Select Query with Current Connection from the cascading menu that appears next, as depicted in Illustration 6.

Illustration 6: Create a New Query with the Current Connection ...

A new tab, with a connection to the Adventure Works cube (we can see it listed in the selector of the Metadata pane, once again) appears in the Query pane.

```
-- MDX052-002 ISANCESTOR()Function: Conditional Logic in
--   the Definition of a Calculation
WITH
MEMBER
[Measures].[Tentative Reseller Share]
AS
'SUM(DESCENDANTS([Product].[Product Categories].CURRENTMEMBER,,LEAVES),

IIF(

ISANCESTOR([Product].[Product Categories].[Bikes],
[Product].[Product Categories].CURRENTMEMBER),
0.075 * [Measures].[Reseller Sales Amount],
0.0575 * [Measures].[Reseller Sales Amount]

))',
FORMAT_STRING='Currency'

SELECT
{[Measures].[Reseller Sales Amount], [Measures].[Tentative Reseller Share]}
ON AXIS(0),
NON EMPTY {[Product].[Product Categories].MEMBERS} ON AXIS(1)
FROM
WHERE
([Date].[Calendar].[Calendar Year].[CY 2003])
```

The Query pane appears, with our input, as shown in Illustration 7.

Illustration 7: Our Initial Query in the Query Pane ...

Note that, in addition to using the IsAncestor() function within the IIF() function, to apply conditional logic in a manner similar to our first example, we employ the SUM() function to aggregate the computed values (simply the required percentages times the pre-existing Reseller Sales Amount measure) across the various Product dimensional levels and members (which we specify via the Descendants() function).

7.  Execute the query by clicking the Execute button in the toolbar.

The Results pane is, once again, populated by Analysis Services. The dataset, including the 2003 Reseller Sales Amount and Tentative Reseller Share values, appears as partially depicted in Illustration 8.

Illustration 8: Results Dataset (Partial View) – IsAncestor() Function within a Calculation

In the returned dataset, we see that the query appears to meet the business requirements outlined by the client analysts and developers. We have delivered both a standard measure and a simple calculation, based upon conditional logic which applies different multiples, depending upon the dimensional “lineage” of the current member within the Products dimension. Specifically, any member that is a descendent of the Bikes category of the Product dimension is returned a Tentative Reseller Share value that is based upon a different percentage than the same value returned for a member that is not a hierarchical descendent of the Bikes category.

Our calculation employs the IsAncestor() function, much in the same manner as we have employed and explained it in our first example above: it supports conditional logic to determine the specified “focus” members of the Product dimension, and then applies the multiplier value to the Reseller Sales Amount, based upon the outcome of this test. We can see each of the Reseller Sales Amount values involved in the calculation of the respective Tentative Reseller Share within the returned data set, making it easy to verify that our calculations are performing as expected.

The client representatives confirm that the immediate goal of the Tentative Reseller Share calculation has been met: the creation of a calculation which is dictated by the IsAncestor() function in a manner that lends itself to the parameterization opportunities that are expected to arise at the reporting layer. Moreover, they state that the illustration we have provided will be easily extrapolated to other scenarios where they need to perform an action, or to present a value, based upon the outcome of a test as to whether or not a given dimensional member is the descendent of a specified member.

8.  Select File -> Save MDXQuery2.mdx As ..., name the file MDX052-002, and place it in a meaningful location.

9.  Select File -> Exit to leave the SQL Server Management Studio, when ready.

### Summary ...

In this article, we exposed another logical function contained within the MDX toolset, the IsAncestor() function, whose general purpose, we learned, is to return a value indicating whether or not a member that we specify is the ancestor of another member we specify. We learned that a significant part of the utility of the IsAncestor() function lies in the fact that it can be used to test whether or not a given member lies within the same dimensional hierarchy as, somewhere between the top (or “all”) level and the level of, another dimensional member that we specify.

We noted that, similar to other logical functions, IsAncestor() can best be employed to apply conditional logic in a couple of primary ways: as a component within a calculation, or as a component within a filter expression. In this article, we concentrated upon IsAncestor() from the perspective of its use within a calculation. We discussed the straightforward purpose of the function, the manner in which IsAncestor() manages to accomplish its purpose, and ways we can leverage the function to support effective conditional logic to meet various business needs within our own environments.

After introducing IsAncestor(), we examined the syntax with which we employ the function. We then undertook illustrative examples whereby we put the IsAncestor() function to work, within a couple of simple illustrations, to meet the business needs of a hypothetical client. Throughout our practice session, we briefly discussed the results datasets we obtained from each of the queries we constructed.

Discuss this article in the MSSQL Server 2000 Analysis Services and MDX Topics Forum.

Share:
Home
Mobile Site | Full Site