Mdx Examples Using Adventureworksdw Data

  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Mdx Examples Using Adventureworksdw Data as PDF for free.

More details

  • Words: 3,316
  • Pages: 12
MDX Examples using AdventureWorksDW Data Tom Tuduc This tutorial shows common MDX expressions and functions using the sample AdventureWorksDW data in SQL Server 2005 to complement the MDX Language Reference on msdn: http://msdn.microsoft.com/en-us/library/ms145595.aspx. This tutorial also includes a quick reference of all operators and functions in the appendixes. Why MDX? MDX (Multi Dimension Expression) and SQL (Structure Query Language) share a similarity: both have features of tuples calculus and first order predicate calculus. While a SQL returns a table of columns and rows (two dimensions), a MDX query returns a multi dimension cubes. MDX provides syntax for working with data in multi dimension. It also enables the presenting of cubes in Excel-like pivoting format. The following comparison of a simplest MDX query and its lengthy SQL equivalence quickly shows MDX's usefulness: SELECT [Dim Reseller].[Year Opened].MEMBERS ON COLUMNS, [Dim Product].[English Product Subcategory Name].MEMBERS ON ROWS FROM [Adventure Works DW]

EQUIVALENT SQL SELECT dbo.DimProductSubcategory.EnglishProductSubcategoryName, dbo.DimReseller.YearOpened, dbo.FactResellerSales.OrderQuantity INTO dbo.test1 FROM dbo.DimReseller, dbo.FactResellerSales, dbo.DimProduct, dbo.DimProductSubcategory WHERE dbo.DimProduct.ProductKey = dbo.FactResellerSales.ProductKey and dbo.DimProduct.ProductSubcategoryKey = dbo.DimProductSubcategory.ProductSubcategoryKey and dbo.FactResellerSales.ResellerKey = dbo.DimReseller.ResellerKey SELECT dbo.test1.EnglishProductSubcategoryName, dbo.test1.YearOpened, SUM(dbo.test1.OrderQuantity) FROM dbo.test1 GROUP BY dbo.test1.EnglishProductSubcategoryName, dbo.test1.YearOpened ORDER BY dbo.test1.EnglishProductSubcategoryName, dbo.test1.YearOpened

The equivalent SQL query still has to be pivoted in Excel to show the years horizontally.

MDX Statements Anatomy

A MDX statement consists of clauses (i.e. SELECT, FROM, WHERE, etc…). Clauses can have operators (i.e. *, =, <, etc…) and functions (i.e. crossjoint, lastChild, covariance, etc...). See the complete list of functions and operators in the APPENDIXES below.

MDX EXAMPLES 1. Using WITH and tuples WITH MEMBER Measures.Profit AS [Measures].[Sales Amount] - [Measures].[Total Product Cost] MEMBER Measures.ProfitPercent AS Measures.Profit/[Measures].[Total Product Cost], FORMAT_STRING = '#.#%' SELECT {Measures.Profit,Measures.ProfitPercent} ON COLUMNS, { ( [Dim Product].[Dim Product Category].[1], [Dim Time].[CalendarYear].[2001] ), ( [Dim Product].[Dim Product Category].[1], [Dim Time].[CalendarYear].[2002] ), ( [Dim Product].[Dim Product Category].[2], [Dim Time].[CalendarYear].[2001] ), ( [Dim Product].[Dim Product Category].[2], [Dim Time].[CalendarYear].[2002]) } ON ROWS FROM [Adventure Works DW]

2. Using CrossJoint to enumerate all tuples SELECT [Dim Reseller].[Year Opened].MEMBERS ON COLUMNS, {CROSSJOIN([Dim Product].[English Product Subcategory Name].MEMBERS, [Dim Time].[CalendarYear].MEMBERS, [Dim Time].[CalendarQuarter].MEMBERS)} ON ROWS FROM [Adventure Works DW]

SELECT CROSSJOIN ( {[Dim Employee].[Billing Country].France }, [Dim Product].[English Product Subcategory Name].Members ) ON 0 FROM [Adventure Works DW] WHERE Measures.[Measures].[Sales Amount]

3. USING WHERE and FILTER

Use Where to slice. This returns the same number of cells. Use filter to select certain members, as in example below: SELECT NON EMPTY {[Dim Reseller].[Dim Reseller].MEMBERS} ON COLUMNS, FILTER({[Dim Reseller].[Geography Key].MEMBERS}, ([Measures].[Sales Amount], [Dim Time].[CalendarYear].[2002])>10) ON ROWS FROM [Adventure Works DW]

4. Using the Linear Regression Function WITH MEMBER Measures.x AS LinRegR2 (LastPeriods(10, [Dim Time].[Month].&[2002]&[11] ), [Measures].[Total Product Cost] ,[Measures].[Sales Amount] ), FORMAT_STRING = '#.##' SELECT Measures.x ON COLUMNS FROM [Adventure Works DW]

The return statistical R2 value of .95 shows a near perfect fit of the linear equation formed by two sets: Total Product Cost and Sales Amount. 5. Calculate standard deviation WITH MEMBER Measures.x AS Stdev ( { [Dim Time].[Month].&[2001]&[7], [Dim Time].[Month].&[2001]&[8], [Dim Time].[Month].&[2001]&[9], [Dim Time].[Month].&[2001]&[10]}, [Measures].[Sales Amount]), FORMAT_STRING = '#.##' MEMBER Measures.x2 AS Stdev ( { [Dim Time].[Month].&[2001]&[10], [Dim Time].[Month].&[2001]&[11], [Dim Time].[Month].&[2001]&[12]}, [Measures].[Sales Amount]), FORMAT_STRING = '#.##'

SELECT {Measures.x, Measures.x2 } ON COLUMNS FROM [Adventure Works DW]

APPENDIXES MDX Statements Multidimensional Expressions statements are organized in three groups as follows:

1.

MDX Scripting These statements manage query context, scope, and the control of flow within MDX scripts. For Statements example, CALCULATE, FREEZE, IF, and SCOPE

2.

MDX Data Definition Statements

These statements create, drop, and manipulate multidimensional objects. For example, ALTER, CREATE ACTION, CREATE CELL, CREATE KPI, etc…

MDX Data Manipulation Statements

These statements retrieve and manipulate data from multidimensional objects. For example, CALL, CLEAR, DRILLTHROUGH, SELECT, and UPDATE CUBE.

3.

MDX Operators -- (Comment) - (Except) - (Negative) - (Subtract) * (Crossjoin) * (Multiply) / (Divide) ^ (Power) /*...*/ (Comment) // (Comment) : (Range) + (Add) + (Positive) + (String Concatenation) + (Union) < (Less Than)

Indicates comment text that is provided by the user. Performs a set operation that returns the difference between two sets, removing duplicate members. Performs a unary operation that returns the negative value of a numeric expression. Performs an arithmetic operation that subtracts one number from another number. Performs a set operation that returns the cross product of two sets. Performs an arithmetic operation that multiplies two numbers. Performs an arithmetic operation that divides one number by another number. Performs an arithmetic operation that raises one number by another number. Indicates comment text that is provided by the user. Indicates user-provided text. Performs a set operation that returns a naturally ordered set, with the two specified members as endpoints, and all members between the two specified members included as members of the set. Performs an arithmetic operation that adds two numbers. Performs a unary operation that returns the positive value of a numeric expression. Performs a string operation that concatenates two or more character strings, tuples, or a combination of strings and tuples. Performs a set operation that returns a union of two sets, removing duplicates. Performs a comparison operation that determines whether the value of one MDX expression is less than the value of another MDX expression.

<= (Less Than or Equal To) <> (Not Equal To)

Performs a comparison operation that determines whether the value of one MDX expression is less than or equal to the value of another MDX expression. Performs a comparison operation that determines whether the value of one MDX expression is not equal to the value of another MDX expression. Performs a comparison operation that determines whether the value of one MDX expression is = (Equal To) equal to the value of another MDX expression. Performs a comparison operation that determines whether the value of one MDX expression is > (Greater Than) greater than the value of another MDX expression. >= (Greater Performs a comparison operation that determines whether the value of one MDX expression is Than or Equal greater than or equal to the value of another MDX expression. To) AND Performs a logical conjunction on two numeric expressions. IS Performs a logical comparison on two object expressions. NOT Performs a logical negation on a numeric expression. OR Performs a logical disjunction on two numeric expressions. XOR Performs a logical exclusion on two numeric expressions.

MDX Function Microsoft SQL Server Analysis Services provides for the use of functions in Multidimensional Expressions syntax. Functions can be used in any valid MDX statement, and are frequently used in queries, custom rollup definitions, and other calculations. This section provides information about the MDX functions included with Analysis Services. Array Functions SetToArray

Converts one or more sets to an array for use in a user-defined function.

Hierarchy Functions Hierarchy Dimension Dimensions Level Functions Level Levels

Returns the hierarchy that contains a specified member or level. Returns the dimension that contains a specified member, level, or hierarchy. Returns a hierarchy specified by a numeric or string expression. Returns the level of a member. Returns the level whose position in a dimension or hierarchy is specified by a numeric expression or whose name is specified by a string expression.

Logical Functions IsAncestor IsEmpty IsGeneration IsLeaf IsSibling Member Functions Ancestor ClosingPeriod Cousin

Returns whether a specified member is an ancestor of another specified member. Returns whether the evaluated expression is the empty cell value. Returns whether a specified member is in a specified generation. Returns whether a specified member is a leaf member. Returns whether a specified member is a sibling of another specified member. Returns the ancestor of a member at a specified level or distance. Returns the last sibling among the descendants of a member at a specified level. Returns the child member with the same relative position under a parent member as the specified child member.

CurrentMember DataMember DefaultMember FirstChild FirstSibling Item (Member) Lag LastChild LastSibling Lead LinkMember Members (String) NextMember OpeningPeriod ParallelPeriod Parent PrevMember StrToMember UnknownMember ValidMeasure Numeric Functions Aggregate Avg CalculationCurrentPass CalculationPassValue CoalesceEmpty Correlation Count (Dimension) Count (Hierarchy Levels) Count (Set) Count (Tuple) Covariance CovarianceN DistinctCount IIf LinRegIntercept LinRegPoint LinRegR2 LinRegSlope LinRegVariance LookupCube

Returns the current member along a specified dimension or hierarchy during iteration. Returns the system-generated data member that is associated with a nonleaf member of a dimension. Returns the default member of a dimension or hierarchy. Returns the first child of a member. Returns the first child of the parent of a member. Returns a member from a specified tuple. Returns the member that is a specified number of positions before a specified member along the member's dimension. Returns the last child of a specified member. Returns the last child of the parent of a specified member. Returns the member that is a specified number of positions following a specified member along the member's dimension. Returns the member equivalent to a specified member in a specified hierarchy. Returns a member specified by a string expression. Returns the next member in the level that contains a specified member. Returns the first sibling among the descendants of a specified level, optionally at a specified member. Returns a member from a prior period in the same relative position as a specified member. Returns the parent of a member. Returns the previous member in the level that contains a specified member. Returns the member specified by an MDX–formatted string. Returns the unknown member associated with a level or member. Returns a valid measure in a virtual cube by forcing inapplicable dimensions to their top level. Returns a scalar value calculated by aggregating either measures or an optionally specified numeric expression over the tuples of a specified set. Returns the average value of measures or the average value of an optional numeric expression, evaluated over a specified set. Returns the current calculation pass of a cube for the specified query context. Returns the value of a MDX expression evaluated over the specified calculation pass of a cube. Coalesces an empty cell value to a number or string and returns the coalesced value. Returns the correlation coefficient of two series evaluated over a set. Returns the number of dimensions in a cube. Returns the number of levels in a dimension or hierarchy. Returns the number of cells in a set. Returns the number of dimensions in a tuple. Returns the population covariance of two series evaluated over a set, using the biased population formula. Returns the sample covariance of two series evaluated over a set, using the unbiased population formula. Returns the number of distinct, nonempty tuples in a set. Returns one of two values determined by a logical test. Calculates the linear regression of a set and returns the value of the intercept in the regression line, y = ax + b. Calculates the linear regression of a set and returns the value of y in the regression line, y = ax + b. Calculates the linear regression of a set and returns the coefficient of determination, R2. Calculates the linear regression of a set, and returns the value of the slope in the regression line, y = ax + b. Calculates the linear regression of a set, and returns the variance associated with the regression line, y = ax + b. Returns the value of an MDX expression evaluated over another specified cube in the same database.

Max Median Min Ordinal Predict Rank RollupChildren Stddev StddevP Stdev StdevP StrToValue Sum Value Var Variance VarianceP VarP Set Functions AddCalculatedMembers AllMembers Ancestors Ascendants Axis BottomCount BottomPercent BottomSum Children Crossjoin CurrentOrdinal Descendants Distinct DrilldownLevel DrilldownLevelBottom DrilldownLevelTop DrilldownMember DrilldownMemberBottom

DrilldownMemberTop DrillupLevel

Returns the maximum value of a numeric expression that is evaluated over a set. Returns the median value of a numeric expression that is evaluated over a set. Returns the minimum value of a numeric expression that is evaluated over a set. Returns the zero-based ordinal value associated with a level. Returns a value of a numeric expression evaluated over a data mining model. Returns the one-based rank of a specified tuple in a specified set. Returns a value generated by rolling up the values of the children of a specified member using the specified unary operator. Alias for Stdev . Alias for StdevP . Returns the sample standard deviation of a numeric expression evaluated over a set, using the unbiased population formula. Returns the population standard deviation of a numeric expression evaluated over a set, using the biased population formula. Returns the value specified by an MDX–formatted string. Returns the sum of a numeric expression evaluated over a set. Returns the value of a measure. Returns the sample variance of a numeric expression evaluated over a set, using the unbiased population formula. Alias for Var . Alias for VarP . Returns the population variance of a numeric expression evaluated over a set, using the biased population formula. Returns a set generated by adding calculated members to a specified set. Returns a set that contains all members, including calculated members, of the specified dimension, hierarchy, or level. Returns a set of all ancestors of a member at a specified level or distance. Returns the set of the ascendants of a specified member, including the member itself. Returns a set defined in an axis. Sorts a set in ascending order, and returns the specified number of tuples with the lowest values. Sorts a set in ascending order, and returns a set of tuples with the lowest values whose cumulative total is equal to or less than a specified percentage. Sorts a set in ascending order, and returns a set of tuples with the lowest values whose total is equal to or less than a specified value. Returns the children of a specified member. Returns the cross product of one or more sets. Returns the current iteration number within a set during iteration. Returns the set of descendants of a member at a specified level or distance, optionally including or excluding descendants in other levels. Returns a set, removing duplicate tuples from a specified set. Drills down the members of a set to one level below the lowest level represented in the set, or to one level below an optionally specified level of a member represented in the set. Drills down the bottommost members of a set, at a specified level, to one level below. Drills down the topmost members of a set, at a specified level, to one level below. Drills down the members in a specified set that are present in a second specified set. Alternatively, the function drills down on a set of tuples. Drills down the members in a specified set that are present in a second specified set, limiting the result set to a specified number of members. Alternatively, this function also drills down on a set of tuples. Drills down the members in a specified set that are present in a second specified set, limiting the result set to a specified number of members. Alternatively, this function drills down on a set of tuples. Drills up the members of a set that are below a specified level.

DrillupMember Except Exists Extract Filter Generate Head Hierarchize Intersect LastPeriods Members (Set) Mtd NameToSet NonEmptyCrossjoin Order PeriodsToDate

Qtd Siblings StripCalculatedMembers StrToSet Subset Tail ToggleDrillState TopCount TopPercent TopSum Union Unorder VisualTotals Wtd Ytd

Drills up the members in a specified set that are present in a second specified set. Finds the difference between two sets, optionally retaining duplicates. Returns the set of members of one set that exist with one or more tuples of one or more other sets. Returns a set of tuples from extracted dimension elements. Returns the set that results from filtering a specified set based on a search condition. Applies a set to each member of another set, and then joins the resulting sets by union. Alternatively, this function returns a concatenated string created by evaluating a string expression over a set. Returns the first specified number of elements in a set, while retaining duplicates. Orders the members of a set in a hierarchy. Returns the intersection of two input sets, optionally retaining duplicates. Returns a set of members up to and including a specified member. Returns the set of members in a dimension, level, or hierarchy. Returns a set of sibling members from the same level as a given member, starting with the first sibling and ending with the given member, as constrained by the Year level in the Time dimension. Returns a set that contains the member specified by an MDX–formatted string. Returns the cross product of one or more sets as a set, excluding empty tuples and tuples without associated fact table data. Arranges members of a specified set, optionally preserving or breaking the hierarchy. Returns a set of sibling members from the same level as a given member, starting with the first sibling and ending with the given member, as constrained by a specified level in the Time dimension. Returns a set of sibling members from the same level as a given member, starting with the first sibling and ending with the given member, as constrained by the Quarter level in the Time dimension. Returns the siblings of a specified member, including the member itself. Returns a set generated by removing calculated members from a specified set. Returns the set specified by an MDX–formatted string. Returns a subset of tuples from a specified set. Returns a subset from the end of a set. Toggles the drill state of members. Sorts a set in descending order and returns the specified number of elements with the highest values. Sorts a set in descending order, and returns a set of tuples with the highest values whose cumulative total is equal to or less than a specified percentage. Sorts a set and returns the topmost elements whose cumulative total is at least a specified value. Returns the union of two sets, optionally retaining duplicates. Removes any enforced ordering from a specified set. Returns a set generated by dynamically totaling child members in a specified set, optionally using a pattern for the name of the parent member in the resulting cellset. Returns a set of sibling members from the same level as a given member, starting with the first sibling and ending with the given member, as constrained by the Week level in the Time dimension. Returns a set of sibling members from the same level as a given member, starting with the first sibling and ending with the given member, as constrained by the Year level in the Time dimension.

String Functions CalculationPassValue CoalesceEmpty Generate IIf LookupCube

Returns the value of an MDX expression evaluated over the specified calculation pass of a cube. Coalesces an empty cell value to a number or string and returns the coalesced value. Applies a set to each member of another set, and then joins the resulting sets by union. Alternatively, this function returns a concatenated string created by evaluating a string expression over a set. Returns one of two values determined by a logical test. Returns the value of an MDX expression evaluated over another specified cube in the same database.

MemberToStr Name Properties SetToStr TupleToStr UniqueName UserName Subcube Functions This Leaves Tuple Functions Current Item (Tuple) Root StrToTuple Other Functions Error

Returns an MDX–formatted string that corresponds to a specified member. Returns the name of a dimension, hierarchy, level, or member. Returns a string, or a strongly-typed value, that contains a member property value. Returns an MDX-formatted string of that corresponds to a specified set. Returns an MDX–formatted string that corresponds to specified tuple. Returns the unique name of a specified dimension, hierarchy, level, or member. Returns the domain name and user name of the current connection. Returns the current subcube. Returns the set of leaf members in the specified dimension, member, or tuple. Returns the current tuple from a set during iteration. Returns a tuple from a set. Returns a tuple that consists of the All members from each attribute hierarchy in a cube, dimension, or tuple. Returns the tuple specified by an MDX–formatted string. Raises an error, optionally providing a specified error message.

Related Documents

Essbase Mdx
July 2020 4
Examples
June 2020 21
Examples
October 2019 40