MAQL Reference Guide

100
MAQL Reference Guide Document publish date: 10/25/14 Copyright © GoodData Corporation 2007 - 2014 All Rights Reserved.

description

MAQL

Transcript of MAQL Reference Guide

  • MAQL Reference GuideDocument publish date:10/25/14

    Copyright GoodDataCorporation2007 - 2014All Rights Reserved.

  • Copyright GoodDataCorporation2007 - 2014All Rights Reserved.

    This document may not be reproduced, modified or distributed without the priorwritten permission of GoodDataCorporation.

    GOODDATACORPORATION PROVIDES THIS DOCUMENTATION AS-IS ANDWITHOUT WARRANTY, AND TO THE MAXIMUM EXTENT PERMITTED,GOODDATACORPORATION DISCLAIMS ALL IMPLIED WARRANTIES,INCLUDINGWITHOUT LIMITATION THE IMPLIED WARRANTIES OFMERCHANTABILITY, NON-INFRINGEMENT AND FITNESS FOR A PARTICULARPURPOSE.

  • MAQL Reference Guide Page #3

    Table of Contents

    Table of Contents 3

    Introduction to MAQL 8

    MAQLTopics 9

    Basic Elements 10

    Project Hierarchy 10

    Logical Data Model 11

    Creating Metrics in the Custom Metric Editor 12

    Accessing the Custom Metric Editor 12

    Using the Custom Metric Editor 12

    Custom Metric Editor Text Field 13

    Project Element Sidebar 15

    Local and Global Settings For Metrics 16

    Custom Metric Editor- MAQL Reference 16

    Basic MAQL Syntax 17

    Project Elements Must Be Inserted from the Sidebar 17

    Using MAQL Aggregations to Form Metrics 18

    Aggregation Functions 18

    SUM 18

    AVG 19

    MIN 19

    MEDIAN 20

    COUNT 20

    Copyright GoodDataCorporation 2007 - 2014All Rights Reserved.

  • MAQL Reference Guide Page #4

    Counting Attribute Values In Specific Data Sets 21

    PERCENTILE 23

    Variance functions 25

    Standard Deviation functions 26

    Covariance functions 28

    CORREL 29

    Least-Squares functions 31

    Arithmetic Operations 33

    Adding, Subtracting, Multiplying, and Dividing 33

    Numerical Variables 33

    Mathematical Functions 35

    ABS 35

    SIGN 35

    SQRT 36

    LOG 36

    LN 37

    EXP 37

    POWER 38

    Running Total Functions 39

    Applying running totals through Simple Metric Editor 41

    Applying running totals to attributes 41

    RUNSUM / RUNAVG / RUNMIN / RUNMAX 43

    RUNSTDEV / RUNSTDEVP / RUNVAR / RUNVARP 44

    Rounding and Truncation Functions 46

    Copyright GoodDataCorporation 2007 - 2014All Rights Reserved.

  • MAQL Reference Guide Page #5

    ROUND 46

    FLOOR 47

    CEILING 47

    TRUNC 48

    Filtering Data 49

    Filtering with the WHERE Clause 52

    Operators for Defining Filters 52

    Equals operator 52

    Does not equals operator 53

    Other relational operators 53

    IN 54

    NOT IN 55

    BETWEEN 55

    NOT BETWEEN 56

    Referencing Floating Time Periods 56

    THIS Macro 56

    PREVIOUS Macro 57

    NEXT Macro 58

    Logical Expressions for Combining Filters 58

    NOT 58

    OR 58

    AND 59

    Adding Filtered Variables to Metric Definitions 59

    Copyright GoodDataCorporation 2007 - 2014All Rights Reserved.

  • MAQL Reference Guide Page #6

    Filter with the HAVING Clause 60

    Overriding Report Filters 62

    PARENT Keywords 63

    WITHOUTPARENT FILTER 64

    WITHOUTPARENT FILTEREXCEPT 65

    WITHPARENT FILTER 67

    WITHPARENT FILTEREXCEPT 68

    Conditional Statements 70

    IF THEN ELSE 70

    CASE 71

    IFNULL 71

    Time Transformations 73

    Functions For Referring to Past Time Periods 73

    FOR Previous 73

    FOR PreviousPeriod 75

    FOR Previous vs. FOR PreviousPeriod 75

    Functions For Referring to Future Time Periods 76

    FOR Next 76

    FOR NextPeriod 77

    FORECAST - Add a Trend Line to a Report 78

    Rank 80

    Rank Variations 83

    RANKwithout WITHIN 83

    RANKwith WITHIN 84

    Copyright GoodDataCorporation 2007 - 2014All Rights Reserved.

  • MAQL Reference Guide Page #7

    WHERE TOP|BOTTOM(n) IN 85

    WHERE TOP|BOTTOM(n) OF 85

    Overriding Report Attributes 87

    Keywords for Overriding Report Attributes 87

    BY 87

    BY ALL 89

    BY attribute ALL IN ALL OTHER DIMENSIONS 91

    BY ALL IN ALL OTHER DIMENSIONS 92

    BY ALL IN ALL OTHER DIMENSIONS EXCEPT FOR attribute 93

    Appendix: MAQL Expression Reference 94

    Copyright GoodDataCorporation 2007 - 2014All Rights Reserved.

  • Introduction to MAQLThe following guide provides an overview of the Multi-Dimension Analytical QueryLanguage (MAQL) that is used to define metrics in the GoodDataPortal.

    MAQL has two extensions: Data Definition Language (DDL) and Data Query Language(DQL). MAQL DDL is briefly introduced below, but the primary focus of this guide will beon using MAQL DQL to define project metrics.

    MAQL has two main extensions, but this guide will primarily focus on using MAQL DQLto define project metrics.

    MAQL Data Definition Language (DDL) is used to build a projects data model, whichspecifies the relationship between the facts and attributes that provide the foundation forany project. Most users do not interact directly with MAQLDDL.

    MAQLDDLstatements are executed as part of normal operations of CloudConnectDesigner. This application is a proprietary end-to-end ETL data-loading tool, platform,and data modeler. CloudConnect allows you to extract, transform and load data frommultiple sources and design your projects logical data models through a graphical userinterface. For more information on CloudConnect or MAQL DDL, please visit DeveloperPortal.

    MAQL Data Query Language (DQL) will be the focus of the remainder of this guide.DQL is the MAQL extension that you can use within the GoodDataPortal(and morespecifically, within the Advanced Metric Editor dialog) to tap a number of theapplications advanced metric-building features.

  • MAQLTopicsThe primary mission of the GoodData Platform is to help you gain business insights fromyourmetrics those numerical values that populate your reports and widgets. This guideaims to introduce the MAQL syntax that can be used to define advanced metrics in theCustom Metric Editor.

    In the coming sections well explore the following topics:

    l Basic concepts

    l Accessing and using the Custom Metric Editor

    l Defining metrics with MAQL syntax in order to:

    l Aggregate facts to form the foundation of each metric

    l Perform arithmetic operations on predefined metrics

    l Use various mathematical functions within metric definitions

    l Calculate running totals of other project facts and metrics

    l Filter subsets of data to be included or excluded in a metrics computations

    l Return different values or carry out different computations, conditional uponthe values of other project metrics

    l Transform which time period each metric value in a report relates to

    l Use ranking functions to sequentially rank or filter report values

    l Use keywords to customize how a metric is affected by attributes and filterswithin any report to which it is added

    As you can see, metrics are powerful tools for anyone seeking business insights fromtheir data. But metrics are only useful when integrated into well-designed reports anddashboards. For more information, see GoodData Reference Guide (PDF).

  • Basic ElementsMAQL DQL (from this point on, simply referred to as MAQL) is primarily used as a way tobuild advanced reporting metrics. In order to understand the power of metrics defineddirectly through MAQL it will be important to have a grounding in common terminologyused in the GoodData Platform.

    Project HierarchyYour projects are organized into dashboards, dashboard tabs, reports, and the metricsthat are contained within those reports. At the lowest level, facts, attributes, and sourcedata represent the foundational components that are aggregated to form the metricsdisplayed in dashboard reports.

    Figure: Project Hierarchy

  • Logical Data ModelA Logical Data Model (LDM) is a model of the relationships between all of the facts andattributes within a project. As such, it defines which of a projects attributes can be usedto break each metric (an aggregation of facts).

    LDMs are typically visualized as oriented graphs like the simplified one below. The LDMshows five attributes (in rectangles), including two date dimensions, Date Created, andDate Closed, all of which relate to some sales opportunity. From the oriented graph, wecan tell that each opportunity in the data set has several facts attached to it, includingnumerical values that represent the amount of money that the opportunity is worth andthe probability the opportunity will be won.

    Figure: An oriented graph of an LDMwith five attributes (in rectangles) and two facts (ovals).

  • Creating Metrics in the Custom Metric EditorThe remainder of this guide will explore how you can create custom metrics in the MetricEditor Dialog. This section explains how to access the Metric Editor and how to use theEditors core features.

    Project users with the editor or administrator role can create new metrics from the MetricEditor Dialog within the Manage Page. You can also create new metrics from the ReportPage, while defining what a report will be measuring.

    NOTE:When you create or save a copy of a metric, report, ordashboard, it is unlocked for editing and visible only to you at first.When it is ready to share with other users in the project, you mustpublish the object. For more information, see ManagingPersonalObjects in GoodData Reference Guide (PDF).

    Accessing the CustomMetric EditorTo access the Metric Editor from the Manage Page:

    1. SelectManage from the Navigation Bar.

    2. Select the Data tab and then Metrics.

    3. Click + Create Metric.

    To access the Metric Editor from the Report Page:

    1. Click a reports name from the Report Directory or click the Create Report button.

    2. SelectWhat and then click (Advanced) next to + Add New Metric.

    Using the CustomMetric EditorWhen the Metric Editor is first opened, you are presented with four options. The firstthree, Share (in %), Difference, and Ratio are Metric Wizards that provide a structure forcreating specific types of advanced metrics with MAQL.

    l For more information on Metric Wizards, see GoodData Reference Guide (PDF).

    This section will focus on the fourth option for creating metrics: Custommetric.

  • NOTE:When you create or save a copy of a metric, report, ordashboard, it is unlocked for editing and visible only to you at first.When it is ready to share with other users in the project, you mustpublish the object. For more information, see ManagingPersonalObjects in GoodData Reference Guide (PDF).

    The Custom Metric Editor provides an interface that serves as a guide for creating yourown metrics in MAQL, a proprietary data querying language.

    Figure: This guide focuses on using MAQL to define metrics from scratch in the CustomMetricEditor.

    Custom Metric Editor Text Field

    From the Custom Metric Editor you can define a metric by entering statements using theproprietary MAQL data query language directly into a text field.

  • Figure: From the CustomMetric Editor you can define a metric by entering the proprietary MAQLdata query language.

    Project elements in your MAQL definitions are automatically color-coded so you cankeep track of which elements youve included in your metric and ensure your MAQLsyntax is valid.

    Figure: Formatting styles highlight the project elements that appear in MAQLmetric syntax.

    Project elements are distinguished by the following colors: Facts, Metrics,Attributes, Attribute Values, Variables.

    MAQL syntax must be valid in order for a custom metric to be saved. In the event that youtry to save a metric with invalid MAQL syntax, you will be prompted with an alert that willhelp you pinpoint the issue.

    In the following example, the SELECT keyword is missing from the start of the metricsdefinition. All MAQL definitions begin with SELECT.

    Figure: Improper MAQL syntax results in a warning message when ametric is saved.

  • Project Element Sidebar

    The sidebar to the right provides an organized directory of all the projects elements(facts, metrics, attributes, attribute values, and variables)all in the form of snippets thatcan be inserted directly into your metrics definition.

    NOTE:While MAQL syntax can typically be typed directly into theMetric Editor text field, project elements like facts,metrics, attributes,attribute values, and variables must be added to metric definitionsusing the Project Element Sidebar.

    Click an elements heading to view its contents.

    Figure: The Project Element Sidebar is used to select and insert project elementslike facts,metrics, attributes, attribute values, and variablesto metric definitions written in MAQL.

    When you find an element of interest, double click it, or select it and click Add Selected,to insert it into your metrics MAQL definition in the text field.

    Figure: Double-click Project Elements in the sidebar to insert them into metric definitions.

  • Local and Global Settings For Metrics

    New metrics created from the Report Editor can either be left local (report-specific) ormade global (available to all project users for use in other reports within the sameproject).

    New metrics that are created from the Report Editor are local by default, but can bemade global by selecting the Add to Global Metrics checkbox in the Metric Editor.

    Figure: The Add to Global Metrics checkboxmakes the newmetric available for use in otherreports within a given project.

    In the case where a user deletes a global metric that is being used in one or more report,the metric is removed from the list of global metrics but remains as a local metric withinthe reports in which it already appears.

    New metrics that are created from the Manage Page are global by default.

    Custom Metric Editor- MAQL Reference

    For more information on the functions available in the Custom Metric Editor, seeMAQLReference Guide (PDF).

  • Basic MAQL SyntaxMAQL syntax is used to define metrics in the Custom Metric Editor.

    The first thing youll need to know when writing custom metric definitions is that everymetric definition is preceded with the SELECT command. Think of this command in termsof making a request to the data warehouse, and selecting which information youd like tobe returned.

    This is the case when you are using MAQL syntax to aggregate a fact into a metric:

    SELECT SUM(Payments)

    You will also use SELECT to introduce one or more predefined metrics within a metricdefinition:

    SELECT Payment_metric / (SELECT Payment_metric BY Year)

    In the first example above, the MAQL statement defines a metric that computes the sumtotal of all Payment fact values across all available records in the current project.

    Tip:MAQL queries begin with SELECT.

    Project Elements Must Be Inserted from the SidebarAs mentioned in the previous section, while the MAQL expression directory beneath theCustom Metric Editors text field can come in handy for formulating correctly structuredexpressions, MAQL expressions can also be typed directly into the Custom MetricEditors text field.

    An important exception is with project elements, such as facts,metrics, attributes,attribute values, and variables. These must be added to metric definitions using theProject Element Sidebar.

  • Using MAQL Aggregations to Form MetricsAs individual numerical measurements, facts arent very interesting on their own. Inorder to pull interesting insights from your data, youll want to aggregate facts intometrics. These metrics will be what your reports measure.

    While all metrics are fundamentally aggregations of facts, thats not to say they dontcontain other interesting features as well. Later on in this guide well discuss optionalmetric customizations. These include using arithmetic to operate on metrics, filtering outcertain subsets of data in metric computations, adding mathematical functions andconditionals to metric definitions, and using MAQL keywords to specify how metrics areaffected by the reports within which they reside. But first well revisit the idea that the onething common to all metrics is a foundation composed of an aggregation of some fact (orset of attribute values).

    Aggregation FunctionsDashboards and reports allow you to gain insights from your business metrics whichdetermine what will be computed in any given report. Metrics are really just aggregationsof facts. Here, when say fact we mean a numerical record that represents an individualbusiness transaction. In other words, facts are the numbers youd find in each cell of aspreadsheet.

    Examples of facts might include:

    l Revenue earned from a sale

    l Cost of some item purchased

    l The hours worked by one employee

    l The number of items shipped in one delivery

    Facts can be aggregated by any of four operations, explained in the following sections.

    SUM

    Description

    Adds facts together to form a metric.

    Syntax

    SELECT SUM()

  • SELECT SUM(fact)

    Examples

    The metric defined by the SUM of the Sales fact would be computed by adding revenueearned from all individual sales transactions:

    SELECT SUM(Sales)

    AVG

    Description

    Calculates the mean of a set of facts to form a metric.

    Syntax

    SELECT AVG()

    SELECT AVG(fact)

    Examples

    The metric AVG of Payment is computed by adding all payment transactions togetherand dividing by the number of payment transactions:

    SELECT AVG(Payment)

    MIN

    Description

    Identifies the lowest value from a set of facts.

    Syntax

    SELECT MIN()

    SELECT MIN(fact)

    Examples

    The MIN of the Opportunity Amount fact is the lowest opportunity amount value onrecord:

    SELECT MIN(Opportunity_Amount)

  • MEDIAN

    The MEDIAN() function is especially useful in cases where a small set of outliers coulddrastically skew the average if calculated as a mean.

    MEDIAN() can be used to aggregate facts in the same way as SUM(), MAX(), MIN(), orAVG(), but it also accepts metrics or entire metric expressions as arguments.

    Description

    Returns the middle value of a set of data, such that half of the values are smaller and halfof the values are larger. For sets with an even number of values, the median iscalculated by finding the mean of the middle two values.

    Syntax

    SELECT MEDIAN()

    MEDIAN(fact)

    MEDIAN(metric)

    MEDIAN(metric_expression)

    Examples

    SELECT MEDIAN(Cost) BY ALL OTHER

    SELECT MEDIAN(Date (Closed) - Date (Opened)) BY Ticket_ID

    SELECT MEDIAN(Payment) BY Customer FOR PREVIOUS(Month)

    COUNT

    Description

    Counts the number of unique values belonging to an attribute.

    COUNT of Store will return the number of different stores based on the number of distinctvalues of the Store attribute.

    Syntax

    SELECT COUNT()

    SELECT COUNT(,)

    SELECT COUNT(attribute)

  • SELECT COUNT(attribute, connection_point*)

    * Where connection_point is the foreign key, connecting to the data set in which thecount is to take place.

    NOTE:You can refer to the following section for more information on the secondparameter of a COUNT operation.

    Examples

    SELECT COUNT(Store)

    SELECT COUNT(Employee, Facts_of_Call)

    Counting Attribute Values In Specific Data SetsCOUNT is different from the other aggregation operations in that it aggregates attributevalues rather than facts. It does so by counting the number of unique values belonging toan attribute. In the example below, the total number of employees could be computedwith the COUNT operation:

    SELECT COUNT(Employee)

    Figure: The Facts of Call, and Facts of Opportunity data sets are both related to the Employeedata set, but this doesnt mean the values of Employee are the same in each of the three datasets.

    But there are some limitations to this approach. Here, weve specified what wed like tocount, but not where it should be counted. This is important because the number ofunique employee values may be different in each of the three data sets insofar as some

  • employees may not be associated with any opportunities and other employees maynever have made a call. The end result is that the SELECT COUNT(Employee) metriccan only be broken down by the Name and Department attributes.

    Now consider the case where youd like to measure the number of employees who havemade a phone call. Because Facts of Call is connected to Employee in the logical datamodel above, we know that for every call that is made, the employee who made it is alsostored in the Facts of Call data set. To count the number of unique Employee valueswithin the Facts of Call data set, well incorporate a second parameter in our countfunction that establishes the data set in which the count will take place.

    To count the number of unique employee values in the Facts of Call data set we wouldformulate our count metric in the following way:

    SELECT COUNT (Employee, Facts_of_Call).

    Tip: The first parameter in the COUNT syntax represents the attributewhose values you wish to count. The second parameter specifies inwhich dataset those attribute values should be counted.

    Figure: In the Metric Editor, the COUNT function includes two parameters.

    As a second example, consider the (Customer Support) Tickets, Employees, and Payrolldata sets below. Ticket_ID and Salary each represent connection points from theirrespective data sets to the Employee data set.

    So while counting the total number of employees could be carried out with a COUNT(Employee) metric, this renders the Tickets and Payroll datasets unusable. Using thismethod, it would not be possible to count the number of employees who have resolved acustomer support ticket, nor would it be possible to count the number of employees whoare on payroll.

  • Figure: The Tickets and Payroll data sets share a common data setthat of Employees. TheEmployee, Ticket_ID, and Salary attributes are the primary key attributes in their respectivedata setseach representing a unique value.

    Again, a second parameter must be added to the COUNT operation in order to designatethe data set within which the COUNT will take place.

    To count the number of employees who have responded to at least one customersupport ticket, the following syntax should be used:

    SELECT COUNT(Employee, Ticket_ID)

    To count the number of employees who are on payroll, the following syntax should beused:

    SELECT COUNT(Employee, Salary)

    In this case, the values of the attribute Salary are unique ID numbers that identify eachemployee who is on payroll.

    PERCENTILE

    Description

    The Percentile function is the latest of a series of extensions made to MAQL, aproprietary query language for defining custom metrics. PERCENTILE() returns thespecified percentile out of some set of values. This could be useful for establishing athreshold of acceptance, such as for candidates who score above the 90th percentile ona certification exam, or rewarding sales reps in the top percentile with regard to dealswon in the past year.

  • l PERCENTILE(numeric, k)

    l where numeric is a fact or metric

    l where k is a value between 0 and 1 representing the percentile you wantreturned specified as a decimal. k accepts constants as inputs. Numericvalues must be expressed in the following format:0.xx

    l For metric expressions, you should compute percentiles using syntax similarto the following:SELECT PERCENTILE((SELECT SUM([fact]) BY[attribute]),0.25)

    l PERCENTILE(numeric, k%)

    l where numeric is a fact or metric

    l where k% is a number between 0 and 100 representing the percentile youwant returned. k accepts constants as inputs, followed by percent signs asinputs.

    l For metric expressions, you should compute percentiles using syntax similarto the following:SELECT PERCENTILE((SELECT SUM([fact]) BY[attribute]),25%)

    Syntax

    SELECT PERCENTILE() [ASC|DESC] [BY()]

    SELECT PERCENTILE(metric, decimal)

    SELECT PERCENTILE(metric, percentage)

    SELECT PERCENTILE(fact, decimal)

    SELECT PERCENTILE(fact, percentage)

    SELECT PERCENTILE((SELECTSUM([metric]) BY[attribute]),decimal)

    SELECT PERCENTILE((SELECTSUM([metric]) BY[attribute]),percentage)

    Examples

  • SELECT PERCENTILE(Amount, 0.75)

    SELECT PERCENTILE(Amount, 75%)

    Variance functions

    Description

    Variance measures the spread of values within a single a single set of values. Thisbasic computation is used to build standard deviation and other statistical functions.

    To measure spread, variance calculates the mean of all values in the sample. For eachinput value in the set, the difference of the value from the mean is computed, and thisdifference is squared. All of the squares are added together, and then divided by asample size factor, depending on the function you are using.

    l Values for variance are non-negative. A value of 0 indicates that there is novariance among the values; all values are identical.

    l The square root of variance is the standard deviation. See Standard Deviation.

    l Covariance measures how two sets of values change together. See Covariance.

    Figure: Equation - Variance

    The spread is measured for a sample of the (biased)population (VAR) or for the entire(unbiased)population (VARP).

    l For a sample of the population, use the VAR function, which divides the sum ofsquares by the number of values in the same size (N-1).

    l If the set of values is the entire population of values, use the VARP function, whichdivides the sum of squares by N:

    Figure: Equation - Variance for Populations

  • l l VAR (numeric)

    l where numeric is a fact or metric

    l Computes the sum of squared differences from the mean for n valuesdivided by n-1]

    l VARP (numeric)

    l where numeric is a fact or metric

    l Computes the sum of squared differences from the mean for n values dividedby n]

    Syntax

    SELECT VAR()

    SELECT VAR(metric)

    SELECT VARP(fact)

    Examples

    SELECT VAR(Internal Rate of Return)

    SELECT VARP(Gross Weight)

    Standard Deviation functions

    Description

    Standard deviation functions measure the dispersion around the mean among arandomly distributed set of values.

    Standard deviation is useful for measuring variance within a data set and, in application,confidence in statistical results. For example, in finance, standard deviation maymeasure the potential deviation from expected return rate, measuring the volatility of theinvestment. Depending on the number of values in the sample set, you should use eitherof the following metrics.

  • Figure: Equation - Standard Deviation

    l STDEV (numeric)

    l where numeric is a fact or metric

    l Computes the sum of squared differences from the mean for n values dividedby a sample size factor. If the input values are a sample of the total (biased)population, the divisor is (n - 1) sample size, which is used in the STDEVfunction.

    l This value is the variance. See Variance. The square root of the above valuerepresents the standard deviation.

    NOTE:If individual values are used as inputs, STDEV, generatesa null value. In these cases, use STDEVP instead.

    l The STDEVfunction is also known as the corrected standard deviation.

    Figure: Equation - Standard Deviation for Populations

    l STDEVP (numeric)

    l where numeric is a fact or metric

    l Computes square root of [the sum of squared differences from the mean for nvalues divided by n ]

    l Use STDEVP for calculating standard deviations if the input set contains theentire (unbiased)population of values. The deviation for a single value iszero.

  • l The STDEVPfunction is also known as the uncorrected standarddeviation.

    Syntax

    SELECT STDEV()

    SELECT STDEV(metric)

    SELECT STDEVP(fact)

    Examples

    SELECT STDEV(Internal Rate of Return)

    SELECT STDEVP(Gross Weight)

    Covariance functions

    Description

    Covariance measures how two sets of values vary together. This elementary function isused as a building block for some of the two-dimensional statistical functions used inlinear regression, as it describes collectively how the two sets of values vary aroundtheir mean values.

    l If your sets of values are only a sample of the total (biased)population, use theCOVAR function.

    l For sets that include the entire (unbiased)population, use COVARP.

    Figure: Equation - Covariance

    l COVAR (numeric1, numeric2)

    l where numeric1 and numeric2 are facts or metrics

    l Computes the product of variance from mean for each value of x and y.These values are summed and then divided by (n]

  • Figure: Equation - Covariance for Populations

    l covarp (numeric1, numeric2)

    l where numeric1 and numeric2 are facts or metrics

    l Use covarp for calculating covariances when the numeric values are theentire population of values.

    Syntax

    SELECT COVAR()

    SELECT COVAR(metric1, metric2)

    SELECT COVAR(fact1, metric2)

    SELECT COVAR(fact1, fact2)

    SELECT COVARP(metric1, metric2)

    SELECT COVARP(fact1, metric2)

    SELECT COVARP(fact1, fact2)

    Examples

    SELECT COVAR(Total Cost of Inputs, Gross Margin)

    SELECT COVARP(Height,Weight )

    CORREL

    Description

    Correlation coefficient measures the degree of association between two sets of values.Values for correlation coefficient range from -1 to 1.

    l A value of 1 indicates that as X increases, Y always increases.

    l A value of -1 indicates that as X increases, Y always decreases.

  • l A value of 0 indicates that there is no correlation; values for X cannot be used aspredictors for values of Y.

    Correlation coefficient is measured by calculating the covariance of the two sets ofvalues, which measures how they vary with each other. This measure is then divided bythe product of the standard deviations of each set of values.

    l See Covariance.

    l See Standard Deviation.

    l Correlation coefficient is a component calculation of the Least-Squares method oflinear regression. See Least-Squares functions.

    Figure: Equation - Correlation Coefficient

    When this equation is broken down into its component parts, it becomes the following:

    Figure: Equation - Correlation Coefficient decomposed

    l CORREL (numeric1,numeric2)

    l where numeric1 and numeric2 are facts or metrics

    Syntax

    SELECT CORREL()

    SELECT CORREL(metric1,metric2)

    SELECT CORREL(metric1,fact2)

    SELECT CORREL(fact1,fact2)

    Examples

    SELECT CORREL(Production Volume, Rate of Defects)

  • SELECT CORREL(Gross Tonnage, Gross Profit)

    Least-Squares functions

    Description

    The least-squares method of linear regression attempts to fit a linear regression trendline as closely as possible. This line has the smallest possible value for the sum of thesquares of the errors between the predicted value of the line and the actual two-dimensional data points.

    Figure: Least-Squares linear regression diagram

    In the above diagram, the least-squares linear regression plots a line through the set ofpoints that minimizes the sum of the squares of the error factors. The actual data pointsare calculated using the following equation:

    Figure: Least-squares data points

    The R-squaredfunction can be used to measure how well the linear regressionexpresses the variability of the Yvalues around their mean.

  • l RSQ (numeric1, numeric2)

    l where numeric1 and numeric2 are facts or metrics

    l Computes the R-squared value for the two sets of numeric values. Alsoknown as the coefficient of determination, R-squared ranges between 0and 1, with a value of 1 indicating that the model explains all variability in thedependent variables data.

    NOTE:R-squared does not determine if there is bias in the estimates.

    Syntax

    SELECT RSQ(metric1,metric2)

    SELECT RSQ(fact1,metric2)

    SELECT RSQ(fact1,fact2)

    Examples

    SELECT RSQ(Count of Defects, Production Volume)

  • Arithmetic OperationsAfter a fact has been aggregated and saved as a metric, it can be used as a componentof another metric. Predefined metrics can be manipulated with any basic arithmeticoperation: addition (+), subtraction (-), multiplication (*), and division (/).

    Adding, Subtracting, Multiplying, and Dividing

    Description You can add, subtract, multiply, or divide predefined metrics.Syntax SELECT metric1 + metric2

    SELECT metric1 - metric2

    SELECT metric1 * metric2

    SELECT metric1 / metric2

    Examples SELECT Expenses + Salary

    SELECT Revenues - Costs

    SELECT Profit * 0.03

    SELECT New_Revenue / Revenue_Last_Year

    NOTE:Where Expenses, Salary, Revenues, Costs, Profit, New_Revenue, and Revenue_Last_Year are predefined metrics.

    Numerical Variables

    You can also introduce dynamic values into arithmetic operations within MAQL. Thesevalues, known as numerical variables, can be assigned to specific project members bya project administrator in the Manage section of the GoodDataPortal. In the examplebelow, a variable is used to calculate the users sales commissions.

    Description

    Variables with user-specific dynamic values in arithmetic expressions

    Syntax

    SELECT metric1 * variable

    Examples

  • SELECT Amount_Won * commission_rate_variable

  • Mathematical FunctionsMathematical functions like absolute value, signum and square root are useful forcarrying out statistic computations. Logarithmic and exponential functions, introducedlater in this section are commonly used in predictive analytics to create regressions.

    ABSDescription

    The absolute value function returns a number or metric input as a positive number.Positive inputs will remain unchanged. Negative inputs will be rendered positive.

    Syntax

    SELECT ABS()

    SELECT ABS(number)

    SELECT ABS(metric)

    Examples

    SELECT ABS(-5) returns the value 5

    SELECT ABS(10) returns the value 10

    SELECT ABS((Total_Amount)-(SELECT Total_Amount WITHOUT PF))

    SIGNDescription

    The signum function returns a number or metric input as one of three values, conditionalupon the value of the input. For inputs greater than zero, signum returns the value 1.For inputs equal to zero, signum returns the value 0. For inputs less than zero, signumreturns the value -1. In effect, signum follows the rule:

    SIGN(number_input) = (number_input)/(abs(number_input))

    Syntax

    SELECT SIGN()

    SELECT SIGN(number)

  • SELECT SIGN(metric)

    Examples

    SELECT SIGN(-3) returns the value -1

    SELECT SIGN(3) returns the value 1

    SELECT SIGN(0) returns the value 0

    SQRTDescription

    The square root function returns the square root of a number or metric input. Negative orcomplex inputs result in a null output.

    Syntax

    SELECT SQRT()

    SELECT SQRT(constant)

    SELECT SQRT(metric)

    Examples

    SELECT SQRT(25) returns the value 5

    SELECT SQRT(33.6) returns the value 5.796550698

    SELECT SQRT(SELECT SUM(Sales)) returns the square root of aTotal Sales metric

    LOGDescription

    The LOG(n,b) function returns the logarithm, base b, of n where:

    l n is any positive value

    l The base, b, is any positive value other than 0 or 1

    This function takes as arguments any numeric data, including constants, metrics, ormetric expressions. If no base is specified, the default base of 10 is applied.

    Syntax

  • SELECT LOG()

    SELECT SQRT(number, base)

    Examples

    SELECT LOG(10, 1/12)

    SELECT LOG(SUM(Amount), 2)

    SELECT LOG(Amount[Max] * 400, Amount[Max])

    LNDescription

    LN(n) returns the natural logarithm of n, where n is greater than 0. A natural logarithm isthe inverse of the EXP() function; LN() returns the logarithm of a number with basee, the constant 2.71828182845904. LN() takes as arguments any numeric data,including metrics, metrics expressions, and constants.

    Syntax

    SELECT LN()

    SELECT LN(number)

    Examples

    SELECT LN(10)

    SELECT LN(1/12)

    SELECT LN(1.5)

    SELECT LN(SUM(Amount))

    EXPDescription

    The inverse of the LN(n) function, EXP(n) returns the value of the constant e,2.71828182845904, raised to the power of the positive real number, n, that is specified.EXP() takes as arguments any numeric data, including metrics, metrics expressions,and constants.

    Syntax

  • EXP()

    EXP(number)

    Examples

    SELECT EXP(10)

    SELECT EXP(1/12)

    SELECT EXP(1.5)

    SELECT EXP(SUM(Amount))

    POWERDescription

    POWER(n, b) returns n raised to the b power.

    The base n and the exponent b accept any numeric data, including metrics, metricexpressions, and constants.

    NOTE: For fractional exponent (b) values, using fractions (e.g. 1/2)rather than decimals (e.g. 0.5) improves performance.

    Syntax

    POWER(,)

    POWER(number, power)

    Examples

    SELECT POWER(10, 1/12)

    SELECT POWER(SUM(Amount), 2)

    SELECT POWER(1, SUM(Amount))

    SELECT POWER(Total_Amount * (1/2), Total_Amount)

  • Running Total FunctionsA running total is a calculation based on input values that are known so far. Forexample, in the table below, you can see that a running summation total (RUNSUM) iscalculated for the values in the Units column that have occurred up to the current date,yielding a Month to Date (MTD) calculation. When this column is added to a running sumacross months, a YTD calculation is available:

    Date Units MTD YTD05/28/2014 2 77 19105/29/2014 3 80 19405/30/2014 6 86 20006/02/2014 2 2 20206/03/2014 3 5 20506/04/2014 1 6 20606/05/2014 2 8 20806/06/2014 3 11 21106/09/2014 4 15 21506/10/2014 1 16 21606/11/2014 3 19 219

    In the above example, the Running Sum values provide insight into the total Units thathave been recorded so far for the month and year. Running total functions provide aneffective method for creating snapshots of metric values over an interval of date orattribute values.

    NOTE: Running totals for attribute values may be applied only throughthe secondary-click menu. Some running total functions are notavailable. See Applying running totals to attributes.

    For example, you can use running totals to identify how Sales are tracking towardexpected goals for the reporting period. The table below renames the columns of theprevious table and adds new columns to support this Sales example:

    Date Sales MTD Expected MTD Difference05/28/2014 2 77 75 +2

  • 05/29/2014 3 80 80 005/30/2014 6 86 85 +106/02/2014 2 2 2 006/03/2014 3 5 4 -106/04/2014 1 6 6 006/05/2014 2 8 8 006/06/2014 3 11 10 +106/09/2014 4 15 12 +306/10/2014 1 16 14 +206/11/2014 3 19 16 +3

    Running total functions can be created like any other metric and have broad applicationacross a variety of transactional data.

    l Running totals can be computed for multiple types of aggregation functions.Supported running functions include average minimum, maximum, and sum, aswell as statistical functions such as standard deviation and variance.

    l In addition to date dimensions, some running totals can be applied to knownvalues of attributes through the secondary-click menu.

    Using running totals and WITHIN keyword:

    The WITHIN keyword can be applied to MAQL definitions of running total metrics tospecify the scope within which running totals are maintained. For example, if you addWITHIN (Quarter) to your MAQL definition for your running total metric, the total ismaintained throughout a quarter and restarts calculation at the start of the next quarter.

    NOTE: The WITHIN keyword can reference date attributes only.Examples are available in the topics listed below.

    l For more information on running total functions for basic aggregation functions, seeRUNSUM/RUNAVG/RUNMIN/RUNMAX.

    l For more information on statistical running total functions, seeRUNSTDEV/RUNSTDEVP/RUNVAR/RUNVARP.

  • Applying running totals through Simple Metric EditorRunning total functions can be inserted through the Simple Metric Editor into metrics thatyou are building for your report.

    l Select the function to apply from the Operation drop-down and specify the otherfields of the metric definition.

    l All running total functions are available through the Simple Metric Editor.

    Figure: Running total functions in the Simple Metric Editor

    Applying running totals to attributesSome running totals may also be added for attribute values to report tables directlythrough the Report Builder interface.

  • Limitations:

    l The report must be of table type.

    l Inserting functions through the secondary-click menu does not add them to your listof available metrics. They exist as a single column in the report where they werecreated.

    l Some running total functions are not available through the secondary-click menu.These functions must be specified in metrics that you create through the SimpleMetric Editor or the Custom Metric Editor. See Applying running totals throughSimple Metric Editor.

    In the following example from the Super Soda demo project, total impressions arebroken down for each product by channel. To assist in identifying weaknesses in yourcampaigns, you could insert a Running Minimum function next to the Impressions.cmetric. Secondary-click the Impressions.c metric title in the report table and selectthe Running Minimum function from the sub-menu:

    Figure: Selecting Running Minimum function

    A new column is inserted to the right of the metric column computing running totals forthe selected columns cells:

  • Figure: Running total function inserted via secondary-click menu

    RUNSUM / RUNAVG / RUNMIN / RUNMAXDescription

    Takes the running sum, average, minimum, or maximum of a project fact or metric. In atable broken down by a date attribute, the running total value on any given day would becalculated by aggregating values from all prior days along with that of the current day.

    NOTE:Running total metrics can be broken down by two or more dateattributes from the same date dimension. Non-date attributes are notsupported.

    Syntax

    SELECT RUNSUM(...)

    SELECT RUNAVG(...)

    SELECT RUNMIN(...)

    SELECT RUNMAX(...)

    SELECT RUNSUM(...) WITHIN (...)

    l Value for WITHIN must be a date attribute.

    SELECT RUNSUM(...) WITHIN (ALL OTHER)

    Examples

    SELECT RUNSUM(Sales)

    SELECT RUNSUM(Sales) WITHIN(Week)

  • SELECT RUNSUM(Sales) WITHIN(Week) BY Date,Region

    SELECT RUNMIN(Probability) WHERE Year = THIS AND Amount >500000

    SELECT RUNMAX(Opportunity) BY Quarter/Year

    SELECT RUNMAX(Sales) WITHIN (Year) WITHOUT PARENT FILTER

    RUNSTDEV / RUNSTDEVP / RUNVAR / RUNVARPDescription

    Calculates the standard deviation or variance using all values up to the current date for afact or metric. Functions are available for standard deviation, variance, and versions ofthose functions for populations.

    l See Standard Deviation.

    l See Variance.

    Suppose you are tracking daily production for your enterprise throughout the month in asimple report tracking daily Units. You can use the RUNAVG and RUNSTDEV statisticalfunctions to track the reliability of estimates as the month begins to close:

    Date Units Running Avg Daily Units Running StDev06/02/2014 50 50.00 (blank value)06/03/2014 60 55.00 7.0706/04/2014 70 60.00 10.0006/05/2014 50 57.50 9.5706/06/2014 60 58.00 8.3706/09/2014 80 61.67 11.6906/10/2014 50 60.00 11.5506/11/2014 70 61.25 11.2606/12/2014 60 61.11 10.5406/13/2014 80 63.00 11.60

  • NOTE: Running total metrics can be broken down by two or more dateattributes from the same date dimension. Non-date attributes are notsupported.

    Syntax

    SELECT RUNSTDEV(...)

    SELECT RUNSTDEVP(...)

    SELECT RUNVAR(...)

    SELECT RUNVARP(...)

    SELECT RUNSTDEV(...) WITHIN (...)

    l Value for WITHIN must be a date attribute.

    SELECT RUNSTDEV(...) WITHIN (ALL OTHER)

    Examples

    SELECT RUNVAR(Sales)

    SELECT RUNSTDEVP(Leads) WHERE Year = THIS

    SELECT RUNVARP(Returns) WHERE Amount > 500000

    SELECT RUNSTDEV(Opportunities) WITHIN (Quarter/Year)

  • Rounding and Truncation FunctionsTo manage precision in your metric computations, MAQLsupports functions to controlhow values are rounded. You may use functions to round to the nearest integer or to adefined number of decimals of precision. For specific types of rounding, the FLOOR()and CEILING()functions round up and down, respectively, to the nearest integer. TheTRUNCATE()function removes digits of precision without applying any rounding.

    ROUNDThe ROUND() function enables the rounding of any input value to an integer (by default)or to a defined number of decimal points. This function allows metric builds to retainexact levels of precision throughout a set of calculations.

    l The first input value may be any constant, fact, metric, or metric expression.

    l The optional second parameter defines the number of decimal points to which thefunction applies rounding. This parameter should be an integer, although realnumbers are supported for input.

    Description

    Returns a value that is the input value rounded to the nearest value, as defined by thesecond parameter. If the second parameter is not specified, then the function rounds tothe nearest integer.

    Syntax

    SELECT ROUND()

    ROUND(fact)

    ROUND(metric)

    ROUND(metric_expression)

    ROUND(input, number_of_decimal_places)

    Examples

    SELECT ROUND(12.2) = 12

    SELECT ROUND(12.7) = 13

    SELECT ROUND(12.257,2) = 12.26

  • SELECT ROUND (12.257,-1) = 10

    FLOORThe FLOOR()function enables strict rounding of an input value to the closest integer thatis less than the value.

    Description

    Returns a value that is the closest integer that is less than the input value.

    Syntax

    SELECT FLOOR()

    FLOOR(constant)

    FLOOR(fact)

    FLOOR(metric)

    FLOOR(metric_expression)

    Examples

    SELECT FLOOR(12.2) = 12

    SELECTFLOOR(12.7) = 12

    CEILINGThe CEILING()function enables strict rounding of an input value to the closest integerthat is more than the value.

    Description

    Returns a value that is the closest integer that is more than the input value.

    Syntax

    SELECT CEILING()

    CEILING(constant)

    CEILING(fact)

    CEILING(metric)

  • CEILING(metric_expression)

    Examples

    SELECT CEILING(12.2) = 13

    SELECTCEILING(12.7) = 13

    TRUNCBy default, the TRUNC() function allows for the removal of all digits to the right of thedecimal point without applying rounding. If a second optional parameter is added to theTRUNC()function, it defines the number of digits to the right of the decimal point atwhich truncation is applied. Negative values are supported for the second parameter.

    l The first input value may be any constant, fact, metric, or metric expression.

    l The optional second parameter defines the number of decimal points at which theremaining digits are removed. This parameter should be an integer, although realnumbers are supported for input.

    Description

    Returns a value that is the input value truncated at the specified number of digits,specified in the second parameter. If the second parameter is not specified, the functionreturns a truncated integer.

    Syntax

    SELECT TRUNC()

    TRUNC(constant)

    TRUNC(fact)

    TRUNC(metric)

    TRUNC(metric_expression)

    TRUNC(input, number_of_decimal_places)

    Examples

    SELECT TRUNC(12.2) = 12

    SELECTTRUNC(12.7) = 12

  • SELECTTRUNC(12.257,2) = 12.25

    SELECTTRUNC(1255.257,-2) = 1200

    Filtering DataIn your analytical project, data can be filtered from display using the followingmechanisms:

    Filter Type DescriptionDataPermissionsFilter A DataPermissions filter is a attribute-based filter that is

    applied to all data queried from the datamart. These filtersenable project developers to filter content for specific users,so that sensitive or irrelevant data is masked from display tothe specified user.

    DataPermissionsfilters cannot be overridden. They arealways applied to any query executed by an affected userfrom the Portal.

    NOTE: DataPermissionsfilters areconsidered an administrator-levelconfiguration. For more information, seeLet's Get Started with Mandatory UserFilters.

    Dashboard Filter A dashboard filter can be used to filter the data to displayacross all reports in a dashboard. It is based on values for anattribute, dates, or defined groups that are chosen from aselector embedded in the dashboard.

    For example, users can choose a date or range of dates inthe dashboard filter, and the displayed data in all reports areupdated to show only the values that apply to the selecteddate(s).

    Report Filter Similar to a dashboard filter, a report filter changes the valuesthat are displayed in the report. However, report filters arespecified by the report builder and cannot be modified byViewers or Embedded Dashboard Only users in the project.

    Metric Filter Inside of a metric definition, you can filter the computed datausing a WHERE clause, which contains the conditions underwhich the selected data can be used in the computation.

  • Filter Evaluation

    In a dashboard, one or more of the above filters may be applied. How these filters areevaluated is based on the following rules:

    Rule: DataPermissionsfilters are always applied. They cannot be overridden or ignored.

    Rule: Dashboard filters change report filters on the specified attribute.

    l If there is a dashboard filter and a report filter on two different attributes, data mustmatch both filter conditions in order to appear in the report. In the MAQL query forthe report, a logical AND is applied between the filters.

    l For example, suppose the user selects the dashboard filter for the Statesattribute to be set to California. On one of the reports in the dashboard,there is a report filter set to Department=Distribution. In the report, abasic metric such as SELECT SUM(Sales) is filtered by both parent filters.The net result is that data is extracted from the fact table for this summationonly if it applied to States=California andDepartment=Distribution.

    l If the dashboard filter and report filter are on the same attribute, the dashboard filteroverrides the report filter.

    l Suppose there is a filter for the State attribute to be set to California inthe report definition. However, on a dashboard the user can select his ownState in a dashboard filter. If he or she chooses State = Nevada, thenthis selection only is applied to the report metrics.

    Rule: report filters are applied in addition to any metric filters.

    l Suppose the report filter is Group = X and the metric definition is SELECTSUM(Sales)WHERE Priority = Urgent. The effective filter on the calculatedmetric is the following: Group = X AND Priority = Urgent.

    Limitations

    Some filters cannot be applied with other filters. Examples:

    l If the report filter is set to Group = X and the metric filter is set to Group = Y,the generated value for the metric in the report is null. Both filters are applied to thedata, and it is not possible to have data associated with two values of an attribute.

  • l If two filters are set to conflicting attribute values in the same hierarchy, you maygenerate null data. For example, if the dashboard filter is set by a user to State =California, and the report filter is fixed on City = New York City, thereport contains no data.

    l Some filters cannot be applied to the metrics because no relation has been definedbetween the fact table and an attribute to be filtered. For example, you cannot filteryour sales metric (SELECT SUM(Sales)) by the attribute filter MarketingCampaign = TV, since marketing activities are tracked using different factsstored in a different fact table.

    NOTE: If the defined report filter is not valid for the metric due tohow the data model has been designed, the report filter isautomatically skipped during computation of any metrics in thereport.

    Filter Overrides

    At the metric level, you can insert keywords to override dashboard, metric, and reportfilters. For example, you can include the keyword WITHOUTPARENTFILTER in yourmetric definition, which prevents any filter in a parent object (metric, report, ordashboard)from being applied.

    l For more information on these filter overrides, see Overriding Report Filters.

  • Filtering with the WHERE ClauseAfter you have aggregated a fact to form the foundations of a metric, you can use MAQLsyntax to add filters to your metric definition. Filters are optional features that can beused to narrow the set of data from which a metric is computed. With logical expressions,its also possible to combine two or more filters within a single metric definition.

    The basic syntax for filters uses the word WHERE to introduce the filter expression:

    SELECT ... WHERE ...

    This section will explore several types of syntax for customizing metric filters:

    l Special operators for defining filters

    l e.g. SELECT Revenues WHERE Year = 2006)

    l Time macros for filtering for floating time periods:

    l e.g. SELECT Payment WHERE Date = THIS 1)

    l Logical expressions for combining filters

    l e.g. SELECT Revenues WHERE Year = 2006 AND Month = 5)

    Operators for Defining Filters

    Special operators are used in metric definitions to determine which data to include orexclude from metric computations. Operators help establish filters by specifying theconditions that determine whether any given fact value will be included or excluded fromcomputing the metric at hand.

    Because facts are categorized by attributes, filter conditions are defined by referring toparticular attribute values of interest (e.g. WHERE Year = 2007) or by referring toscenarios where two attributes have the same value (e.g. WHERE Date_Ordered =Date_Shipped). By specifying these conditions, you are able to delineate a widerange of fact values and specify whether they should be included or excluded frommetric computations.

    Equals operatorDescription

  • A filtering operator that includes only a single attribute value of interest. It can also beused to define the filter condition where two attributes have the same value.

    Syntax

    SELECT WHERE =

    SELECT metric WHERE attribute = attribute_value

    Examples

    SELECT Salary WHERE Year = 2007

    SELECT Revenues WHERE Month = THIS

    SELECT Expenses WHERE Quarter = PREVIOUS

    SELECT Expenses WHERE Quarter = THIS - 2

    SELECT Amount WHERE Date_Ordered = Date_Shipped

    Does not equals operatorDescription

    A filtering operator that excludes a single attribute value. This operator can also be usedto define the filter condition where two attributes have different values.

    Syntax

    SELECT WHERE

    SELECT metric WHERE attribute attribute_value

    SELECT metric WHERE attribute1 attribute2

    Examples

    SELECT Revenues WHERE Year 2006

    SELECT Amount WHERE Date_Ordered Date_Shipped

    Other relational operatorsDescription

    Relational operators can be used with facts, metrics, or attributes to define filterconditions within a metric definition.

  • When defining filters with attributes, the unique numerical IDs of ordinal attribute valuescan be extremely useful. Attribute value IDs are invisible to end users but knowledge ofhow they are applied can allow relational operator filters to be applied to certainattributes. For example, in the case of date values, attribute IDs are ordinal andchronological so for the Month/Year attribute, the ID value of May 2007 is higher thanthe ID value for April 2007. This allows you to refer to all months after May 2007 in thefollowing way: Month/Year > May 2007. More examples are provided below.

    Syntax

    SELECT WHERE <

    SELECT metric WHERE fact1 < fact2

    SELECT metric WHERE fact1 < number

    SELECT metric1 WHERE metric2 < number

    SELECT metric WHERE attribute < attribute_value

    Examples

    SELECT Number of Transactions WHERE Total_Amount > 10,000

    SELECT Number_of_Transactions WHERE AMOUNT > 6 AND AMOUNT 2007

    SELECT Profit WHERE Date = 2

    INDescription

    A filtering operator that includes two or more attribute values of interest, separated bycommas.

    Syntax

    SELECT WHERE IN (,)

    SELECT metric WHERE attribute IN (attribute_value1, attribute_value2)

  • Examples

    SELECT Profit WHERE Year IN (2006, 2007)

    NOT INDescription

    A filtering operator that excludes two or more attribute values of interest, separated bycommas.

    Syntax

    SELECT WHERE NOT IN (,)

    SELECT metric WHERE attribute NOT IN (attribute_value1,attribute_value2)

    Examples

    SELECT Profit WHERE Year NOT IN (2006, 2007)

    SELECT Sales WHERE Quarter NOT IN (THIS, PREVIOUS)

    BETWEENDescription

    A filtering operator that includes only those attribute values that fall within somespecified range. The range is specified by two inclusive attribute value endpoints.

    Syntax

    SELECT WHERE BETWEEN AND

    SELECT metric WHERE attribute BETWEEN attribute_value1 ANDattribute_value2

    Examples

    SELECT Profit WHERE Year BETWEEN 2005 AND 2008

    SELECT Sales WHERE Quarter BETWEEN THIS - 5 AND THIS)

    NOTE:In this last example, the time macro THIS serves as an attributevalue, though it can be typed directly into the Metric Editor rather thanselecting it from the Project Element Sidebar.

  • NOT BETWEENDescription

    A filtering operator that excludes attribute values that fall within some specified range.The range is specified by two inclusive attribute value endpoints.

    Syntax

    SELECT WHERE NOT BETWEEN AND

    SELECT metric WHERE attribute NOT BETWEEN attribute_value1 ANDattribute_value2

    Examples

    SELECT Profit WHERE Year NOT BETWEEN 2005 AND 2008

    SELECT Sales WHERE Quarter NOT BETWEEN THIS - 5 AND THIS)

    Referencing Floating Time Periods

    Time macros are floating references to day, month, week, and other date-relatedattribute values, relative to the present. The GoodData Platform supports the followingtime macros:

    l THIS

    l PREVIOUS

    l NEXT

    Because time macros are values that belong to a date attribute, they inherit thegranularity of the attribute with which they are associated. These macros are useful forcreating reports that relate to data from today or yesterday or to data from quarter-to-date or year-to-date floating periods.

    You can also use multiple time macros within the same metric definition.

    THIS MacroThe THIS macro is a reference to the current value for the selected date attribute.

    In the following example, the THIS macro inherits the day granularity from the Dateattribute. As a result, in this context, THIS means this date, or today:

  • SELECT Payment WHERE Date = THIS

    You could also modify this syntax to refer to the same day last week:

    SELECT Payment WHERE Date = THIS - 7

    NOTE:To reference yesterday or tomorrow, use the PREVIOUS andNEXT macros. See PREVIOUSand NEXT.

    If the attributes granularity changes, so does the granularity of the macro. In thefollowing example THIS means this month.

    SELECT Payment WHERE Month = THIS

    Below, THIS means this year in the first instance and this day of year in the second(e.g.March 2nd would be day 61 of the year).

    SELECT Payment WHERE Year = THIS AND Day of Year = THIS

    PREVIOUS MacroThe PREVIOUS macro is used to select the attribute value for the date dimension thatimmediately precedes the current value.

    In the following example, PREVIOUS means previous quarter.

    SELECT Payment WHERE Quarter = PREVIOUS

    In the next example, PREVIOUS means last quarter and THIS references this day, lastquarter (e.g. February 2nd and May 3rd are both day 33 of their respective quarters, sothey have the same Day of Quarter value).

    SELECT # of Employees WHERE Quarter = PREVIOUS AND Day of Quarter =THIS

  • NEXT MacroThe NEXT macro is used to select the attribute value for the date dimension thatimmediately follows the current value.

    In the following example, NEXT refers to the opportunity probability in the subsequentmonth.

    SELECT Opp_Probability WHERE Month= NEXT

    In the following example, the PREVIOUS and NEXT macros are used to specify aninclusive range of weeks between last week and next week:

    SELECT Payment WHERE Week BETWEEN PREVIOUS AND NEXT

    Below, the PREVIOUS and NEXT macros are used to specify the specific set of attributevalues to use. In this case, the set of payments to select may come from last year or thenext year--not the current year:

    SELECT Payment WHERE Year IN (PREVIOUS,NEXT)

    Logical Expressions for Combining Filters

    Logical expressions allow you to combine multiple filters within a single metric definition.

    NOTPreceding a filter with NOT excludes the specified attribute values when the metric iscomputed.

    SELECT Revenues WHERE NOT(Year = 2006 AND Month = 5)

    ORCombining filters using OR indicates that all metric values associated with the specifiedattribute values should be combined. In the following example, all metric valuesassociated with the attribute values 2006 and 2005 will be returned.

    SELECT Revenues WHERE Year = 2006 OR Year = 2005

  • OR can also be used to combine two different types of filters. Consider the case whereyou wish to return the total of all payments from the year 2006 and the first four months of2007:

    SELECT SUM(Payment) WHERE Year = 2006 OR Month IN (January 2007,February 2007, March 2007, April 2007)

    ANDCombining filters with AND applies all filters simultaneously when the metric iscomputed.

    SELECT Revenues WHERE Year = 2006 AND Month = 5

    While OR combines filters in a way that allows more data to pass through reportcomputations, AND restricts, or limits, the amount of data that is used in computations.Consider the case where our metric has a filter that serves to include all data from 2006as well as data from the first four months of 2007. Adding an additional AND clause ontothe metric definition limits the data that is used in the metrics computations becausenow there are more conditions than before that data must meet in order to be included incomputations.

    In the following example, payments must come from 2006 or the first four months of 2007to be included in metric computations. They must also be greater than $10,000.

    SELECT SUM(Payment) WHERE Year = 2006 OR Month IN (January 2007,February 2007, March 2007, April 2007) AND (Payment > 10000)

    Payment values that come from 2006 or the first four months of 2007 but are less than10,000 will be excluded.

    Adding Filtered Variables to Metric Definitions

    Filtered variables rely on attribute values to filter out data that only pertains to certainusers. This is useful for restricting users access to data for security reasons, but mayalso be helpful for streamlining large and complex projects so that users are not boggeddown by data that does not relate to them. Filtered variables are set up in the Managesection and allow project administrators to determine which values within a givenattribute should be available to particular users.

  • After a filtered variable has been established, you can apply it to a metrics definitionusing the WHERE filtering keyword. The variable will allow for dynamic (user-specific)metric computations in whatever report the metric is used.

    In the following example, the variable Var_Industry has been defined such that thenumber of leads calculated will relate only to those industries that are relevant to eachuser.

    SELECT #Leads WHERE Var_Industry

    Figure: Use theWHERE MAQL keyword to introduce filtered variables in MAQL syntax

    Filter with the HAVING ClauseDescription

    The HAVING filter enables you to apply filtration to a metric after all containing metricsand aggregation functions have been computed.

    In MAQL, the WHEREclause is used to perform basic filtration on your data before it hasbeen aggregated. In some cases, you may want to filter your metric data after it has beenaggregated, so that you can make conditional evaluations based on the results of thecomputations within the metric.

    HAVINGclause filtration is applied after all other conditions of the metric have beenresolved.

    Syntax

    SELECT... HAVING...

  • If your metric contains multiple keywords, they must be listed in alphabetical order:

    SELECT (...) (BY ...) (FOR ...) (...|HAVING ...) (WITHPF|WITHOUTPF)

    NOTE:The HAVINGkeyword cannot be applied in a metric containinga WHEREclause.

    Restrictions

    Suppose you have created a metric containing the following:

    SELECTSUM(Sales)BYQuarter,Product HAVINGRegion = West

    However, since there is no direct relationship between Quarter and Region orbetween Product and Region, the HAVINGclause conditions are ignored.

    l However, if the HAVINGclause included Quarter, Year, Product, or ProductCategory, then the filter would be applied.

    NOTE:A HAVING filter is only applied if the data model supports itsevaluation.

    Examples

    SELECT SUM(amount) BY Region, Year HAVING Year = 2014

    SELECT SUM(amount) BY Region, Quarter HAVING Year = 2014

    SELECT SUM(amount) BY Quarter FOR PREVIOUS(Quarter) HAVING Year =2014 WITHOUT PARENT FILTER

    The last MAQLstatement above returns values for amount for the quarter before thisone, displaying only results from 2014. No parent filters are applied.

  • Overriding Report FiltersIn your project, you can apply data filters at the metric, report, and dashboard levels.Specified based on attributes and attribute values, these filters change the computedvalues displayed in your reports.

    l Filters are applied to the data based on an order of precedence, in whichdashboard filters are given the highest priority, followed by report filters and thenfilters within metric definitions. For more information, see Filtering Data.

    In your metric definitions, you can specify overrides of the filters that have been specifiedin higher-level (parent)objects in your project.

    A parent filter is any data filter applied to a project object from one of its parent objects.A parent object can be considered any report that contains the metric or another metricbuilt on the metric.

    l For example, if your report filter is defined to be Channel = Twitter, then bydefault all metrics in the report are computed for data that matches Channel =Twitter. Similarly, if the dashboard filter is set to Date = June 2, 2014,then all metrics in the report calculated from data matching Date = June 2,2014 and Channel = Twitter. However, other reports on the dashboard areonly filtered by the date value.

    l If there is a dashboard filter and a report filter on two different attributes: datamust match both filter conditions in order to appear in the report. In the MAQLqueryfor the report, a logical AND is applied between the filters.

    l If the dashboard filter and report filter are on the same attribute: the dashboardfilter overrides the report filter.

    A metric's parent filters may be specified in any report or dashboard containing themetric or in any metric in which the original metric is nested.

    l These filters are applied to a metric's data before the computations has beenexecuted.

    In some cases, however, you may wish to override parent filters or to specify which ofthese filters to apply from within your metric definitions. These report filter overridescan be an important method for maintaining control over the data that is displayed for ametric.

  • For example, suppose your Total_Employees metric should display a single,consistent value wherever it is used in the project. However, your data model may makeit possible to filter this metric by attributes such as Region or Office_Location inmetrics, report filters, and dashboard filters. By adding the WITHOUT PARENT FILTERkeyword to the metric definition, you ensure that the Total_Employees metric returnsa consistent value no matter where and how it is used in the project.

    Applying report filter overrides to your metric definitions can bevery important to ensure consistency in usage. However, youshould avoid overusing these overrides, as they can make yourmetrics less flexible and create debugging issues.

    For more information:

    l See PARENTKeywords.

    l See HAVINGFilter.

    PARENT Keywords

    MAQLsupports a set of keywords that can be used to override and control which parent-level filters are applied to a specified metric. When inserted into your metric definition,these keywords specify whether to apply any filters from the metric's parent metric,report, or dashboard to the data used in the metric calculation.

    l You may include or exclude all filters or specify the specific filters to include orexclude.

    l These keywords are applied to selecting data before it has been aggregated in themetric computation. For more information on applying filtering to data after it hasbeen aggregated, see HAVINGFilter.

    The effects of these keywords are best demonstrated by example. Suppose you havethe following metric (M1), which has report-level filters applied to it:

    Definition Report Filter Metric ValueSELECTM1 (none) 500

    SELECTM1 F1:Group = X 350

    In the above table, you can see the value generated for the metric (M1) is 500 when nofiltration is applied. When the report filter (F1) is applied, the value for the metric is 350.This example can be used to describe the effects of each of the following parentkeywords.

    If your metric contains multiple keywords, they must be listed in alphabetical order:

  • SELECT (...) (BY ...) (FOR ...) (WHERE ...|HAVING ...)(WITHPF|WITHPFEXCEPT|WITHOUT PF|WITHOUTPFEXCEPT)

    Tip:For any metric that utilizes the WITHor WITHOUTkeywords tooverride report filters, you should include an indicator in the metricname. For example, you might append [WO/PF] to any metric's namethat uses the WITHOUT PF keywords.

    WITHOUTPARENT FILTERDescription

    Removes parent filters from being applied to the metric. All parent filters specified inreports, dashboards, and any metrics in which this metric is nested are ignored.

    l Any user filters in the project are never ignored. They are always applied even ifparent filters are ignored in individual metrics. See Filtering Data.

    l This clause may be shortened to WITHOUTPF.

    Example

    In the table below, you can see how the WITHOUTPARENT FILTERclause affects thefiltered version of the report.

    Definition Report Filter Metric ValueSELECTM1 (none) 500

    SELECTM1 F1:Group = X 350

    SELECTM1WITHOUTPARENTFILTER

    F1:Group = X 500

    Since the metric in the third row removes the parent filter in the report, the returned valuematches the calculation when no report filter is applied in the first row.

    Syntax

    SELECT ... WITHOUT PARENT FILTER

    SELECT ... WITHOUT PF

  • WITHOUTPARENT FILTEREXCEPTDescription

    Remove parent filters, except for any filters specified as a comma-separated list ofattributes.

    l This clause may be shortened to WITHOUTPFEXCEPT.

    NOTE: In EXCEPT clauses, multiple attributes may be specified as aseries of comma-separated values.

    NOTE: Excepted attribute filters are applied to the specified attributeand to all attributes of coarser granularity in the hierarchy. For example,in the hierarchy State-County-City, the values of the attributeCity do not group the values of County, but County groups Citybecause County has coarser granularity than City. So, if City isexcepted, County and State are excepted too. If you apply theexception to the State attribute, it is the only attribute filter that isexcepted.

    Example 1

    In the table below, you can see how the WITHOUT PARENT FILTER EXCEPTkeyword works with the State-County-City hierarchy.

    Definition Report Filter Metric ValueSELECTM1 (none) 1000

    SELECTM1 F1:County = X 600

    SELECTM1WITHOUTPF

    F1:County = X 1000

    SELECTM1 WITHOUTPFEXCEPTCity

    F1:County = X 600

  • SELECTM1 WITHOUTPFEXCEPTState

    F1:County = X 1000

    SELECTM1 WITHOUTPFEXCEPTState

    F1:State = Y 550

    l In the above example in the third row, the WITHOUT PARENT FILTER removesall parent filters from the metric, so COUNTY = X is not applied. The returnedresults match the unfiltered version of the metric in the first row.

    l In the fourth row, City is excepted. Since County has coarser grain than City,the parent report filter (County = X) is applied.

    l In the fifth row, the excepted filter is State. However, the report filter is at theCounty attribute level, which is finer than State. Therefore, the filter is notapplied, and the results match the unfiltered version in the first row.

    l In the fifth row, the excepted filter is State, which matches the report filter. So, theresults are filtered.

    Example 2

    In the table below, you can see how the WITHOUTPARENTFILTEREXCEPTkeyword affects the filtered version of the report.

    Definition Report Filter Metric ValueSELECTM1 (none) 500

    SELECTM1 F1:Group = X 350

    SELECTM1 F1:Group = X;F2:Priority is Y

    250

    SELECTM1WITHOUTPARENTFILTEREXCEPTGroup

    F1:Group = X;F2:Priority is Y

    350

    In the above example in the fourth row, theWITHOUTPARENTFILTEREXCEPTremoves all parent filters from the metric, exceptfor one:Group, so the Priority filter is not applied to the metric. The generated metricvalue equates to the value generated in the version in the second row.

  • Syntax

    SELECT ... WITHOUT PARENT FILTER EXCEPT Attribute1,...

    SELECT ... WITHOUT PF EXCEPT Attribute1,...

    WITHPARENT FILTERDescription

    Applies all parent filters to the metric. All parent filters specified in reports, dashboards,and any metrics in which this metric is nested are applied to the calculation.

    l This clause may be shortened to WITHPF.

    NOTE:The WITHPARENTkeyword is applied by default when otherreport filters are not present.

    Example

    In the table below, you can see how the WITHPARENT FILTERclause affects thefiltered version of the report.

    Definition Report Filter Metric ValueSELECTM1 (none) 500

    SELECTM1 F1:Group = X 350

    SELECT(SELECTM1WITHPARENTFILTER)WHEREGroup = Y

    F1:Group = X null

    In the third row above, the definition includes a nested metric in which parent filters areforced to be included from inside the nested metric.

    l In the parent metric is the filter Group = Y.

    l At the report level, the filter is Group = X.

    l The WITH PARENT FILTER keyword means that all parent filters are applied tothe metric. During evaluation, both Group = X and Group = Y are applied tothe data as a logical AND. Since a data element may be associated with a single

  • attribute value, there are no data elements that match both filters, and the result setis null.

    Syntax

    SELECT ... WITH PARENT FILTER

    SELECT ... WITH PF

    WITHPARENT FILTEREXCEPTDescription

    Includes all parent filters, except for any filters specified as a comma-separated list ofattributes.

    l This clause may be shortened to WITHPFEXCEPT.

    NOTE: In EXCEPT clauses, multiple attributes may be specified as aseries of comma-separated values.

    NOTE: Excepted attribute filters are applied to the specified attributeand to all attributes of coarser granularity in the hierarchy. For example,in the hierarchy State-County-City, the values of the attributeCity do not group the values of County, but County groups Citybecause County has coarser granularity than City. So, if City isexcepted, County and State are excepted too. If you apply theexception to the State attribute, it is the only attribute filter that isexcepted.

    Example

    In the table below, you can see how the WITHPARENT FILTEREXCEPTkeywordaffects the filtered version of the report.

    Definition Report Filter Metric ValueSELECTM1 (none) 500

    SELECTM1 F1:Group = X 350

  • SELECTM1 F1:Group = X;F2:Priority is Y

    250

    SELECTM1WITHPARENTFILTEREXCEPTPriority

    F1:Group = X;F2:Priority is Y

    350

    In the above example in the fourth row, the WITHPARENTFILTEREXCEPTincludesall parent filters in the metric, except for one:Priority, so in this case, the Priorityfilter is not applied to the metric. The generated metric value equates to the valuegenerated in the version in the second row.

    Syntax

    SELECT ... WITH PARENT FILTER EXCEPT Attribute1,...

    SELECT ... WITH PF EXCEPT Attribute1,...

  • Conditional StatementsConditional statements using the IF THEN ELSE or CASE WHEN THEN formulationscan return different values or metric expressions depending on whether certainconditions are met. IFNULL allows you to substitute a predefined replacement value in areport, if a null value is returned.

    IF THEN ELSEDescription

    IF THEN ELSE statements return one of two possible values, or perform one of twopossible computations, depending on whether some condition is met.

    The defined condition follows the keyword IF and can be constructed using any of thefiltering keywords or relational operators (IN, NOT IN, BETWEEN, NOT BETWEEN, =, < ,, >=, ).

    The first possible outcome follows the keyword THEN, and the second possible outcomefollows the keyword ELSE. The outcomes that are returned can be numerical values orarithmetic operations. All IF THEN ELSE statements conclude with the END keyword.

    NOTE:If there more than two possible conditions to be defined, usethe CASE statement described below.

    Syntax

    SELECT IF THEN ELSE END

    l SELECT IF condition THEN number ELSE number END

    l SELECT IF condition THEN arithmetic_operation ELSEarithmetic_operation END

    Examples

    l SELECT IF SUM(Amount)>= AVG(Amount) THEN 10 ELSE 0 END

    l SELECT IF SUM(Duration) - AVG(Duration) > 2000 THEN 0ELSE 1 END

    l SELECT IF AVG(Probability) > 0.5 THEN SUM(Amount) * 10ELSE SUM(Amount) / 10 END

  • CASEDescription

    CASE is used for complex conditional expressions that contain three or more conditions.Following the CASE keyword, conditions and outcomes follow the keywords WHEN andTHEN, respectively. If none of the WHEN conditions are met, the outcome following ELSEis returned. Outcomes can be numerical values or arithmetic operations. All CASEexpressions conclude with the END keyword.

    Syntax

    SELECT CASE WHEN THEN , WHEN THEN ELSE END

    SELECT CASE WHEN condition1 THEN outcome1, WHEN condition2THEN outcome2 ELSE outcome3 END

    Examples

    SELECT CASE WHENactivity_typeIN(email,meeting) THEN 1, WHENactivity_typeIN(phone_call,meeting) THEN 2 ELSE 0 END

    SELECT CASE WHEN SUM(Amount) > SUM(Lost) AND SUM(Amount) SUM(Lost) > 100000 THEN 2, WHEN SUM(Amount) > SUM(Lost) AND SUM(Amount) SUM(Lost) < 100000 THEN 1 ELSE 0 END

    IFNULLDescription

    IFNULL allows you to predefine how the GoodData Platform addresses any missingvalues that are returned by a metric expression (metric, fact aggregation, or arithmeticoperation). If a metric expression that is wrapped within an IFNULL statement everreturns a null value, the replacement number specified in the second parameter of theIFNULL function will be inserted in place of the null value.

    IFNULL is especially useful in cases where a sub metric is referred to within anothermetrics definition. Wrapping the sub metric in an IFNULL statement keeps theencompassing metric from becoming null due to one of its components returning a nullvalue.

    NOTE:Supported replacement values include constants, but not othermetric expressions.

  • Syntax

    SELECT IFNULL(,)

    SELECT IFNULL(metric, replacement_value)

    Examples

    SELECT IFNULL(SUM(Amount), 0)

    SELECT IFNULL(SUM(FB_Cost + TW_Cost), 0)

    SELECT IFNULL(SUM(Amount) + 100, 1)

  • Time TransformationsMAQL time transformation functions allow you to refer to past or future time periods.Depending on the function, time transformations may relate to a certain pre-specifiedgranularity of time, or may adapt to the context (attribute granularity) of a given report.

    Functions For Referring to Past Time PeriodsTwo functions in MAQL allow you to create metrics showing a time over time comparison(e.g., month over month, or quarter over quarter) of past time periods:

    l FOR Previous()

    l FOR PreviousPeriod()

    FOR Previous

    Description

    A function that allows you to compute a metric for a previous, fixed time period.

    Syntax

    SELECT FOR Previous(,)

    SELECT metric FOR Previous(time_attribute)

    SELECT metric FOR Previous(time_attribute, #periods_ago)

    Examples

    SELECT Revenues FOR Previous(Quarter)

    NOTE: By default, FOR Previous()refers to values from one timeperiod ago. This can be customized by adding a second parameter tothe function. For example, you might want to return a revenue valuefrom three quarters ago (see below).

    SELECT Revenues FOR Previous(Quarter , 3)

    Note how the Previous Qtr column in the table below displays a metric that is linked tothe metric values in the Amount column with the FOR Previous() function.

  • Figure: Column 3 and column 2metric values are linked with the For Previous(quarter) function.

    Figure: Payment FORPrevious(Quarter,2) refers to the payment from two quarters ago.

    Even in cases where metric values are broken across a date attribute of smaller timegranularity, the GoodData Platform intelligently calculates FOR Previous(quarter) metricvalues. In the case illustrated below, each month in a quarter is linked to thecorresponding month in the previous quarter.

    Figure:Metric values in column 4 are related to column 3 values using the For Previous(quarter)function. Note how the GoodData Platform intelligently interprets FORPrevious(quarter) byassociating each month within a quarter to the corresponding month in the previous quarter.

  • FOR PreviousPeriod

    Description

    A function that allows you to compute a metric for a previous time period the granularityof which is determined contextually by the most granular date attribute that is defined inthe report at hand.

    Syntax

    SELECT FOR PreviousPeriod(,)

    SELECT metric FOR PreviousPeriod(time_attribute)

    Examples

    SELECT Payment FOR PreviousPeriod(Quarter)

    SELECT Payment FOR PreviousPeriod(Quarter, 2)

    FOR Previous vs. FOR PreviousPeriod

    The difference between the Previous() and PreviousPeriod() functionsbecomes clear when the date attribute in a report is smaller that the time period specifiedwithin the functions parentheses.

    FOR Previous() strictly follows the date attribute specified by the metric authorwithin the parentheses of the function.

    On the other hand, FOR PreviousPeriod() adapts to the context of the report athand. Regardless of the date attribute specified by the metric author, thePreviousPeriod() function takes on the date attribute of the smallest granularityfrom the report.

    In the example below, even though the metric in the final column has been defined asFOR PreviousPeriod(quarter), the function returns values from the previousmonth, as month is the most granular date attribute in this report.

  • Figure: The Previous() function strictly follows the date attribute specified within the functionsparentheses. PreviousPeriod () takes on the most granular date attribute that is containedwithin the report.

    NOTE: Even if PreviousPeriod() automatically takes on thegranularity of the smallest date attribute in a report, it is still important tospecify a date attribute within the PreviousPeriod() function as away of specifying the date dimension of interest. This is becauseprojects often have multiple date dimensions, such as Date(LeadCreated), Date(MQL Qualified), or Date(Snapshot).

    Functions For Referring to Future Time PeriodsYou can also create a metric that incorporates metric values from a future time period.Doing so requires one of two functions that are analogous to Previous() andPreviousPeriod() but relate to the future:

    l FOR Next()

    l FOR NextPeriod()

    FOR Next

    Description

    A function that allows you to compute a metric for a future, fixed time period.

    Syntax

    SELECT FOR Next(,)

  • SELECT metricFOR Next(time_attribute)

    Examples

    SELECT Revenue FOR Next(Quarter)

    NOTE:By default, FOR Next()refers to values from one time periodin the future. This can be customized by adding a second parameter tothe function. For example, you might want to return a payment valuefrom three quarters in the future with respect to a certain time period(see below.)

    SELECT Payment FOR Next(Quarter,3)

    FOR NextPeriod

    Description

    A function that allows you to compute a metric for a future time period the granularity ofwhich is determined contextually by the most granular date attribute that is defined in thereport at hand.

    Syntax

    SELECT FOR NextPeriod(,)

    SELECT metric FOR NextPeriod(time_attribute)

    Examples

    SELECT Revenue FOR NextPeriod(Quarter)

    SELECT Payment FOR NextPeriod(Quarter, 3)

    Notes

    As was the case for the functions Previous() and PreviousPeriod(), thedifferences between Next() and NextPeriod() become most relevant when areport contains a more granular date attribute than is specified within the functionsthemselves. The chart below demonstrates the differences between Leads FOR Next(Quarter) and Leads FOR NextPeriod(Quarter) in a report broken across amore granular Date attribute.

  • Figure: The Next() function strictly follows the date attribute specified within the functionsparentheses. NextPeriod () takes on the most granular date attribute that is contained withinthe report.

    FORECAST - Add a Trend Line to a Report

    Use the FORECAST function to add a trend line to a report. The trend line uses linearregression to predict up to ten future periods based on existing data. For example, youcould use a trend line to predict future sales based on historical data. Forecast reportsmust have one date/time attribute on the Xaxis, and no other attributes. When you createa report with FORECAST, select only one date/time attribute for HOW.

    Syntax

    FORECAST(... [, number of periods])

    l [, number of periods]

    Optionally specify a number of periods to forecast in the future.Format: number

  • Default: 3Maximum: 10

    All report filters are applied to the metric that you FORECAST except for date and timefilters. To apply a date or time filter to the report, add it directly to the metric. For example:

    SELECT FORECAST((SELECT COUNT(Activity) WHERE Year = 2012), 6)

    TIPs:If the metric being FORECASTcontains a BY clause, the trend linemay render in steps. To create a smooth regression line, remove theBY clause.

    If your FORECAST report does not have a trend line, ensure youselected a date or time attribute for HOW.

    Examples

    You create a report to forecastAverage Deal Size with a HOWof Month (DealClosed). Use the following metric to compute the next three months based on allhistorical data:

    SELECT FORECAST(Average Deal Size)

    This metric predicts Average Deal Size for the next six months:

    SELECT FORECAST(Average Deal Size, 6)

    This metric predicts Average Deal Size for the next two months using data from theprevious year:

    SELECT FORECAST(Select COUNT(Average Deal Size) WHEREyear =PREVIOUS), 2)

    This metric predicts Average Deal Size for the next two months using data from theprevious and current years:

  • SELECT FORECAST(Select COUNT(Average Deal Size) WHEREyear =PREVIOUS OR year = THIS), 2)

    This metric predicts Average Deal Si