Functions & Formulas

Overview 

Formulas let a semantic query compute values that are not stored directly in the model. You write a formula as an expression string — combining field references, operators, literals, and functions — and the Semantic Query API evaluates it as part of the query. Formulas power calculated dimensions and calculated measurements: a calculated dimension groups or filters rows by a computed value, while a calculated measurement aggregates a computed value.

There are two ways to bring a formula into a query:

  • Model-defined calculated fields. The formula is authored once in the Semantic Data Model as a SemanticCalculatedDimension or SemanticCalculatedMeasurement, and the query references it by name through a semantic_field expression.
  • On-the-fly calculated fields. The formula is supplied directly in the request as a calculated_field expression, without being persisted to the model. Use this for query-scoped computations.

Formula expressions use the Tua dialect, which references fields with bracket notation [Table].[Field] and supports level-of-detail (LOD) expressions and table calculations. A calculated field declares its dialect with the syntax property ("Tua"); when a request carries an inline semanticModel, Tua is the default. The Function reference below documents the full Tua function library.

Metadata in the model 

Calculated fields can be defined at authoring time as part of the Semantic Data Model, so their formulas are reusable across queries. A calculated dimension is authored as a SemanticCalculatedDimension; a calculated measurement is authored as a SemanticCalculatedMeasurement. Each carries an apiName, a dataType, an expression, a syntax, and (for measurements) an aggregationType and a level. For the full authoring field schema, see Semantic Calculated Dimension and Semantic Calculated Measurement in the Authoring API.

A model-defined calculated measurement:

1{
2  "apiName": "AverageSumOfSales_clc",
3  "label": "AverageSumOfSales",
4  "dataType": "Number",
5  "aggregationType": "UserAgg",
6  "decimalPlace": 2,
7  "expression": "WINDOW_AVG(SUM([Sales]), -3, 1)",
8  "level": "TableCalc"
9  // ...
10}

A query references a model-defined calculated field by name with a semanticField expression. The referenced formula is resolved from the model:

1{
2  "fields": [
3    {
4      "expression": {
5        "semanticField": {
6          "name": "AverageSumOfSales_clc"
7        }
8      },
9      "alias": "AverageSumOfSales_clc",
10      "rowGrouping": false,
11      "semanticAggregationMethod": "SEMANTIC_AGGREGATION_METHOD_USER_AGG"
12    }
13  ]
14}

Query usage 

Defining an on-the-fly calculated field 

To compute a value without persisting it to the model, place a calculated_field object inside a fields[] entry’s expression. A calculated_field has a name, an expression string, an optional syntax, and exactly one of calculated_measure_expression (for an aggregated numeric result) or calculated_dimension_expression (for a grouping value).

A calculated measurement declares its output type under calculated_measure_expression:

1{
2  "fields": [
3    {
4      "expression": {
5        "calculated_field": {
6          "name": "simple_power_calc",
7          "expression": "POWER(2,2)",
8          "calculated_measure_expression": {
9            "measure_output_type": "SEMANTIC_MEASUREMENT_TYPE_NUMBER"
10          }
11        }
12      },
13      "semantic_aggregation_method": "SEMANTIC_AGGREGATION_METHOD_SUM",
14      "alias": "simple_power_calc"
15    }
16  ]
17}

A calculated dimension declares its output type under calculated_dimension_expression, using dimension_output_type:

1{
2  "calculated_field": {
3    "name": "simple-calc",
4    "expression": "DATETIMEVALUE(DATE_TRUNC('day', ssot__Account__dlm.ssot__LastModifiedDate__c))",
5    "calculated_dimension_expression": {
6      "dimension_output_type": "SEMANTIC_DIMENSION_TYPE_DATE_TIME"
7    }
8  }
9}

To group query rows by a computed dimension, set row_grouping to true on the field:

1{
2  "expression": {
3    "calculated_field": {
4      "name": "fiscal_quarter_on_the_fly_calculation",
5      "expression": "CONCAT('FY', TEXT(FISCAL_QUARTER(AccountSemanticLayer__dll.LastModifiedDate__c)), '-Q', TEXT(FISCAL_YEAR(AccountSemanticLayer__dll.LastModifiedDate__c)))"
6    }
7  },
8  "row_grouping": true
9}

A measurement calculated field may also specify decimal places under decimal_places_options:

1{
2  "calculated_field": {
3    "name": "table_calc_running_sum",
4    "expression": "{ PARTITION [AccountSemanticLayer__dll].[Name__c]: { ORDERBY [AccountSemanticLayer__dll].[KQ_Id__c] : RANK(SUM([AccountSemanticLayer__dll].[AnnualRevenue__c])) } }",
5    "calculated_measure_expression": {
6      "measure_output_type": "SEMANTIC_MEASUREMENT_TYPE_NUMBER",
7      "decimal_places_options": {
8        "decimal_places": 2
9      }
10    },
11    "syntax": "Tua"
12  }
13}

Operators and precedence 

Expressions combine values with arithmetic, comparison, and logical operators. Operators evaluate in the following order, from highest to lowest precedence:

  1. Parentheses ( )
  2. Unary minus -
  3. Exponentiation ^
  4. Multiplication, division, modulo * / %
  5. Addition, subtraction + -
  6. Comparisons > < >= <= = !=
  7. IN
  8. NOT
  9. AND
  10. OR

Use parentheses to make grouping explicit. Arithmetic combines aggregates, fields, parameters, and literals — this on-the-fly measurement adds a parameter value to a summed field:

1{
2  "calculated_field": {
3    "name": "summary-calc-in-select",
4    "expression": "SUM([SemanticAccount__dlm].[sdm__AccountTypeId__c]) + [Parameters].[test12]",
5    "calculated_measure_expression": {
6      "measure_output_type": "SEMANTIC_MEASUREMENT_TYPE_NUMBER",
7      "decimal_places_options": {
8        "decimal_places": 2
9      }
10    }
11  }
12}

Arithmetic can also combine field references directly:

1{
2  "calculated_field": {
3    "name": "nested_semantic_field_calc",
4    "expression": "[logical_table].[AnnualRevenue] + [SemanticContact_SDO].[MailingLatitude]",
5    "syntax": "Tua",
6    "calculated_measure_expression": {
7      "measure_output_type": "SEMANTIC_MEASUREMENT_TYPE_NUMBER"
8    }
9  }
10}

Math and numeric functions 

Numeric functions operate on numbers and numeric expressions. POWER(base, exponent) raises a number to a power:

1{
2  "calculated_field": {
3    "name": "simple_power_calc",
4    "expression": "POWER(2,2)",
5    "calculated_measure_expression": {
6      "measure_output_type": "SEMANTIC_MEASUREMENT_TYPE_NUMBER"
7    }
8  }
9}

ROUND(value, places) rounds to a given number of decimal places, and ABS(value) returns absolute value. This model-defined table calculation uses ABS in a period-over-period growth formula:

1{
2  "apiName": "Calculation18",
3  "dataType": "Number",
4  "aggregationType": "UserAgg",
5  "expression": "(ZN(SUM([Superstore_Orders].[Sales])) - LOOKUP(ZN(SUM([Superstore_Orders].[Sales])), -1)) / ABS(LOOKUP(ZN(SUM([Superstore_Orders].[Sales])), -1))",
6  "level": "TableCalc"
7}

String functions 

String functions build and transform text. CONCAT(...) joins strings, and TEXT(value) converts a value to text — combined here to format a fiscal-period label:

1{
2  "calculated_field": {
3    "name": "fiscal_quarter_on_the_fly_calculation",
4    "expression": "CONCAT('FY', TEXT(FISCAL_QUARTER(AccountSemanticLayer__dll.LastModifiedDate__c)), '-Q', TEXT(FISCAL_YEAR(AccountSemanticLayer__dll.LastModifiedDate__c)))"
5  }
6}

LEFT(text, count) returns the leftmost characters. STR(value) converts a value to a string, and text values concatenate with +. This model-defined calculated dimension formats a rounded score with a text suffix:

1{
2  "apiName": "Avg_Quality_Score_clc",
3  "dataType": "Text",
4  "expression": "IF [Quality_Score_Color_clc] = \"High\"\nTHEN STR(ROUND([Average_Quality_Score_clc],2)) + \" (High)\"\nELSEIF [Quality_Score_Color_clc] = \"Medium\"\nTHEN STR(ROUND([Average_Quality_Score_clc],2)) + \" (Medium)\"\nELSEIF [Quality_Score_Color_clc] = \"Low\"\nTHEN STR(ROUND([Average_Quality_Score_clc],2)) + \" (Low)\"\nELSE STR(ROUND([Average_Quality_Score_clc],2)) + \" (Very Low)\"\nEND"
5}

Date and datetime functions 

Date functions extract, truncate, and construct date and datetime values. DATE_TRUNC(part, datetime) truncates a datetime to a given part, and DATETIMEVALUE(...) produces a datetime value:

1{
2  "calculated_field": {
3    "name": "simple-calc",
4    "expression": "DATETIMEVALUE(DATE_TRUNC('day', ssot__Account__dlm.ssot__LastModifiedDate__c))",
5    "calculated_dimension_expression": {
6      "dimension_output_type": "SEMANTIC_DIMENSION_TYPE_DATE_TIME"
7    }
8  }
9}

DATEPART(part, date) returns a numeric component of a date, such as the year. This calculated dimension extracts the year from another calculated field:

1{
2  "calculated_field": {
3    "name": "datepartyear:F1",
4    "expression": "DATEPART('year', [ship_datetime_clc])",
5    "calculated_dimension_expression": {
6      "dimension_output_type": "SEMANTIC_DIMENSION_TYPE_NUMBER"
7    },
8    "syntax": "Tua"
9  }
10}

Fiscal date functions 

Fiscal date functions return fiscal-calendar components. FISCAL_YEAR(date) returns the fiscal year and FISCAL_QUARTER(date) returns the fiscal quarter for a date:

1{
2  "calculated_field": {
3    "name": "fiscal_quarter_on_the_fly_calculation",
4    "expression": "CONCAT('FY', TEXT(FISCAL_QUARTER(AccountSemanticLayer__dll.LastModifiedDate__c)), '-Q', TEXT(FISCAL_YEAR(AccountSemanticLayer__dll.LastModifiedDate__c)))"
5  }
6}

Conditional and null-handling functions 

Conditional expressions branch on a condition. The IF ... THEN ... ELSEIF ... ELSE ... END form returns different values per branch; IN tests membership in a value list. This model-defined measurement returns an amount only for matching forecast categories:

1{
2  "apiName": "Open_Pipeline_clc",
3  "dataType": "Number",
4  "aggregationType": "Sum",
5  "expression": "IF [Opportunity26].[Opportunity_Forecast_Category110] IN (\"Pipeline\", \"Best Case\", \"Most Likely\", \"Commit\") \n    THEN [Opportunity26].[Total_Amount19]\nEND",
6  "level": "Row"
7}

IFNULL(value, replacement) substitutes a replacement when a value is null. This measurement sums two counts, treating null counts as zero:

1{
2  "apiName": "Test_clc",
3  "dataType": "Number",
4  "aggregationType": "UserAgg",
5  "expression": "IFNULL(COUNT([Opportunity26].[Opportunity_Id23]),0)+IFNULL(COUNT([Product2].[Product_Id75]),0)",
6  "level": "AggregateFunction"
7}

ISNULL(expression) returns whether a value is null, and ZN(expression) converts a null numeric result to zero. The growth formula above uses ZN so that missing sales values participate in arithmetic as zero:

1{
2  "apiName": "Calculation18",
3  "expression": "(ZN(SUM([Superstore_Orders].[Sales])) - LOOKUP(ZN(SUM([Superstore_Orders].[Sales])), -1)) / ABS(LOOKUP(ZN(SUM([Superstore_Orders].[Sales])), -1))",
4  "aggregationType": "UserAgg",
5  "level": "TableCalc"
6  // ...
7}

Aggregation functions 

Aggregation functions collapse many rows into a single measurement value. Common ones include SUM, MIN, MAX, AVG, COUNT, COUNTD (distinct count), and MEDIAN — this is a representative sample, not the full list. For every supported aggregation function (including PERCENTILE, CORR, COVAR, COVARP, STDEV, STDEVP, VAR, and VARP), see Aggregation in the Function reference below. COUNTD counts distinct values of a field:

1{
2  "calculated_field": {
3    "name": "countd",
4    "expression": "COUNTD([SemanticAccount__dlm].[semantic__AccountSource__c])",
5    "calculated_measure_expression": {
6      "measure_output_type": "SEMANTIC_MEASUREMENT_TYPE_NUMBER"
7    }
8  }
9}

When a calculated field wraps an aggregation, set the field’s aggregation method to SEMANTIC_AGGREGATION_METHOD_USER_AGG so the expression’s own aggregation is used rather than an outer one. Aggregate expressions also appear in Top-N criteria — here MEDIAN ranks dimension values:

1{
2  "operator": "AdvancedDimension",
3  "top_bottom_criteria": {
4    "top_bottom_limit": 10,
5    "expression": "MEDIAN([superstore_fixed_nulls].[Quantity150])"
6  }
7}

Window and table-calculation functions 

Table calculations compute across the ordered result set — running totals, moving averages, rankings, and offset lookups. A calculated measurement authored at level TableCalc carries a window function. WINDOW_AVG(expression, start, end) averages a measure over a sliding window of rows:

1{
2  "apiName": "AverageSumOfSales_clc",
3  "dataType": "Number",
4  "aggregationType": "UserAgg",
5  "expression": "WINDOW_AVG(SUM([Sales]), -3, 1)",
6  "level": "TableCalc"
7  // ...
8}

LOOKUP(expression, offset) returns a measure’s value from a row offset by a given number of positions — negative offsets look backward. The period-over-period formula uses LOOKUP(..., -1) to reference the prior row:

1{
2  "apiName": "Calculation18",
3  "expression": "(ZN(SUM([Superstore_Orders].[Sales])) - LOOKUP(ZN(SUM([Superstore_Orders].[Sales])), -1)) / ABS(LOOKUP(ZN(SUM([Superstore_Orders].[Sales])), -1))",
4  "aggregationType": "UserAgg",
5  "level": "TableCalc"
6  // ...
7}

Table calculations use a PARTITION/ORDERBY window frame. The frame partitions rows by one set of columns, orders within each partition, and applies an analytics function. RANK(measure) assigns a rank within the ordered partition:

1{
2  "calculated_field": {
3    "name": "table_calc_running_sum",
4    "expression": "{ PARTITION [AccountSemanticLayer__dll].[Name__c]: { ORDERBY [AccountSemanticLayer__dll].[KQ_Id__c] : RANK(SUM([AccountSemanticLayer__dll].[AnnualRevenue__c])) } }",
5    "calculated_measure_expression": {
6      "measure_output_type": "SEMANTIC_MEASUREMENT_TYPE_NUMBER",
7      "decimal_places_options": { "decimal_places": 2 }
8    },
9    "syntax": "Tua"
10  }
11}

The ORDERBY clause accepts sort direction (ASC / DESC) and null placement (NULLS FIRST / NULLS LAST). Table-calculation expressions can also be used inside filters — this filter selects rows by an ordered index computed with an ORDERBY frame:

1{
2  "unified_filter": {
3    "filter_logic": "1",
4    "filters": [
5      {
6        "fields": [
7          {
8            "expression": "{ORDERBY [Superstore_Orders].[Region] ASC NULLS FIRST : ([Row_Index_1_clc])}"
9          }
10        ],
11        "operator": "Between",
12        "values": [1, 2],
13        "include_nulls": false
14      }
15    ]
16  }
17}

Identity functions 

Identity functions return values about the current user. USERID() returns the running user’s ID; combine it with LEFT to compare on a 15-character ID prefix. This model-defined calculated dimension marks rows owned by the current user:

1{
2  "apiName": "FFact_owner_opp_history_lv_clc",
3  "label": "FFact owner - opp history lv",
4  "dataType": "Boolean",
5  "expression": "LEFT([SW_FF_OPP_HIS_PA_lv].[Forecasting_Fact10_Owner], 15) = LEFT(USERID(), 15)"
6}

Referencing parameters in formulas 

A formula can reference a model parameter with bracket notation, as [Parameters].[<name>]. This on-the-fly measurement adds a parameter value to a summed field:

1{
2  "calculated_field": {
3    "name": "summary-calc-in-select",
4    "expression": "SUM([SemanticAccount__dlm].[sdm__AccountTypeId__c]) + [Parameters].[test12]",
5    "calculated_measure_expression": {
6      "measure_output_type": "SEMANTIC_MEASUREMENT_TYPE_NUMBER",
7      "decimal_places_options": {
8        "decimal_places": 2
9      }
10    }
11  }
12}

Comments in expressions 

You can annotate expressions with comments. Line comments (//) and block comments (/* */) are ignored during evaluation.

Function reference 

These are the built-in functions available in Tua formula expressions, as exposed in the Semantic Data Model authoring UI. Operators and precedence are covered in the Operators and precedence section above.

Functions differ in how they evaluate, which determines whether the calculated field is a dimension or a measurement:

  • Row-level (scalar) — evaluates independently for each row and returns one value per row. Math, String, Date/Fiscal, Conditional & Null, and AI & Predictive functions are row-level, and typically define a calculated dimension.
  • Aggregate — collapses the rows in a group into a single measurement value. When a calculated field wraps an aggregate expression, set its aggregation method to SEMANTIC_AGGREGATION_METHOD_USER_AGG so the expression’s own aggregation is honored (see Limitations).
  • Window (table calculation) — returns one value per row, computed over an ordered partition of neighboring rows. These require a PARTITION/ORDERBY frame.
  • Level of detail — computes an aggregation at a dimensionality you specify, independent of the query’s grouping.

Each category below notes which evaluation applies.

Math 

Evaluation: Row-level. The exceptions are MAX and MIN: with two arguments they are row-level (the larger/smaller of the two values per row); applied to a single field they act as an aggregate over the group.

FunctionReturn typeDescription
MAX(expr1, expr2)DynamicReturns the maximum of the two arguments, which must be of the same data type. MAX can also be applied to a single field as an aggregation — see Aggregation.
MIN(expr1, expr2)DynamicReturns the minimum of the two arguments, which must be of the same data type. MIN can also be applied to a single field as an aggregation — see Aggregation.
ROUND(number, [decimals])NumberRounds to a specified number of digits. The optional decimals argument specifies how many decimal points of precision to include in the final result. If decimals is omitted, number is rounded to the nearest integer.
RANDOM()NumberReturns a random decimal number in the following range 0.0 <= x < 1.0.
INT(expression)NumberCasts its argument as an integer.
CEILING(number)NumberRounds a to the nearest integer of equal or greater value.
FLOOR(number)NumberRounds a number to the nearest of equal or lesser value.
POWER(number, power)NumberRaises the to the specified .
SIN(number)NumberReturns the sine of an angle.
COS(number)NumberReturns the cosine of an angle.
TAN(number)NumberReturns the tangent of an angle.
COT(number)NumberReturns the cotangent of an angle.
ACOS(number)NumberReturns the arccosine (angle) of the given .
ASIN(number)NumberReturns the arcsine (angle) of a given .
ATAN(number)NumberReturns the arctangent (angle) of a given .
ATAN2(y number, x number)NumberReturns the arctangent (angle) between two numbers (x and y). The result is in radians.
PI()NumberReturns the numeric constant pi: 3.14159…
LN(number)NumberReturns the natural logarithm of a .
RADIANS(number)NumberConverts the given from degrees to radians.
DEGREES(number)NumberConverts an angle in radians to degrees.
ABS(number)NumberReturns the absolute value of the given .
DIV(integer1, integer2)NumberReturns the integer part of a division operation, in which is divided by .
SIGN(number)NumberReturns the sign of a : The possible return values are -1 if the number is negative, 0 if the number is zero, or 1 if the number is positive.
SQUARE(number)NumberReturns the square of a .
EXP(number)NumberReturns e raised to the power of the given .
LOG(number, [base])NumberReturns the logarithm of a for the given . If the optional base argument isn’t present, base 10 is used.
FLOAT(expression)NumberCasts its argument as a floating point number.

String 

Evaluation: Row-level.

FunctionReturn typeDescription
CONTAINS(string, substring)BooleanCompares two arguments of text and returns TRUE if the first argument contains the second argument. If not, returns FALSE.
LEN(string)NumberReturns the length of the string.
LOWER(string)TextReturns the provided in all lowercase characters.
REPLACE(string, substring, replacement)TextSearches for and replaces it with . If is not found, the string is not changed.
UPPER(string)TextReturns the provided in all uppercase characters.
SPLIT(string, delimiter, token number)TextReturns a substring from a string, using a delimiter character to divide the string into a sequence of tokens.
TRIM(string)TextReturns the provided with leading and trailing spaces removed.
LEFT(string, number)TextReturns the left-most of characters in the string.
RIGHT(string, number)TextReturns the right-most of characters in the string.
STR(expression)TextCasts its argument as a string.
FIND(string, substring, [start])NumberReturns the index position of substring in string, or 0 if the substring isn’t found. The first character in the string is position 1. If the optional numeric argument start is added, the function ignores any instances of substring that appear before the starting position.
FINDNTH(string, substring, occurrence)NumberReturns the position of the nth occurrence of substring within the specified string, where n is defined by the occurrence argument.
REGEXP_REPLACE(string, pattern, replacement)TextReturns a copy of the given string where the regular expression pattern is replaced by the replacement string.
REGEXP_MATCH(string, pattern)BooleanReturns true if a substring of the specified string matches the regular expression pattern.
REGEXP_EXTRACT(string, pattern)TextReturns the portion of the string that matches the regular expression pattern.
REGEXP_EXTRACT_NTH(string, pattern, index)TextReturns the portion of the string that matches the regular expression pattern. The substring is matched to the nth capturing group, where n is the given index. If index is 0, the entire string is returned.
RTRIM(string)TextReturns the provided with any trailing spaces removed.
LTRIM(string)TextReturns the provided with any leading spaces removed.
PROPER(string)TextReturns the provided with the first letter of each word is capitalized and the remaining letters are in lowercase.
ASCII(string)NumberReturns the ASCII code for the first character of a .
MID(string, start, [length])TextReturns a string starting at the specified start position. The first character in the string is position 1. If the optional numeric argument length is added, the returned string includes only that number of characters.
STARTSWITH(string, substring)BooleanReturns true if string starts with substring. Leading white spaces are ignored.
ENDSWITH(string, substring)BooleanReturns true if the given ends with the specified . Trailing white spaces are ignored.
SPACE(number)TextReturns a string that is composed of the specified number of repeated spaces.

Date/Fiscal 

Evaluation: Row-level.

FunctionReturn typeDescription
DATEADD(date_part, interval, date)Date (or DateTime)Returns the with the specified number added to the specified <date_part> of that date. For example, adding three months or 12 days to a starting date.
MAKEDATE(year, month, day)DateReturns a date value constructed from the specified , , and .
DATEPART(date_part, date, [start_of_week])NumberReturns the name of the specified date part as an integer.
DATE(expression)DateReturns a date given a number, string, or date .
DATEPARSE(date_format, date_string)DateTimeReturns specifically formatted strings as dates.
TODAY()DateReturns the current date as a date data type.
DATETRUNC(date_part, date, [start_of_week])Date (or DateTime)This function can be thought of as date rounding. It takes a specific date and returns a version of that date at the desired specificity. Because every date must have a value for day, month, quarter, and year, DATETRUNC sets the values as the lowest value for each date part up to the date part specified. Refer to the example for more information.
DATEDIFF(date_part, date1, date2, [start_of_week])NumberReturns the number of date parts (weeks, years, etc) between two dates.
DATENAME(date_part, date, [start_of_week])TextReturns <date_part> of as a string.
DATETIME(expression)DateTimeReturns a datetime given a number, string, or date expression.
QUARTER(date)NumberReturns the quarter of the given as an integer.
ISDATE(string)BooleanReturns true if a given is a valid date.
NOW()DateTimeReturns the current local system date and time.
MAKETIME(hour, minute, second)DateTimeReturns a date value constructed from the specified , , and .
MAKEDATETIME(date, time)DateTimeReturns a datetime that combines a and a
ISOWEEK(date)NumberReturns the ISO8601 week-based week of a given as an integer.
ISOYEAR(date)NumberReturns the ISO8601 week-based year of a given date as an integer.
ISOQUARTER(date)NumberReturns the ISO8601 week-based quarter of a given as an integer.
ISOWEEKDAY(date)NumberReturns the ISO8601 week-based weekday of a given as an integer.
DAY(date)NumberReturns the day of the given as an integer.
WEEK(date)NumberReturns the week of the given as an integer.
MONTH(date)NumberReturns the month of the given as an integer.
YEAR(date)NumberReturns the year of the given as an integer.

Functions that take a date_part argument (such as DATEADD, DATEPART, DATETRUNC, DATEDIFF, and DATENAME) accept these values: year, quarter, month, week, day, dayofyear, weekday, hour, minute, second, milliseconds, iso-year, iso-quarter, iso-week, and iso-weekday. Fiscal-calendar variants — fiscal_year, fiscal_quarter, fiscal_month, and fiscal_week — are also accepted, and follow the model’s fiscal-year configuration.

Conditional & Null 

Evaluation: Row-level.

FunctionReturn typeDescription
CASE <expression> WHEN <value> THEN <result> [WHEN ...] [ELSE <default>] ENDDynamicEvaluates the expression and compares it to the specified options (, , etc.). When a value that matches expression is encountered, CASE returns the corresponding return. If no match is found, the (optional) default is returned. If there is no default and no values match, then Null is returned.
IF <test> THEN <result> [ELSEIF <test> THEN <result> ...] [ELSE <default>] ENDDynamicTests a series of expressions and returns the value for the first true .
IIF(<test>, <then>, <else>, [<unknown>])DynamicChecks whether a condition is met (), and returns if the test is true, if the test is false, and an optional value for if the test is null. If the optional unknown isn’t specified, IIF returns null.
NOT <expression>BooleanPerforms logical negation on an expression.
<expr1> IN <expr2>BooleanReturns TRUE if any value in matches any value in .
IFNULL(expr1, expr2)DynamicReturns if it’s non-null, otherwise returns .
ZN(expression)NumberReturns if it isn’t null, otherwise returns zero.
ISNULL(expression)BooleanReturns true if the is NULL (does not contain valid data).

The IF and CASE functions support multi-line syntax with the keywords THEN, ELSE, ELSEIF (for IF), WHEN (for CASE), and END:

1IF <test1> THEN <then1>
2ELSEIF <test2> THEN <then2>
3...
4[ELSE <default>]
5END
1CASE <expression>
2WHEN <value1> THEN <then1>
3WHEN <value2> THEN <then2>
4...
5[ELSE <default>]
6END

Aggregation 

Evaluation: Aggregate. Each function collapses the rows in a group into a single measurement value. Set the calculated field’s aggregation method to SEMANTIC_AGGREGATION_METHOD_USER_AGG when wrapping one of these (see Limitations).

FunctionReturn typeDescription
COUNTD(expression)NumberReturns the number of distinct items in a group. Null values are not counted.
MAX(expression)DynamicReturns the maximum of a single field as an aggregation. MAX applied to two arguments is a row-level function — see Math.
MIN(expression)DynamicReturns the minimum of a single field as an aggregation. MIN applied to two arguments is a row-level function — see Math.
AVG(expression)NumberReturns the average of all the values in the expression. Null values are ignored.
MEDIAN(expression)NumberReturns the median of an expression across all records. Null values are ignored.
COUNT(expression)NumberReturns the number of non-distinct items in a group. Null values are not counted.
SUM(expression)NumberReturns the sum of all values in the expression. Null values are ignored.
PERCENTILE(expression, number)NumberReturns the percentile value from the given expression corresponding to the specified . The must be between 0 and 1 (inclusive) and must be a numeric constant.
CORR(expression1, expression2)NumberReturns the Pearson correlation coefficient of two expressions.
COVAR(expression1, expression2)NumberReturns the sample covariance of two expressions.
COVARP(expression 1, expression2)NumberReturns the population covariance of two expressions.
STDEV(expression)NumberReturns the statistical standard deviation of all values in the given based on a sample of the population.
STDEVP(expression)NumberReturns the statistical standard deviation of all values in the given based on a biased population.
VAR(expression)NumberReturns the statistical variance of all values in the given based on a sample of the population.
VARP(expression)NumberReturns the statistical variance of all values in the given on the entire population.

Window & Table Calc 

Evaluation: Window (table calculation). Each function returns one value per row, computed over an ordered partition; it requires a PARTITION/ORDERBY frame (or window bounds). A table calculation must act on an aggregate expression (for example SUM([Sales])) or wrap another table calculation — it cannot be applied directly to a row-level expression.

Wrap a table calculation in a PARTITION/ORDERBY block that defines the partition and the sort order it operates over:

1{ PARTITION <dimension> [, <dimension> ...] :
2  { ORDERBY <dimension> [ASC | DESC] [NULLS FIRST | NULLS LAST] [, ...] :
3    <table calc function>(<aggregate expression>)
4  }
5}
1{ PARTITION [AccountSemanticLayer__dll].[Name__c] :
2  { ORDERBY [AccountSemanticLayer__dll].[KQ_Id__c] :
3    RANK(SUM([AccountSemanticLayer__dll].[AnnualRevenue__c]))
4  }
5}

PARTITION/ORDERBY blocks can’t be saved as a persistent calculated field in the model — pass them at query time on an on-the-fly calculated_field.

FunctionReturn typeDescription
FIRST()NumberReturns the number of rows from the current row to the first row in the partition. For example, the view below shows quarterly sales. When FIRST() is computed within the Date partition, the offset of the first row from the second row is -1.
LAST()NumberReturns the number of rows from the current row to the last row in the partition. For example, the table below shows quarterly sales. When LAST() is computed within the Date partition, the offset of the last row from the second row is 5.
RANK(expression, ['asc' | 'desc'])NumberReturns the standard competition rank for the current row in the partition. Identical values are assigned an identical rank.
RANK_DENSE(expression, ['asc' | 'desc'])NumberReturns the dense rank for the current row in the partition. Identical values are assigned an identical rank, but no gaps are inserted into the number sequence.
RANK_MODIFIED(expression, ['asc' | 'desc'])NumberReturns the modified competition rank for the current row in the partition. Identical values are assigned an identical rank.
RANK_PERCENTILE(expression, ['asc' | 'desc'])NumberReturns the percentile rank for the current row in the partition.
RANK_UNIQUE(expression, ['asc' | 'desc'])NumberReturns the unique rank for the current row in the partition. Identical values are assigned different ranks.
RUNNING_AVG(expression)NumberReturns the running average of the given expression, from the first row in the partition to the current row.
RUNNING_COUNT(expression)NumberReturns the running count of the given expression, from the first row in the partition to the current row.
RUNNING_MAX(expression)NumberReturns the running maximum of the given expression, from the first row in the partition to the current row.
RUNNING_MIN(expression)NumberReturns the running minimum of the given expression, from the first row in the partition to the current row.
RUNNING_SUM(expression)NumberReturns the running sum of the given expression, from the first row in the partition to the current row.
TOTAL(expression)NumberReturns the total for the given expression in a table calculation partition.
WINDOW_AVG(expression, [start, end])NumberReturns the average of the expression within the window. The window is defined by means of offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row in the partition. If the start and end are omitted, the entire partition is used.
WINDOW_CORR(expression1, expression2, [start, end])NumberReturns the Pearson correlation coefficient of two expressions within the window. The window is defined as offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row in the partition. If start and end are omitted, the entire partition is used.
WINDOW_COUNT(expression, [start, end])NumberReturns the count of the expression within the window. The window is defined by means of offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row in the partition. If the start and end are omitted, the entire partition is used.
WINDOW_COVAR(expression1, expression2, [start, end])NumberReturns the sample covariance of two expressions within the window. The window is defined as offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row in the partition. If the start and end arguments are omitted, the window is the entire partition.
WINDOW_COVARP(expression1, expression2, [start, end])NumberReturns the population covariance of two expressions within the window. The window is defined as offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row in the partition. If start and end are omitted, the entire partition is used.
WINDOW_MAX(expression, [start, end])NumberReturns the maximum of the expression within the window. The window is defined by means of offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row in the partition. If the start and end are omitted, the entire partition is used.
WINDOW_MIN(expression, [start, end])NumberReturns the minimum of the expression within the window. The window is defined by means of offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row in the partition. If the start and end are omitted, the entire partition is used.
WINDOW_STDEV(expression, [start, end])NumberReturns the sample standard deviation of the expression within the window. The window is defined by means of offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row in the partition. If the start and end are omitted, the entire partition is used.
WINDOW_STDEVP(expression, [start, end])NumberReturns the biased standard deviation of the expression within the window. The window is defined by means of offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row in the partition. If the start and end are omitted, the entire partition is used.
WINDOW_SUM(expression, [start, end])NumberReturns the sum of the expression within the window. The window is defined by means of offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row in the partition. If the start and end are omitted, the entire partition is used.
WINDOW_VAR(expression, [start, end])NumberReturns the sample variance of the expression within the window. The window is defined by means of offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row in the partition. If the start and end are omitted, the entire partition is used.
WINDOW_VARP(expression, [start, end])NumberReturns the biased variance of the expression within the window. The window is defined by means of offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row in the partition. If the start and end are omitted, the entire partition is used.
INDEX()NumberReturns a unique sequential row ID to each row.
LOOKUP(expression, offset)DynamicReturns the value of the expression in a target row, specified as a relative offset from the current row. Use FIRST() + n and LAST() - n as part of your offset definition for a target relative to the first/last rows in the partition. This function returns NULL if the target row cannot be determined.
SIZE()NumberReturns the number of rows in the partition.

Like all table calculations, these functions act on an aggregate expression or wrap another table calculation — not a row-level expression.

TOTAL is grouped with table calculations because of its evaluation scope, but it behaves differently from the row-oriented functions above (such as RANK or RUNNING_SUM). Instead of computing per row, TOTAL re-runs the underlying aggregation at the grain defined by the PARTITION clause — conceptually similar to a Level of Detail expression, but scoped to the table calculation’s partition rather than a fixed set of dimensions.

Level of Detail 

Evaluation: Level of detail. Each expression computes an aggregation at the dimensionality you specify, independent of the query’s grouping.

FunctionReturn typeDescription
{ FIXED [dimension 1], … ,[dimension n] : AGGREGATION_FUNCTION(expression) }DynamicFIXED level of detail expressions compute a value using the specified dimensions, without reference to the dimensions in the view.
{ EXCLUDE [dimension 1], … ,[dimension n] : AGGREGATION_FUNCTION(expression) }DynamicEXCLUDE level of detail expressions declare dimensions to omit from the view level of detail.
{ INCLUDE [dimension 1], … ,[dimension n] : AGGREGATION_FUNCTION(expression) }DynamicINCLUDE level of detail expressions compute values using the specified dimensions in addition to whatever dimensions are in the view.

A FIXED LOD is computed before the query’s dimension filters, so ordinary dimension filters do not reduce the rows it scans — they apply only to the outer query, not to the FIXED calculation. INCLUDE and EXCLUDE LODs are computed after dimension filters, so those filters do apply to their calculation. To constrain a FIXED calculation’s scope, use a context filter, which applies before the FIXED LOD is computed.

AI & Predictive 

Evaluation: Row-level.

FunctionReturn typeDescription
AI_SENTIMENT([tablename].[fieldname])TextClassifies the input in one of the following sentiments: positive, negative, or neutral.
AI_CLASSIFY([tablename].[fieldname], 'Category 1, Category 2, Category 3')TextClassifies the input into one of the specified categories.

Reference 

Field (wire name)TypeRequiredDescription
calculated_fieldCalculatedFieldNOn-the-fly calculated field supplied in the request; holds name, expression, and an output type.
nameStringYIdentifier for the calculated field within the request.
expressionStringYThe formula, written in the field’s syntax dialect.
syntaxString (enum)NFormula dialect. Use "Tua" (bracket notation, [Table].[Field]); it is the default for requests with an inline semanticModel.
calculated_measure_expressionCalculatedMeasureExpressionY*Marks the field as a measurement; carries measure_output_type and optional decimal_places_options.
calculated_dimension_expressionCalculatedDimensionExpressionY*Marks the field as a dimension; carries dimension_output_type.
measure_output_typeString (enum)Y*Output type of a calculated measurement, e.g. SEMANTIC_MEASUREMENT_TYPE_NUMBER.
dimension_output_typeString (enum)Y*Output type of a calculated dimension, e.g. SEMANTIC_DIMENSION_TYPE_TEXT, SEMANTIC_DIMENSION_TYPE_DATE_TIME, SEMANTIC_DIMENSION_TYPE_NUMBER.
decimal_places_optionsDecimalPlacesOptionsNSets decimal_places for a calculated measurement.
semanticField / semantic_fieldSemanticFieldExpressionNReferences a model-defined calculated field by name.
semantic_aggregation_methodString (enum)NAggregation applied to the field, e.g. SEMANTIC_AGGREGATION_METHOD_SUM, _AVG, _MIN, _MAX, _USER_AGG, _AUTO, _NONE.
row_groupingBooleanNWhen true, groups query rows by this (dimension) field.

For the full request schema, see Request Reference.

Limitations 

  • A calculated field is either a measurement or a dimension, not both. Supply exactly one of calculated_measure_expression or calculated_dimension_expression per calculated_field.
  • Wrapped aggregations use USER_AGG. When an expression contains its own aggregation function (for example COUNTD(...) or a TableCalc-level formula), set the field’s aggregation method to SEMANTIC_AGGREGATION_METHOD_USER_AGG so the expression’s aggregation is honored.
  • Table calculations require an ordering. Window and ranking functions evaluate over an ordered frame; a table-calculation formula specifies its PARTITION and ORDERBY (or window bounds) so row order is well-defined.
  • Reference parameters with bracket notation. Reference a model parameter in a formula as [Parameters].[<name>].
  • Calculated dimensions can only use FIXED LOD expressions. EXCLUDE and INCLUDE depend on the view’s grouping, which isn’t defined for a field that itself supplies grouping — use them only in calculated measurements.

Related