 • Print

Returning Values Based on Specified Dimensions

In the integrated exercise in Part 2 of this series, we calculated the percentage of total organizational expense contributed by each Store member in our cube. In this freestanding lesson, we'll extend the calculation of the individual stores' contributions to the whole, to include more illustrations of using expressions to add more analytical features for information consumers.

Extending MDX Expressions: An Integrated Exercise

In this preliminary exercise, we'll first extend the calculation of expense contribution of the individual stores to include their relative contributions to the various levels of the Store dimension (City, State, and Country). The intent is to demonstrate further the power of OLAP cubes to embrace the hierarchical relationships of their dimension members. We'll practice using conditional tests to identify empty members, illustrating both why this might be necessary, and how we can build in logic to deal with complications that empty members might present.

Next, we'll examine how to use MDX to retrieve a value from a second cube, offering the capability of using multiple OLAP data sources together for analysis and reporting. In addition, we'll learn how to compute a per-unit average, within the context of providing a "revenue per unit sold" value based on values retrieved from two separate OLAP data sources.

Finally, we'll explore the use of MDX functions that incorporate the concept of time within the context of expression design. We'll practice incorporating support for time-based analysis, such as the quantification of change in values over time, with MDX functions that are ideally suited for that purpose. We'll perform exercises to reinforce these concepts within the context of OLAP data sources.

To prepare for the lesson, let's open Analysis Manager and create a new calculated member within the Budget cube. We'll re-create the calculated member we left at the end of the second lesson in this series, to provide a fresh start, and to allow this lesson to be accomplished in a stand-alone manner.

Create a new calculated member within the Budgets cube by following these steps:

1. In the Analysis Manager console, expand the Cubes folder within the FoodMart 2000 database sample (see Figure 1). Figure 1 Sample cubes provided with Analysis Services.

2. Right-click the Budget cube and select Edit from the context menu.

3. When the Cube Editor opens, click the Data tab in the lower-left corner to display the data viewing pane. The data viewing pane retrieves the view that was last saved (or the default, if none was saved from previous exercises).

4. Drag the Store dimension from the top pane down to replace the current dimension in the row axis.

NOTE

To "swap" the current dimension to the top and Store below, you can drop the icon that appears in the current dimension's old place. After dropping, it will appear as Store Country. A small, double-headed arrow appears at the drop point.

5. Drag the Measures dimension from the top pane down to replace the dimension in the column axis (unless it's already there). The heading will appear as MeasuresLevel, with the measure Amount appearing just underneath.

6. Select 1998 in the filter field for the Year dimension at the top of the data viewing pane. Figure 2 shows the result. Figure 2 The data viewing pane after the dimension swap.

We'll delete the Expense % calculated member created in the previous tutorial, as we'll make some changes to it from the last session. (If you're joining the series with this lesson, simply begin with a new calculated member here.)

7. Select the Expense % calculated member.

8. Right-click and select Delete on the context menu.

9. Click Yes at the confirmation dialog box to complete the deletion.

Next, we'll create a new calculated member to replace the one we deleted, Expense %.

10. Choose Insert, Calculated Member (see Figure 3) to display the Calculated Member Builder. Figure 3 Creating a new calculated member.

11. Type Expense % in the Member Name box. In the Value Expression box, enter the following expression (see Figure 4):

`[Amount]/([Amount], Ancestor([Store].CurrentMember, [Store].[(All)]))`

NOTE

Remember that it can be helpful to use the Check button to verify syntax completeness. (See the discussion in the second lesson regarding the benefits and limitations of the Check functionality.)

The resulting expression is similar to the expression in the Value Expression box for the calculated member Expense % that we modified in the final exercise of the last lesson. (For an explanation of the purpose of this expression, see the section "Specification Made Simple: An Integrated Example" in Part 2 of this series.) Figure 4 The Value Expression Box with the inserted calculation.

12. Click OK.

13. In the Cube tree, select Expense % in the Calculated Members folder for the Budget cube.

The Basic tab of the Properties pane appears underneath Expense %.

14. On the Basic tab, select the Parent Dimension property of Expense %.

15. If necessary, select the Measures dimension.

16. Click the Advanced tab in the Properties pane.

17. Select the Format String property of Expense %. Open the drop-down list and select Percent as the format for the string.

18. Press Enter. Figure 5 shows the results. Figure 5 The modified results in the data viewing pane.

19. Double-click the Mexico member of the Store Country level (row axis) to explode the Mexico Store State view of the Store dimension (see Figure 6), displaying the individual Mexican Store State members. Figure 6 Data view, drilled down to the Mexican Store State members.

Although the Expense % for the individual Mexican Store states equals 100% at the All Stores Total rollup (the top dimension level), our calculated member doesn't extend the concept to the hierarchical levels. That is, the Expense % for the Mexican Store states doesn't indicate the relative contribution of the Store states to their respective immediate rollup levels. In other words, the Mexican Store states' percentages don't total to 100% at their hierarchical rollup level Mexico Total—instead, they only show their respective contributions to the top level, All Stores, in that they simply add to a total of 76.21%, the Mexico Total contribution.

Next, we'll modify our expression to use the distance version of the Ancestor function to do the following:

• Identify the hierarchical parent for the Store states

• Calculate context-sensitive rollup percentages, based on our position in the drill-down of the hierarchy. Recall from the previous lessons that the distance version of the Ancestor function has the same meaning as the Parent function, when the "distance," or the number of levels removed from the original member (in our case, the current member) to the target member (in our case, the parent member) is 1.

1. Select the Value property for the Expense % calculated member.

2. Click the ellipsis (...) button to display the Calculated Member Builder.

3. In the Value Expression box, enter the following expression (see Figure 7):

`[Amount]/([Amount], Ancestor([Store].CurrentMember,1))` Figure 7 Modified results in the data viewing pane.

Now the percentages for the Mexican Store States add to 100%. We've achieved our objective, in that the Store Country level Expense % values total to 100%, and the Store State level Expense % values also total 100% of their respective rollup levels. This scenario demonstrates how MDX allows us to leverage the hierarchical capacity of the OLAP data source with relative ease in expressions.

However, Figure 7 shows a fly in the ointment: The top-level Expense % value is nonsensical. This condition is the result of a divide-by-zero condition, as the expression doesn't yet provide for cases in which the parent (distance = 1 from the current member) is nonexistent. The top level can't refer to a higher level; therefore, our expression generates a zero in its denominator. And, as we all know, the result of dividing by zero is "undefined."

We'll handle this annoying situation with another enhancement to the expression. We'll add a conditional test that will help to ensure that top-level members are treated differently, to accommodate the fact that, when it comes to parents, they're "empty." Recall the IIF function from the first of our tutorials? (See the section "Basic Conversion Functions" in Part 1.) We'll use this test to ascertain an empty state, and provide for that state to always simply return a 100% result. While there are many ways to handle this, we'll keep it simple with the following steps:

1. Return to the value property of the Expense % calculated member.

2. Click the ellipsis (...) button.

3. When the Calculated Member Builder appears, modify the expression as follows:

```IIF(IsEmpty(([Amount],Ancestor([Store].CurrentMember,1))),1,
[Amount]/([Amount], Ancestor([Store].CurrentMember,1)))```

Remember to use the Check button to verify the syntax.

The expression now says, "If the value for the current member at the 'address' under consideration is zero, substitute 1, rather than performing the calculation we've built up to this point (the else clause that appears after the then of value 1 above).

4. Click OK. Compare the results to Figure 8. The top level displays 100% as its value. Figure 8 The results of the conditional test in the expression.

5. Choose File, Save from the top menu to save your work up to this point.

Retrieving Data from a Second Cube

We can add the retrieval of data from another cube to our example by creating an expression to "look up" a value from the secondary data source. While truly sophisticated uses of this capability are possible, we'll undertake a simple instance to illustrate that you can rely on data from other sources to enhance the end product that you deliver to targeted information consumers. (Indeed, optimal cube design principles suggest that in creating new cubes, you avoid replicating data that can easily be obtained from other sources.)

Suppose we want to bring sales units data into our information product. The Budget cube doesn't contain this information, primarily because its designers wanted to restrict its size, but also to limit its focus to the business requirements of the budgeting users. For this example, we'll assume that these users didn't express an interest in unit quantity information as a part of the business-requirements collection phase of design. (A quick review of the measures data in the Budget cube confirms that no unit information exists in the cube.)

Meanwhile, an ad hoc need arises to be able to access the unit sales data that corresponds to the sales information stored in the Budget cube. Say that we need to compare some rough per-unit calculations between stores. This will give us an opportunity to expand the integrated exercise to include the calculation of some high-level per-unit average costs.

Our first focus will be to retrieve the unit sales data from the Sales cube (another sample cube that comes with the Analysis Services installation). To create a calculated member to accomplish this objective, we'll use a lookup function. We'll continue where we left off at the end of the last exercise.

1. Select 1997 in the filter field for the Year dimension at the top of the data viewing pane.

2. Select Gross Sales in the filter field for the Account dimension.

3. Double-click the Mexico member of the Store Country level (row axis) to zoom to the Store Country view of the Store dimension.

4. Double-click the USA member of the Store Country level (row axis) to explode to the USA Store State view of the Store dimension for USA.

The result set should be identical to that shown in Figure 9. Figure 9 The results in the data viewing pane.

Notice that the Budget cube contains data for USA stores only. We'll create a new calculated measure to act as our "pipeline" from the Sales cube.

5. From the top menu, choose Insert, Calculated Member to display the Calculated Member Builder.

6. Type Sales Units in the Member Name box. In the Value Expression box, enter the following expression:

`LookupCube("Sales","([Unit Sales],"+[Store].CurrentMember.UniqueName +")")`
7. Click OK. Figure 10 shows the data viewing pane at this point. Figure 10 The sales unit data as retrieved from the Sales cube.

A quick comparison of the result set to the data in the Sales cube verifies its accuracy.

The simple expression we created above exploits the LookupCube function, which consists of two text-string arguments. The first argument (Sales, in this example) refers to the name of the cube targeted as the source. The second argument is the tuple with which we specify the value we want to return. We enforced the criteria for specification of dimensions by using the now familiar CurrentMember, appending the unique name after first closing the string, and then appending (via the second +) the remainder of the string. (See Part 1 of this series for a discussion of the UniqueName function, which returns a string for containing the qualified name of the entire hierarchy "path" for the member.)

As you might expect at this point in our exploration of MDX, the default member is used by the LookupCube function for any dimension not specified within it, meaning that a simple expression is adequate for this high-level figure.

Let's go a step further and practice creation of another expression to compute the average total revenue (gross sales) per unit sold. This will be a quick-and-dirty metric to use in perhaps identifying significant outliers from a reasonable average total revenue (and helping to point out sales items that might not be contributing comparably to the total sales amount). (Realizing, of course, that this would only be a rough indicator, but would perhaps serve to identify further, more precisely designed analysis opportunities.)

1. Choose Insert, Calculated Member to display the Calculated Member Builder.

2. Type Avg Rev Per Unit Sold in the Member Name box. In the Value Expression box, type the following expression:

`[Sales Units]/[Amount]`
3. Click OK to accept the expression entered.

4. In the Cube tree, select Avg Rev Per Unit Sold in the calculated members folder for the Budget cube.

The Basic tab of the Properties pane appears underneath Avg Rev Per Unit Sold.

5. On the Basic tab, select the Parent Dimension property of Avg Rev Per Unit Sold.

6. If necessary, click the drop-down arrow button and select the Measures dimension.

7. Click the Advanced tab in the Properties pane.

8. Select the Format String property of Avg Rev Per Unit Sold, click the drop-down arrow button, and select Currency as the format for the string.

9. Press Enter.

10. Select Sales Units in the Calculated Members folder for the Budget cube.

The Basic tab of the Properties pane appears underneath Sales Units.

11. On the Basic tab, select the Parent Dimension property of Sales Units.

12. If necessary, click the drop-down arrow button and select the Measures dimension.

13. Click the Advanced tab in the Properties pane.

14. Select the Format String property of Sales Units, click the drop-down arrow button, and select #,# (whole units with thousands separator) as the format for the string.

15. Press Enter.

Compare the result set to that partially shown in Figure 11. Figure 11 The enhanced results in the data viewing pane.

Both the Sales Units and the Avg Rev Per Unit Sold calculated members appear, complete with the specified formatting. This integrated exercise has covered many new aspects of MDX, while reviewing several key concepts touched on earlier in this series. Next, we'll examine the roles that MDX functions can play in helping to support the time-based analysis needs of information consumers.