Home > Articles > Data > SQL Server

Like this article? We recommend

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 1Figure 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 2Figure 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 3Figure 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 4Figure 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 5Figure 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 6Figure 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 7Figure 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 8Figure 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 9Figure 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 10Figure 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 11Figure 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020