MDX with SSAS 2012 Cookbook
By Sherry Li and Tomislav Piasevoli
()
About this ebook
Related to MDX with SSAS 2012 Cookbook
Related ebooks
MDX with Microsoft SQL Server 2016 Analysis Services Cookbook - Third Edition Rating: 0 out of 5 stars0 ratingsSQL Server Analysis Services 2012 Cube Development Cookbook Rating: 0 out of 5 stars0 ratingsMicrosoft SQL Server 2012 Integration Services: An Expert Cookbook Rating: 5 out of 5 stars5/5Oracle Goldengate 11g Complete Cookbook Rating: 5 out of 5 stars5/5Tabular Modeling with SQL Server 2016 Analysis Services Cookbook Rating: 4 out of 5 stars4/5Microsoft Tabular Modeling Cookbook Rating: 0 out of 5 stars0 ratingsPentaho Data Integration 4 Cookbook Rating: 0 out of 5 stars0 ratingsSQL Server 2016 Reporting Services Cookbook Rating: 5 out of 5 stars5/5SAP Data Services 4.x Cookbook Rating: 0 out of 5 stars0 ratingsAmazon QuickSight A Complete Guide - 2019 Edition Rating: 0 out of 5 stars0 ratingsdata quality tools Second Edition Rating: 0 out of 5 stars0 ratingsOracle Warehouse Builder 11g: Getting Started Rating: 0 out of 5 stars0 ratingsAzure SQL Data Warehouse A Complete Guide - 2020 Edition Rating: 0 out of 5 stars0 ratingsInstant SQL Server Analysis Services 2012 Cube Security Rating: 0 out of 5 stars0 ratingsSmart Data Discovery Using SAS Viya: Powerful Techniques for Deeper Insights Rating: 0 out of 5 stars0 ratingsData Management Strategy A Complete Guide - 2019 Edition Rating: 0 out of 5 stars0 ratingsThe Study of Building the Data Warehouse Rating: 0 out of 5 stars0 ratingsEnterprise Data Warehouse Third Edition Rating: 0 out of 5 stars0 ratingsSQL Server Reporting Services Complete Self-Assessment Guide Rating: 0 out of 5 stars0 ratingsSQL Server Analysis Services A Complete Guide - 2020 Edition Rating: 0 out of 5 stars0 ratingsExpert Cube Development with SSAS Multidimensional Models Rating: 0 out of 5 stars0 ratingsGetting Started with Greenplum for Big Data Analytics Rating: 0 out of 5 stars0 ratingsMicrosoft SQL Server 2014 Business Intelligence Development Beginner’s Guide Rating: 0 out of 5 stars0 ratingsChange data capture Third Edition Rating: 0 out of 5 stars0 ratingsData Strategy A Complete Guide - 2019 Edition Rating: 0 out of 5 stars0 ratingsData Virtualization: Selected Writings Rating: 0 out of 5 stars0 ratingsData And Analytics Capabilities A Complete Guide - 2019 Edition Rating: 0 out of 5 stars0 ratingsAdvanced SAS Interview Questions You'll Most Likely Be Asked: Job Interview Questions Series Rating: 0 out of 5 stars0 ratingsAnalytics and Business Intelligence A Complete Guide Rating: 0 out of 5 stars0 ratingsData Lake A Complete Guide - 2019 Edition Rating: 0 out of 5 stars0 ratings
Enterprise Applications For You
Bitcoin For Dummies Rating: 4 out of 5 stars4/5Scrivener For Dummies Rating: 4 out of 5 stars4/5ChatGPT Ultimate User Guide - How to Make Money Online Faster and More Precise Using AI Technology Rating: 0 out of 5 stars0 ratingsExcel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Excel 2019 For Dummies Rating: 3 out of 5 stars3/5QuickBooks 2021 For Dummies Rating: 0 out of 5 stars0 ratingsQuickBooks 2023 All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsCreating Online Courses with ChatGPT | A Step-by-Step Guide with Prompt Templates Rating: 4 out of 5 stars4/5Create Income through Self-Publishing: An Author's Approach on Generating Wealth by Self-Publishing Rating: 5 out of 5 stars5/5Systems Thinking: Managing Chaos and Complexity: A Platform for Designing Business Architecture Rating: 4 out of 5 stars4/550 Useful Excel Functions: Excel Essentials, #3 Rating: 5 out of 5 stars5/5Experts' Guide to OneNote Rating: 5 out of 5 stars5/5101 Ready-to-Use Excel Formulas Rating: 4 out of 5 stars4/5Notion for Beginners: Notion for Work, Play, and Productivity Rating: 4 out of 5 stars4/5Excel Guide for Success Rating: 5 out of 5 stars5/5Excel Formulas That Automate Tasks You No Longer Have Time For Rating: 5 out of 5 stars5/5The New Email Revolution: Save Time, Make Money, and Write Emails People Actually Want to Read! Rating: 5 out of 5 stars5/5Excel 2016 For Dummies Rating: 4 out of 5 stars4/5Mastering QuickBooks 2020: The ultimate guide to bookkeeping and QuickBooks Online Rating: 0 out of 5 stars0 ratingsEnterprise AI For Dummies Rating: 3 out of 5 stars3/5Excel : The Complete Ultimate Comprehensive Step-By-Step Guide To Learn Excel Programming Rating: 0 out of 5 stars0 ratingsExcel Formulas and Functions 2020: Excel Academy, #1 Rating: 4 out of 5 stars4/5Excel 2019 Bible Rating: 4 out of 5 stars4/5Managing Humans: Biting and Humorous Tales of a Software Engineering Manager Rating: 4 out of 5 stars4/5Excel Data Analysis For Dummies Rating: 0 out of 5 stars0 ratings
Reviews for MDX with SSAS 2012 Cookbook
0 ratings0 reviews
Book preview
MDX with SSAS 2012 Cookbook - Sherry Li
Table of Contents
MDX with SSAS 2012 Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Instant Updates on New Packt Books
Preface
What this book covers
What you need for this book
Database Installation
Sample Adventure Works 2012 Database
For Creating PivotTable
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Elementary MDX Techniques
Introduction
Putting data on x and y axes
Getting ready
How to do it…
How it works…
There's more…
Putting more hierarchies on x and y axes with cross join
Skipping axes
Getting ready
How to do it…
How it works…
There's more…
The idea behind it
Possible workarounds – dummy column
Using a WHERE clause to filter the data returned
Getting ready
How to do it…
How it works…
There's more…
Optimizing MDX queries using the NonEmpty() function
Getting ready
How to do it…
How it works…
There's more…
NonEmpty() versus NON EMPTY
Common mistakes and useful tips
Using the PROPERTIES() function to retrieve data from attribute relationships
Getting ready
How to do it…
How it works…
There's more…
Basic sorting and ranking
Getting ready
How to do it…
How it works…
There's more…
Handling division by zero errors
Getting ready
How to do it…
How it works…
There's more…
Earlier versions of SSAS
Setting a default member of a hierarchy in the MDX script
Getting ready
How to do it…
How it works…
There's more…
Helpful tips
2. Working with Sets
Introduction
Implementing the NOT IN set logic
Getting ready
How to do it…
How it works…
There's more…
See also
Implementing the logical OR on members from different hierarchies
Getting ready
How to do it…
How it works…
There's more…
A special case of a non-aggregatable dimension
A very complex scenario
See also
Implementing the logical AND on members from the same hierarchy
Getting ready
How to do it…
How it works…
There's more…
Where to put what?
A very complex scenario
See also
Iterating on a set in order to reduce it
Getting ready
How to do it…
How it works…
There's more…
Hints for query improvements
See also
Iterating on a set in order to create a new one
Getting ready
How to do it…
How it works…
There's more…
Did you know
See also
Iterating on a set using recursion
Getting ready
How to do it…
How it works…
There's more…
Earlier versions of SSAS
See also
Dissecting and debugging MDX queries
Getting ready
How to do it…
How it works…
There's more…
Useful string functions
See also
3. Working with Time
Introduction
Calculating the YTD (Year-To-Date) value
Getting ready
How to do it...
How it works...
There's more...
Inception-To-Date calculation
Using the argument in the YTD() function
Common problems and how to avoid them
YTD() and future dates
See also
Calculating the YoY (Year-over-Year) growth (parallel periods)
Getting ready
How to do it...
How it works...
There's more...
ParallelPeriod is not a time-aware function
See also
Calculating moving averages
Getting ready
How to do it...
How it works...
There's more...
Other ways to calculate the moving averages
Moving averages and the future dates
Finding the last date with data
Getting ready
How to do it...
How it works...
There's more...
See also
Getting values on the last date with data
Getting ready
How to do it...
How it works...
There's more...
Format members on the Date dimension properly
Optimizing time-non-sensitive calculation
Calculating today's date using the string functions
Getting ready
How to do it...
How it works...
There's more...
Relative periods
Potential problems
See also
Calculating today's date using the MemberValue function
Getting ready
How to do it...
How it works...
There's more...
Using the ValueColumn property in the Date dimension
See also
Calculating today's date using an attribute hierarchy
Getting ready
How to do it...
How it works...
There's more...
Member Yes as a default member?
Other approaches
See also
Calculating the difference between two dates
Getting ready
How to do it...
How it works...
There's more...
Dates in other scenarios
The problem of non-consecutive dates
See also
Calculating the difference between two times
Getting ready
How to do it...
How it works...
There's more...
Formatting the duration
Examples of formatting the duration on the web
Counting working days only
See also
Calculating parallel periods for multiple dates in a set
Getting ready
How to do it...
How it works...
There's more...
Parameters
Reporting covered by design
See also
Calculating parallel periods for multiple dates in a slicer
Getting ready
How to do it...
How it works...
There's more...
See also
4. Concise Reporting
Introduction
Isolating the best N members in a set
Getting ready
How to do it...
How it works...
There's more...
The top N member is evaluated in All Periods, not in the context of the opposite query axis
The top N member will be evaluated in the context of the slicer
Use a tuple in the third argument of the TopCount() function to overwrite the member on the slicer
Testing the correctness of the result
Multidimensional sets
TopPercent() and TopSum() functions
See also
Isolating the worst N members in a set
Getting ready
How to do it...
How it works...
There's more...
See also
Identifying the best/worst members for each member of another hierarchy
Getting ready
How to do it...
How it works...
There's more...
Support for the relative context and multidimensional sets in SSAS frontends
See also
Displaying few important members, others as a single row, and the total at the end
Getting ready
How to do it...
How it works...
There's more...
Making the query even more generic
See also
Combining two hierarchies into one
Getting ready
How to do it...
How it works...
There's more...
Use it, but don't abuse it
Limitations
Finding the name of a child with the best/worst value
Getting ready
How to do it...
How it works...
There's more...
Variations on a theme
Displaying more than one member's caption
See also
Highlighting siblings with the best/worst values
Getting ready
How to do it...
How it works...
There's more...
Troubleshooting
See also
Implementing bubble-up exceptions
Getting ready
How to do it...
How it works...
There's more...
Practical value of bubble-up exceptions
Potential problems
See also
5. Navigation
Introduction
Detecting a particular member in a hierarchy
Getting ready
How to do it...
How it works...
There's more...
Important remarks
Comparing members versus comparing values
Detecting complex combination of members
See also
Detecting the root member
Getting ready
How to do it...
How it works...
There's more...
The scope-based solution
See also
Detecting members on the same branch
Getting ready
How to do it...
How it works...
There's more...
The query-based alternative
Children() will return empty sets when out of boundaries
Various options of the Descendants() function
See also
Finding related members in the same dimension
Getting ready
How to do it...
How it works...
There's more...
Tips and trick related to the EXISTING keyword
Filter() versus Exists(), Existing(), and EXISTING
A friendly warning
See also
Finding related members in another dimension
Getting ready
How to do it...
How it works...
There's more...
Leaf and non-leaf calculations
See also
Calculating various percentages
Getting ready
How to do it...
How it works...
There's more...
Use cases
The alternative syntax for the root member
The case of nonexisting [All] level
The percentage of leaf member values
See also
Calculating various averages
Getting ready
How to do it...
How it works...
There's more...
Preserving empty rows
Other specifics of average calculations
See also
Calculating various ranks
Getting ready
How to do it...
How it works...
There's more...
Tie in ranks
Preserving empty rows
Ranks in multidimensional sets
The pluses and minuses of named sets
See also
6. Business Analytics
Introduction
Forecasting using the linear regression
Getting ready
How to do it...
How it works...
There's more...
Tips and tricks
Where to find more information?
See also
Forecasting using the periodic cycles
Getting ready
How to do it...
How it works...
There's more...
Other approaches
See also
Allocating the nonallocated company expenses to departments
Getting ready
How to do it...
How it works...
There's more...
Choosing a proper allocation scheme
Analyzing fluctuation of customers
Getting ready
How to do it...
How it works...
There's more...
Identifying loyal customers in a particular period
More complex scenario
The alternative approach
Implementing the ABC analysis
Getting ready
How to do it...
How it works...
There's more...
Tips and tricks
See also
7. When MDX is Not Enough
Introduction
Using a new attribute to separate members on a level
Getting ready
How to do it...
How it works...
There's more...
So, where's the MDX?
Typical scenarios
Using a distinct count measure to implement histograms over existing hierarchies
Getting ready
How to do it...
How it works...
There's more...
See also
Using a dummy dimension to implement histograms over nonexisting hierarchies
Getting ready
How to do it...
How it works...
There's more...
DSV or DW?
More calculations
Other examples
See also
Creating a physical measure as a placeholder for MDX assignments
Getting ready
How to do it...
How it works...
There's more...
Associated measure group
See also
Using a new dimension to calculate the most frequent price
Getting ready
How to do it...
How it works...
There's more...
Using a utility dimension to implement flexible display units
Getting ready
How to do it...
How it works...
There's more...
Set-based approach
Format string on a filtered set approach
Using a utility dimension to implement time-based calculations
Getting ready
How to do it...
How it works...
There's more...
Interesting details
Fine-tuning the calculations
Other approaches
See also
8. Advanced MDX Topics
Introduction
Displaying members without children (leaves)
Getting ready
How to do it...
How it works...
There's more...
Second and third argument in Descendant() are optional
A reverse case
Possible problems with ragged hierarchies
See also
Displaying members with data in parent-child hierarchies
Getting ready
How to do it...
How it works...
There's more...
Alternative solution
See also
Displaying random values
Getting ready
How to do it...
How it works...
There's more...
See also
Displaying a random sample of hierarchy members
Getting ready
How to do it...
How it works...
There's more...
Alternative solution
See also
Displaying a sample from a random hierarchy
Getting ready
How to do it...
How it works...
There's more...
See also
Performing complex sorts
Getting ready
How to do it...
How it works...
There's more...
Things to be extra careful about
A costly operation
See also
Using recursion to calculate cumulative values
Getting ready
How to do it...
How it works...
There's more...
A simplified version of the solution
Choosing between recursive and cumulative calculations
See also
9. On the Edge
Introduction
Clearing the Analysis Services cache
Getting ready
How to do it...
How it works...
There's more...
Objects whose cache can be cleared
Additional information
Tips and tricks
See also
Using Analysis Services stored procedures
Getting ready
How to do it...
How it works...
There's more...
Tips and tricks
Existing assemblies
Additional information
See also
Executing MDX queries in T-SQL environments
Getting ready
How to do it...
How it works...
There's more...
Additional information
Useful tips
Accessing Analysis Services 2000 from a 64-bit environment
Troubleshooting the linked server
See also
Using SSAS Dynamic Management Views (DMV) to fast-document a cube
Getting ready
How to do it...
How it works...
There's more...
Tips and tricks
Warning!
More information
See also
Using SSAS Dynamic Management View (DMVs) to monitor activity and usage
Getting ready
How to do it...
How it works...
There's more...
See also
Capturing MDX queries generated by SSAS frontends
Getting ready
How to do it...
How it works...
There's more...
Alternative solution
Tips and tricks
See also
Performing a custom drillthrough
Getting ready
How to do it...
How it works...
There's more...
Allowed functions and potential problems about them
More info
Other examples
See also
Index
MDX with SSAS 2012 Cookbook
MDX with SSAS 2012 Cookbook
Copyright © 2013 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: August 2011
Second edition: August 2013
Production Reference: 1200813
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-84968-960-1
www.packtpub.com
Cover Image by Žarko Piljak (<zpiljak@gmail.com>)
Credits
Authors
Sherry Li
Tomislav Piasevoli
Reviewers
Prakash Chatla
Jeremy Kashel
Acquisition Editor
Akram Hussain
Lead Technical Editor
Arun Nadar
Technical Editors
Shashank Desai
Iram Malik
Project Coordinator
Anugya Khurana
Proofreaders
Judith Bill
Lesley Harrison
Indexer
Monica Ajmera Mehta
Production Coordinator
Nilesh R. Mohite
Cover Work
Nilesh R. Mohite
About the Authors
Sherry Li has worked with Microsoft SQL Server Business Intelligence stacks for many years. She lives in Phoenix, Arizona where she works for a major financial organization with responsibilities in implementing data warehousing and BI solutions. She specializes in ETL, dimensional modeling, cube design, and reporting in MDX and T-SQL. Sherry Li maintains her blog at bisherryli.com.
I owe tremendous thanks to Packt Publishing for giving me this opportunity to write this book. Readers who want to become proficient in MDX and have been asking for more.
I would like to thank Tomislav Piasevoli, for starting this book in SQL Server Analysis Servies 2008, and for his deep knowledge in MDX and cube design. I have learned so much from him.
In addition, I would like to thank Prakash Chatla and Jeremy Kashel, for their insight, helpful questioning (I don't think the point you're trying to make comes across.
), enthusiastic responses (I think every BI consultant should read this book!
).
I would also like to thank my friends, my past co-workers, for their earnest encouragement and my current co-workers for putting up with my late morning starts at the office.
Also I thank my father, for keeping me company late at night on Skype from the other side of the globe.
My daughter Shasha, for showing me funny videos on YouTube at night.
My husband, Jim, for loving me unconditionally.
My dog Atari, for always sitting by my feet, while I write late at night.
Tomislav Piasevoli (<tomislav@piasevoli.com>) is a Business Intelligence Specialist with years of experience in Microsoft SQL Server Analysis Services (SSAS). He lives in Croatia and works for SoftPro Tetral d.o.o., a company specializing in development of SSAS frontends and implementation of BI solutions.
His main interests are dimensional modeling, cube design, and MDX about which he blogs at http://tomislav.piasevoli.com. Tomislav also writes articles and speaks at regional conferences and user groups. For his contribution to the community, Microsoft awarded him with the Microsoft SQL Server MVP title.
I wish to thank everyone who contributed to this book, in one way or another. First and foremost, a big thank you goes to my wife Kristina and our three children—one of them was born while I was beginning to write this book—for having enormous patience throughout this period.
Secondly, I'd like to thank Chris Webb for vouching for me to the publisher and providing valuable information as one of the reviewers of this book. Greg Galloway, Marco Russo, Darren Gosbell, and Deepak Puri were the other precious reviewers of this book who corrected my mistakes and provided additional information relevant to the chapter topics.
Next, I'd like to thank all the people at Packt Publishing who worked on this book, to help make it better by assisting me during the book-writing process: Kerry George, Zainab Bagasrawala, Chris Rodrigues, and Merwine Machado.
There were also people who knowingly and unknowingly helped me with their ideas, articles, and helpful tips. My younger brother Hrvoje Piasevoli and Willfried Färber are representatives of the first group. The other group consists of bloggers and subject-matter experts whose articles I found useful for many recipes of this book. Here they are: Mosha Pasumansky, Teo Lachev, Jeffrey Wang, Jeremy Kashel, Vidas Matelis, Thomas Kejser (and other bloggers at SQLCAT site), Jeff Moden, Michael Coles, Itzik Ben-Gan, Irina Gorbach, Vincent Rainardi and in particular my reviewers again.
Additionally, I acknowledge countless contributors to MSDN SQL Server Analysis Services forum—whom I had the luck to meet—for the solutions they shared with the rest of us there.
Last but not least, a thank you goes to my current and former colleagues at SoftPro Tetral company who played a part by exchanging ideas with me during the time spent together all these years.
About the Reviewers
Prakash Chatla is a Business Intelligence Solution Architect and Software Developer who has over ten years of practical experience in building and implementing data warehousing and business intelligence solutions and products on the Microsoft platform in sectors, such as commercial distribution, financial services, online retailing, system integration services, software development, and the agricultural sector.
He used all his experience together with passion for programming in creating Microsoft BI client named PowerPanels available at http://www.powerpanels.eu. Currently, he and his team are building startup around PowerPanels.
My sincere thanks to Tomislav Piasevoli, Anugya Khurana and my PowerPanels team.
Jeremy Kashel is a principal consultant with Adatis, a UK-based Microsoft Gold Partner, specializing in the Microsoft Business Intelligence stack.
Jeremy has over 10 years' experience in delivering SQL Server data warehouse and business intelligence projects for a variety of UK and international clients. When time permits, he blogs at blogs.adatis.co.uk and has also spoken at a number of Microsoft events. Jeremy is the lead author of the book Microsoft SQL Server 2008 R2 Master Data Services, PacktPublishing.
www.PacktPub.com
Support files, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support files and downloads related to your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.
Why Subscribe?
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
Instant Updates on New Packt Books
Get notified! Find out when new books are published by following @PacktEnterprise on Twitter, or the Packt Enterprise Facebook page.
Preface
Microsoft SQL Server Analysis is one of the keystones of Microsoft's Business Intelligence (BI) product strategy. It is the most widely deployed OLAP server around the world. Many organizations, both large and small, have adopted it to provide secure and high-performance access to complex analytics.
MDX (for Multi-Dimensional expressions) is the BI industry standard for multidimensional calculations and queries, and is the most widely accepted software language in multidimensional data warehouse. Proficiency with MDX is essential for any professional who works with multidimensional cubes. MDX is an elegant and powerful language, and also has a steep learning curve.
SQL Server 2012 Analysis Services has introduced a new BISM tabular model and a new formula language, Data Analysis Expressions (DAX). However, for the multi-dimensional model, MDX is still the only query and expression language. For many product developers and report developers, MDX still is and always will be the preferred language for both the tabular model and multi-dimensional model.
Despite its popularity, very few books are dedicated to MDX. MDX-related books often limit their content to explaining the concepts of multidimensional cubes, the MDX language concept and its functions, and other specifics related to working with Analysis Services.
This book presents MDX solutions for business requirements that can be found in the real world of business. You will find best practices, explanations on advanced subjects in full detail, and deep knowledge in every topic. Organized around practical MDX solutions, this book provides a full, in-depth treatment of each topic, sequenced in a logical progression from elementary to advanced techniques.
This book is written in a cookbook format. You can browse through the contents and look for solutions to a particular problem. Each recipe is relatively short and grouped by relevancy, so you can find solutions to related issues in one place. Related recipes are sequenced in a logical progression; you will be able to build up your understanding of the topic incrementally.
This book is designed for both beginners and experts in the MDX language. If you are a beginner, this book is a good place to start. Each recipe provides you with best practices and their underlying rationale, detailed sample scripts, and options you need to know to make good choices. If you are an expert, you will be able to use this book as a reference. Whenever you face a particular challenge, you will be able to find a chapter that is dedicated to the topic.
We hope that you will become confident not only in using the sample MDX queries, but also in creating your own solutions. The moment you start creating your own solutions by combining techniques presented in this book, our goal of teaching through examples is accomplished. We want to hear from you about your journey to MDX proficiency. Feel free to contact me.
What this book covers
Chapter 1, Elementary MDX Techniques, uses some simple examples to demonstrate the fundamental MDX concepts, features, and techniques that are the foundations for our further explorations of the MDX language.
Chapter 2, Working with Sets, focuses on the challenges and solutions of performing the logic operations, NOT, OR, and AND, on Sets.
Chapter 3, Working with Time, presents various time-related functions in MDX language that are designed to work with a special type of dimension called the Time and its typed attributes.
Chapter 4, Concise Reporting, focuses on techniques that you can employ in your project to make analytical reports more compact and concise, and therefore, more efficient.
Chapter 5, Navigation, shows common tasks and techniques related to navigation and data retrieval relative to the current context.
Chapter 6, Business Analytics, focuses on how to perform some of the typical business analysis, such as forecasting, allocating values, and calculating the number of days from last sale date.
Chapter 7, When MDX is Not Enough, discovers that MDX calculations are not always the place to look for solutions. It illustrates several techniques to optimize the query response times with a relatively simple change in cube structure.
Chapter 8, Advanced MDX Topics, contains more advanced MDX topics, such as dealing with parent-child hierarchies and unbalanced hierarchies, getting random samples from a random hierarchy, and complex sorting and iterations.
Chapter 9, On the Edge, presents topics that will expand your horizons, such as clearing cache for performance tuning, executing MDX queries in T-SQL environment, using SSAS Dynamic Management Views (DMVs), drillthrough, and capturing MDX queries using SQL Server Profiler.
What you need for this book
To run the examples in the book the following software will be required:
Database Installation
A full installation of Microsoft SQL Server 2012, or at least the following components are required:
SQL Server 2012 engine
Analysis Services 2012
Microsoft SQL Server management Studio
Microsoft SQL Server Data Tools (part of the Microsoft Visual Studio Shell 2010)
We recommend the Developer, Enterprise, or Trial Edition of Microsoft SQL Server. A few examples might not work using the Standard Edition.
To download Microsoft SQL Server 2012 Trial Edition, go to Microsoft SQL Server site http://tinyurl.com/TrialSQLServer.
You can find Microsoft SQL Server 2012 Developer Edition on amazon.com, using the link http://tinyurl.com/DeveloperSQLServer2012.
Sample Adventure Works 2012 Database
Both the relational database file and the multidimensional Adventure Works project files are required:
AdventureWorksDW2012_Data.mdf: relational database
Adventure Works Multidimensional Models SQL Server 2012—Enterprise Edition: SSAS project files
We recommend the Enterprise Edition of the Adventure Works cube project. To download the installation files, use the following link to go to CodePlex: http://tinyurl.com/AdventureWorks2012
For Creating PivotTable
Microsoft Excel 2007 (or newer) with PivotTable is required.
Most of the examples will work with older versions of Microsoft SQL Server (2005 or 2008 or 2008 R2). However, some of them will need adjustments because the Date dimension in the older versions of the Adventure Works database has a different set of years. To solve that problem simply shift the date-specific parts of the queries few years back in time, for example, turn the year 2006 into the year 2002 and Q3 of the year 2007 to Q3 of 2003.
Who this book is for
This book is for multidimensional cube developers or multidimensional database administrators. It is also for report developers who write MDX queries to access multidimensional cube. If you are a power cube user or an experienced business analyst, you will also find this book invaluable.
In other words, this book is for anyone who has been involved with multidimensional cube. This book is for you if you have found yourself in situations where it is difficult to deliver what your users want and you are interested in getting more information out of your multidimensional cubes.
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Alternatively, we could have used the Aggregate() function instead.
A block of code is set as follows:
SELECT
{ [Measures].[Reseller Order Quantity],
[Measures].[Reseller Order Count] } ON 0,
NON EMPTY
{ [Date].[Month of Year].MEMBERS } ON 1
FROM
[Adventure Works]
WHERE
( [Promotion].[Promotion Type].&[New Product] )
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
SELECT
{ [Measures].[Reseller Sales Amount] } ON 0,
{
ParallelPeriod( [Geography].[Geography].[Country], 2, [Geography].[Geography].[State-Province] .&[CA]&[US] )
} ON 1
FROM
[Adventure Works]
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: We can verify this by browsing the Geography user hierarchy in the Geography dimension in SQL Server Management Studio
.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <feedback@packtpub.com>, and mention the book title via the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions
You can contact us at <questions@packtpub.com> if you are having a problem with any aspect of the book, and we will do our best to address it.
Chapter 1. Elementary MDX Techniques
In this chapter, we will cover:
Putting data on x and y axes
Skipping axes
Using a WHERE clause to filter the data returned
Optimizing MDX queries using the NONEMPTY() function
Using the PROPERTIES() function to retrieve data from attribute relationships
Basic sorting and ranking
Handling division by zero errors
Setting a default member of a hierarchy in the MDX script
Introduction
MDX is an elegant and powerful language, and also has a steep learning curve.
The goal of this chapter is to use some simple examples to demonstrate the fundamental MDX concepts, features and techniques that are the foundations for further explorations of the MDX language.
The chapter begins with several basic techniques: putting multi-dimensional data onto query axes, cube space restriction, empty cell removal, and the important concept of unique names for members, tuples, and sets. From there, we shall turn our attention to a few more advanced features, such as using the MDX functions, creating calculations in the cube space, manipulating strings, writing parameterized queries, and conditionally formatting cell properties. This will form the basis for the rest of the chapters in this book.
SSAS 2012 provides a sample Analysis Services database, the Multidimensional Adventure Works DW. All the MDX queries and scripts in this book have been updated for Analysis Services 2012, and verified against the 2012 Enterprise Edition of the Adventure Works DW Analysis Services database. Majority of the MDX queries and scripts should also run and have been tested in SSAS 2008 R2.
The Query Editor in SQL Server Management Studio (SSMS) is our choice of writing and testing MDX queries. The SQL Server 2012 comes with a free tool, SQL Server Data Tools (SSDT) for cube developers. Just as the Business Intelligence Development Studio (BIDS) was the tool that we used for cube design and MDX scripting in SSAS 2008, SSDT is the tool we will use in this cookbook for cube design and MDX scripting for SSAS 2012.
Putting data on x and y axes
Cube space in SSAS is multi-dimensional. MDX allows you to display results on axes from 0, 1, and 2 up to 128. The first five axes have aliases: COLUMNS, ROWS, PAGES, SECTIONS, and CHAPTERS. However, the frontend tools such as SQL Server Management Studio (SSMS) or other application that you can use for writing and executing MDX queries only have two axes, x and y axis, or COLUMNS and ROWS.
As a result, we have two tasks to do when trying to fit the multi-dimensional data onto the limited axes in our frontend tool:
We must always explicitly specify a display axis for all elements in the SELECT list. We can use aliases for the first five axes: COLUMNS, ROWS, PAGES, SECTIONS, and CHAPTERS. We are also allowed to use integers, 0, 1, 2, 3, and so on. But we are not allowed to skip axes. For example, the first axis must be COLUMNS (or 0). ROWS (or 1) cannot be specified, unless COLUMNS (or 0) has been specified first.
Since we only have two display axes to show our data, we must be able to combine
multiple hierarchies into one query axis. In MDX and other query language terms, we call it cross join
.
It's fair to say that your job of writing the MDX queries is mostly trying to figure out how to project multi-dimensional data onto only two axes, namely, x and y. We will start by putting only one hierarchy on COLUMNS, and one on ROWS. Then we will use the CROSSJOIN function to combine
more than one hierarchy into COLUMNS and ROWS.
Getting ready
Making a two by eight table below in a spreadsheet is quite simple. Writing a MDX query to do that can also be very simple. Putting data on the x and y axes is a matter of finding the right expressions for each axis.
All we need are three things from our cube:
The name of the cube
The correct expression for the Internet Sales Amount, so we can put it on the columns
The correct expression of the sales territory, so we can put it on the rows
Once, we have the preceding three things, we are ready to plug them into the following MDX query, and the cube will give us back the two by eight table:
SELECT
[The Sales Expression] ON COLUMNS,
[The Territory Expression] ON ROWS
FROM
[The Cube Name]
The MDX engine will understand it perfectly, if we replace columns by 0 and rows by 1. Throughout this book, we will use the number 0 for columns that is the x axis, and 1 for rows that is the y axis.
How to do it…
We are going to use the Adventure Works 2012 Multidimensional Analysis Service database enterprise edition in our cookbook. If you open the Adventure Works cube, and hover your cursor over the measure Internet Sales Amount, you will see the fully qualified expression, [Measures].[Internet Sales Amount]. This is a long expression. Drag-and-drop in SQL Server Management Studio works perfectly for us in this situation.
Tip
Long expression is a fact of life in MDX. Although the case does not matter, correct spelling is required and fully qualified and unique expressions are recommended for MDX queries to work properly.
Follow these two steps to open the Query Editor in SSMS:
StartSQL Server Management Studio (SSMS) and connect to your SQL Server Analysis Services (SSAS) 2012 instance (localhost or servername\instancename).
Click on the target database Adventure Works DW 2012, and then right-click on the New Query button.
Follow these steps to save the time spent for typing the long expressions:
Put your cursor on measure Internet Sales Amount, and drag-and-drop it onto AXIS(0).
To get the proper expression for the sales territory, put your cursor over the Sales Territory Country under the Sales Territory | Sales Territory Country. Again, this is a