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:

<!-- source: preparer integration/90.5-pds-table-calc -->
{
  "apiName": "AverageSumOfSales_clc",
  "label": "AverageSumOfSales",
  "dataType": "Number",
  "aggregationType": "UserAgg",
  "decimalPlace": 2,
  "expression": "WINDOW_AVG(SUM([Sales]), -3, 1)",
  "level": "TableCalc"
  // ...
}

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

<!-- source: preparer integration/90.5-pds-table-calc -->
{
  "fields": [
    {
      "expression": {
        "semanticField": {
          "name": "AverageSumOfSales_clc"
        }
      },
      "alias": "AverageSumOfSales_clc",
      "rowGrouping": false,
      "semanticAggregationMethod": "SEMANTIC_AGGREGATION_METHOD_USER_AGG"
    }
  ]
}

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:

<!-- source: preparer integration/41-power-function-tua-calc -->
{
  "fields": [
    {
      "expression": {
        "calculated_field": {
          "name": "simple_power_calc",
          "expression": "POWER(2,2)",
          "calculated_measure_expression": {
            "measure_output_type": "SEMANTIC_MEASUREMENT_TYPE_NUMBER"
          }
        }
      },
      "semantic_aggregation_method": "SEMANTIC_AGGREGATION_METHOD_SUM",
      "alias": "simple_power_calc"
    }
  ]
}

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

<!-- source: preparer integration/46.2-default-syntax-setting-sf -->
{
  "calculated_field": {
    "name": "simple-calc",
    "expression": "DATETIMEVALUE(DATE_TRUNC('day', ssot__Account__dlm.ssot__LastModifiedDate__c))",
    "calculated_dimension_expression": {
      "dimension_output_type": "SEMANTIC_DIMENSION_TYPE_DATE_TIME"
    }
  }
}

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

<!-- source: preparer integration/15-aggregative-by-fiscal-year-with-override -->
{
  "expression": {
    "calculated_field": {
      "name": "fiscal_quarter_on_the_fly_calculation",
      "expression": "CONCAT('FY', TEXT(FISCAL_QUARTER(AccountSemanticLayer__dll.LastModifiedDate__c)), '-Q', TEXT(FISCAL_YEAR(AccountSemanticLayer__dll.LastModifiedDate__c)))"
    }
  },
  "row_grouping": true
}

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

<!-- source: preparer integration/88-standard_query_table_calc_filter -->
{
  "calculated_field": {
    "name": "table_calc_running_sum",
    "expression": "{ PARTITION [AccountSemanticLayer__dll].[Name__c]: { ORDERBY [AccountSemanticLayer__dll].[KQ_Id__c] : RANK(SUM([AccountSemanticLayer__dll].[AnnualRevenue__c])) } }",
    "calculated_measure_expression": {
      "measure_output_type": "SEMANTIC_MEASUREMENT_TYPE_NUMBER",
      "decimal_places_options": {
        "decimal_places": 2
      }
    },
    "syntax": "Tua"
  }
}

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:

<!-- source: preparer integration/85-list-parameter -->
{
  "calculated_field": {
    "name": "summary-calc-in-select",
    "expression": "SUM([SemanticAccount__dlm].[sdm__AccountTypeId__c]) + [Parameters].[test12]",
    "calculated_measure_expression": {
      "measure_output_type": "SEMANTIC_MEASUREMENT_TYPE_NUMBER",
      "decimal_places_options": {
        "decimal_places": 2
      }
    }
  }
}

Arithmetic can also combine field references directly:

<!-- source: preparer integration/120-relationship-with-nested-semantic-field -->
{
  "calculated_field": {
    "name": "nested_semantic_field_calc",
    "expression": "[logical_table].[AnnualRevenue] + [SemanticContact_SDO].[MailingLatitude]",
    "syntax": "Tua",
    "calculated_measure_expression": {
      "measure_output_type": "SEMANTIC_MEASUREMENT_TYPE_NUMBER"
    }
  }
}

Math and numeric functions

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

<!-- source: preparer integration/41-power-function-tua-calc -->
{
  "calculated_field": {
    "name": "simple_power_calc",
    "expression": "POWER(2,2)",
    "calculated_measure_expression": {
      "measure_output_type": "SEMANTIC_MEASUREMENT_TYPE_NUMBER"
    }
  }
}

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:

<!-- source: preparer integration/106.2-unified-filter-without-select-preserves-calc-table-calc -->
{
  "apiName": "Calculation18",
  "dataType": "Number",
  "aggregationType": "UserAgg",
  "expression": "(ZN(SUM([Superstore_Orders].[Sales])) - LOOKUP(ZN(SUM([Superstore_Orders].[Sales])), -1)) / ABS(LOOKUP(ZN(SUM([Superstore_Orders].[Sales])), -1))",
  "level": "TableCalc"
}

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:

<!-- source: preparer integration/15-aggregative-by-fiscal-year-with-override -->
{
  "calculated_field": {
    "name": "fiscal_quarter_on_the_fly_calculation",
    "expression": "CONCAT('FY', TEXT(FISCAL_QUARTER(AccountSemanticLayer__dll.LastModifiedDate__c)), '-Q', TEXT(FISCAL_YEAR(AccountSemanticLayer__dll.LastModifiedDate__c)))"
  }
}

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:

<!-- source: preparer integration/123-unmapped-field-in-model-only -->
{
  "apiName": "Avg_Quality_Score_clc",
  "dataType": "Text",
  "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"
}

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:

<!-- source: preparer integration/46.2-default-syntax-setting-sf -->
{
  "calculated_field": {
    "name": "simple-calc",
    "expression": "DATETIMEVALUE(DATE_TRUNC('day', ssot__Account__dlm.ssot__LastModifiedDate__c))",
    "calculated_dimension_expression": {
      "dimension_output_type": "SEMANTIC_DIMENSION_TYPE_DATE_TIME"
    }
  }
}

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

<!-- source: preparer integration/90.3-pds-model-calc-on-calc -->
{
  "calculated_field": {
    "name": "datepartyear:F1",
    "expression": "DATEPART('year', [ship_datetime_clc])",
    "calculated_dimension_expression": {
      "dimension_output_type": "SEMANTIC_DIMENSION_TYPE_NUMBER"
    },
    "syntax": "Tua"
  }
}

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:

<!-- source: preparer integration/15-aggregative-by-fiscal-year-with-override -->
{
  "calculated_field": {
    "name": "fiscal_quarter_on_the_fly_calculation",
    "expression": "CONCAT('FY', TEXT(FISCAL_QUARTER(AccountSemanticLayer__dll.LastModifiedDate__c)), '-Q', TEXT(FISCAL_YEAR(AccountSemanticLayer__dll.LastModifiedDate__c)))"
  }
}

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:

<!-- source: preparer integration/94.6-calc-with-unmapped-fields -->
{
  "apiName": "Open_Pipeline_clc",
  "dataType": "Number",
  "aggregationType": "Sum",
  "expression": "IF [Opportunity26].[Opportunity_Forecast_Category110] IN (\"Pipeline\", \"Best Case\", \"Most Likely\", \"Commit\") \n    THEN [Opportunity26].[Total_Amount19]\nEND",
  "level": "Row"
}

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

<!-- source: preparer integration/94.6-calc-with-unmapped-fields -->
{
  "apiName": "Test_clc",
  "dataType": "Number",
  "aggregationType": "UserAgg",
  "expression": "IFNULL(COUNT([Opportunity26].[Opportunity_Id23]),0)+IFNULL(COUNT([Product2].[Product_Id75]),0)",
  "level": "AggregateFunction"
}

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:

<!-- source: preparer integration/106.2-unified-filter-without-select-preserves-calc-table-calc -->
{
  "apiName": "Calculation18",
  "expression": "(ZN(SUM([Superstore_Orders].[Sales])) - LOOKUP(ZN(SUM([Superstore_Orders].[Sales])), -1)) / ABS(LOOKUP(ZN(SUM([Superstore_Orders].[Sales])), -1))",
  "aggregationType": "UserAgg",
  "level": "TableCalc"
  // ...
}

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:

<!-- source: preparer integration/42-countd-tua-calc -->
{
  "calculated_field": {
    "name": "countd",
    "expression": "COUNTD([SemanticAccount__dlm].[semantic__AccountSource__c])",
    "calculated_measure_expression": {
      "measure_output_type": "SEMANTIC_MEASUREMENT_TYPE_NUMBER"
    }
  }
}

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:

<!-- source: preparer integration/105-2-advanced-dimension-filters-v2-without-select -->
{
  "operator": "AdvancedDimension",
  "top_bottom_criteria": {
    "top_bottom_limit": 10,
    "expression": "MEDIAN([superstore_fixed_nulls].[Quantity150])"
  }
}

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:

<!-- source: preparer integration/90.5-pds-table-calc -->
{
  "apiName": "AverageSumOfSales_clc",
  "dataType": "Number",
  "aggregationType": "UserAgg",
  "expression": "WINDOW_AVG(SUM([Sales]), -3, 1)",
  "level": "TableCalc"
  // ...
}

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:

<!-- source: preparer integration/106.2-unified-filter-without-select-preserves-calc-table-calc -->
{
  "apiName": "Calculation18",
  "expression": "(ZN(SUM([Superstore_Orders].[Sales])) - LOOKUP(ZN(SUM([Superstore_Orders].[Sales])), -1)) / ABS(LOOKUP(ZN(SUM([Superstore_Orders].[Sales])), -1))",
  "aggregationType": "UserAgg",
  "level": "TableCalc"
  // ...
}

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:

<!-- source: preparer integration/88-standard_query_table_calc_filter -->
{
  "calculated_field": {
    "name": "table_calc_running_sum",
    "expression": "{ PARTITION [AccountSemanticLayer__dll].[Name__c]: { ORDERBY [AccountSemanticLayer__dll].[KQ_Id__c] : RANK(SUM([AccountSemanticLayer__dll].[AnnualRevenue__c])) } }",
    "calculated_measure_expression": {
      "measure_output_type": "SEMANTIC_MEASUREMENT_TYPE_NUMBER",
      "decimal_places_options": { "decimal_places": 2 }
    },
    "syntax": "Tua"
  }
}

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:

<!-- source: preparer integration/106.2-unified-filter-without-select-preserves-calc-table-calc -->
{
  "unified_filter": {
    "filter_logic": "1",
    "filters": [
      {
        "fields": [
          {
            "expression": "{ORDERBY [Superstore_Orders].[Region] ASC NULLS FIRST : ([Row_Index_1_clc])}"
          }
        ],
        "operator": "Between",
        "values": [1, 2],
        "include_nulls": false
      }
    ]
  }
}

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:

<!-- source: preparer integration/101_CalculatedDimension_in_model_filter -->
{
  "apiName": "FFact_owner_opp_history_lv_clc",
  "label": "FFact owner - opp history lv",
  "dataType": "Boolean",
  "expression": "LEFT([SW_FF_OPP_HIS_PA_lv].[Forecasting_Fact10_Owner], 15) = LEFT(USERID(), 15)"
}

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:

<!-- source: preparer integration/85-list-parameter -->
{
  "calculated_field": {
    "name": "summary-calc-in-select",
    "expression": "SUM([SemanticAccount__dlm].[sdm__AccountTypeId__c]) + [Parameters].[test12]",
    "calculated_measure_expression": {
      "measure_output_type": "SEMANTIC_MEASUREMENT_TYPE_NUMBER",
      "decimal_places_options": {
        "decimal_places": 2
      }
    }
  }
}

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.

Function Return type Description
MAX(expr1, expr2) Dynamic Returns 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) Dynamic Returns 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]) Number Rounds <number> 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() Number Returns a random decimal number in the following range 0.0 <= x < 1.0.
INT(expression) Number Casts its argument as an integer.
CEILING(number) Number Rounds a <number> to the nearest integer of equal or greater value.
FLOOR(number) Number Rounds a number to the nearest <number> of equal or lesser value.
POWER(number, power) Number Raises the <number> to the specified <power>.
SIN(number) Number Returns the sine of an angle.
COS(number) Number Returns the cosine of an angle.
TAN(number) Number Returns the tangent of an angle.
COT(number) Number Returns the cotangent of an angle.
ACOS(number) Number Returns the arccosine (angle) of the given <number>.
ASIN(number) Number Returns the arcsine (angle) of a given <number>.
ATAN(number) Number Returns the arctangent (angle) of a given <number>.
ATAN2(y number, x number) Number Returns the arctangent (angle) between two numbers (x and y). The result is in radians.
PI() Number Returns the numeric constant pi: 3.14159...
LN(number) Number Returns the natural logarithm of a <number>.
RADIANS(number) Number Converts the given <number> from degrees to radians.
DEGREES(number) Number Converts an angle in radians to degrees.
ABS(number) Number Returns the absolute value of the given <number>.
DIV(integer1, integer2) Number Returns the integer part of a division operation, in which <integer1> is divided by <integer2>.
SIGN(number) Number Returns the sign of a <number>: 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) Number Returns the square of a <number>.
EXP(number) Number Returns e raised to the power of the given <number>.
LOG(number, [base]) Number Returns the logarithm of a <number> for the given <base>. If the optional base argument isn't present, base 10 is used.
FLOAT(expression) Number Casts its argument as a floating point number.

String

Evaluation: Row-level.

Function Return type Description
CONTAINS(string, substring) Boolean Compares two arguments of text and returns TRUE if the first argument contains the second argument. If not, returns FALSE.
LEN(string) Number Returns the length of the string.
LOWER(string) Text Returns the provided <string> in all lowercase characters.
REPLACE(string, substring, replacement) Text Searches <string> for <substring> and replaces it with <replacement>. If <substring> is not found, the string is not changed.
UPPER(string) Text Returns the provided <string> in all uppercase characters.
SPLIT(string, delimiter, token number) Text Returns a substring from a string, using a delimiter character to divide the string into a sequence of tokens.
TRIM(string) Text Returns the provided <string> with leading and trailing spaces removed.
LEFT(string, number) Text Returns the left-most <number> of characters in the string.
RIGHT(string, number) Text Returns the right-most <number> of characters in the string.
STR(expression) Text Casts its argument as a string.
FIND(string, substring, [start]) Number Returns 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) Number Returns 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) Text Returns a copy of the given string where the regular expression pattern is replaced by the replacement string.
REGEXP_MATCH(string, pattern) Boolean Returns true if a substring of the specified string matches the regular expression pattern.
REGEXP_EXTRACT(string, pattern) Text Returns the portion of the string that matches the regular expression pattern.
REGEXP_EXTRACT_NTH(string, pattern, index) Text Returns 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) Text Returns the provided <string> with any trailing spaces removed.
LTRIM(string) Text Returns the provided <string> with any leading spaces removed.
PROPER(string) Text Returns the provided <string> with the first letter of each word is capitalized and the remaining letters are in lowercase.
ASCII(string) Number Returns the ASCII code for the first character of a <string>.
MID(string, start, [length]) Text Returns 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) Boolean Returns true if string starts with substring. Leading white spaces are ignored.
ENDSWITH(string, substring) Boolean Returns true if the given <string> ends with the specified <substring>. Trailing white spaces are ignored.
SPACE(number) Text Returns a string that is composed of the specified number of repeated spaces.

Date/Fiscal

Evaluation: Row-level.

Function Return type Description
DATEADD(date_part, interval, date) Date (or DateTime) Returns the <date> with the specified number <interval> 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) Date Returns a date value constructed from the specified <year>, <month>, and <day>.
DATEPART(date_part, date, [start_of_week]) Number Returns the name of the specified date part as an integer.
DATE(expression) Date Returns a date given a number, string, or date <expression>.
DATEPARSE(date_format, date_string) DateTime Returns specifically formatted strings as dates.
TODAY() Date Returns 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]) Number Returns the number of date parts (weeks, years, etc) between two dates.
DATENAME(date_part, date, [start_of_week]) Text Returns <date_part> of <date> as a string.
DATETIME(expression) DateTime Returns a datetime given a number, string, or date expression.
QUARTER(date) Number Returns the quarter of the given <date> as an integer.
ISDATE(string) Boolean Returns true if a given <string> is a valid date.
NOW() DateTime Returns the current local system date and time.
MAKETIME(hour, minute, second) DateTime Returns a date value constructed from the specified <hour>, <minute>, and <second>.
MAKEDATETIME(date, time) DateTime Returns a datetime that combines a <date> and a <time>. The date can be a date, datetime, or a string type. The time must be a datetime.
ISOWEEK(date) Number Returns the ISO8601 week-based week of a given <date> as an integer.
ISOYEAR(date) Number Returns the ISO8601 week-based year of a given date as an integer.
ISOQUARTER(date) Number Returns the ISO8601 week-based quarter of a given <date> as an integer.
ISOWEEKDAY(date) Number Returns the ISO8601 week-based weekday of a given <date> as an integer.
DAY(date) Number Returns the day of the given <date> as an integer.
WEEK(date) Number Returns the week of the given <date> as an integer.
MONTH(date) Number Returns the month of the given <date> as an integer.
YEAR(date) Number Returns the year of the given <date> 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.

Function Return type Description
CASE <expression> WHEN <value> THEN <result> [WHEN ...] [ELSE <default>] END Dynamic Evaluates the expression and compares it to the specified options (<value1>, <value2>, 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>] END Dynamic Tests a series of expressions and returns the <then> value for the first true <test>.
IIF(<test>, <then>, <else>, [<unknown>]) Dynamic Checks whether a condition is met (<test>), and returns <then>if the test is true, <else> if the test is false, and an optional value for <unknown> if the test is null. If the optional unknown isn't specified, IIF returns null.
NOT <expression> Boolean Performs logical negation on an expression.
<expr1> IN <expr2> Boolean Returns TRUE if any value in <expr1> matches any value in <expr2>.
IFNULL(expr1, expr2) Dynamic Returns <expr1> if it's non-null, otherwise returns <expr2>.
ZN(expression) Number Returns <expression> if it isn't null, otherwise returns zero.
ISNULL(expression) Boolean Returns true if the <expression> 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:

IF <test1> THEN <then1>
ELSEIF <test2> THEN <then2>
...
[ELSE <default>]
END
CASE <expression>
WHEN <value1> THEN <then1>
WHEN <value2> THEN <then2>
...
[ELSE <default>]
END

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).

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

{ PARTITION <dimension> [, <dimension> ...] :
  { ORDERBY <dimension> [ASC | DESC] [NULLS FIRST | NULLS LAST] [, ...] :
    <table calc function>(<aggregate expression>)
  }
}
<!-- source: preparer integration/88-standard_query_table_calc_filter -->
{ PARTITION [AccountSemanticLayer__dll].[Name__c] :
  { ORDERBY [AccountSemanticLayer__dll].[KQ_Id__c] :
    RANK(SUM([AccountSemanticLayer__dll].[AnnualRevenue__c]))
  }
}

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.

Function Return type Description
FIRST() Number Returns 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() Number Returns 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']) Number Returns the standard competition rank for the current row in the partition. Identical values are assigned an identical rank.
RANK_DENSE(expression, ['asc' | 'desc']) Number Returns 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']) Number Returns the modified competition rank for the current row in the partition. Identical values are assigned an identical rank.
RANK_PERCENTILE(expression, ['asc' | 'desc']) Number Returns the percentile rank for the current row in the partition.
RANK_UNIQUE(expression, ['asc' | 'desc']) Number Returns the unique rank for the current row in the partition. Identical values are assigned different ranks.
RUNNING_AVG(expression) Number Returns the running average of the given expression, from the first row in the partition to the current row.
RUNNING_COUNT(expression) Number Returns the running count of the given expression, from the first row in the partition to the current row.
RUNNING_MAX(expression) Number Returns the running maximum of the given expression, from the first row in the partition to the current row.
RUNNING_MIN(expression) Number Returns the running minimum of the given expression, from the first row in the partition to the current row.
RUNNING_SUM(expression) Number Returns the running sum of the given expression, from the first row in the partition to the current row.
TOTAL(expression) Number Returns the total for the given expression in a table calculation partition.
WINDOW_AVG(expression, [start, end]) Number Returns 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]) Number Returns 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]) Number Returns 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]) Number Returns 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]) Number Returns 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]) Number Returns 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]) Number Returns 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]) Number Returns 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]) Number Returns 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]) Number Returns 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]) Number Returns 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]) Number Returns 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() Number Returns a unique sequential row ID to each row.
LOOKUP(expression, offset) Dynamic Returns 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() Number Returns 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.

Function Return type Description
{ FIXED [dimension 1], … ,[dimension n] : AGGREGATION_FUNCTION(expression) } Dynamic FIXED 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) } Dynamic EXCLUDE level of detail expressions declare dimensions to omit from the view level of detail.
{ INCLUDE [dimension 1], … ,[dimension n] : AGGREGATION_FUNCTION(expression) } Dynamic INCLUDE 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.

Function Return type Description
AI_SENTIMENT([tablename].[fieldname]) Text Classifies the input in one of the following sentiments: positive, negative, or neutral.
AI_CLASSIFY([tablename].[fieldname], 'Category 1, Category 2, Category 3') Text Classifies the input into one of the specified categories.

Reference

Field (wire name) Type Required Description
calculated_field CalculatedField N On-the-fly calculated field supplied in the request; holds name, expression, and an output type.
name String Y Identifier for the calculated field within the request.
expression String Y The formula, written in the field's syntax dialect.
syntax String (enum) N Formula dialect. Use "Tua" (bracket notation, [Table].[Field]); it is the default for requests with an inline semanticModel.
calculated_measure_expression CalculatedMeasureExpression Y* Marks the field as a measurement; carries measure_output_type and optional decimal_places_options.
calculated_dimension_expression CalculatedDimensionExpression Y* Marks the field as a dimension; carries dimension_output_type.
measure_output_type String (enum) Y* Output type of a calculated measurement, e.g. SEMANTIC_MEASUREMENT_TYPE_NUMBER.
dimension_output_type String (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_options DecimalPlacesOptions N Sets decimal_places for a calculated measurement.
semanticField / semantic_field SemanticFieldExpression N References a model-defined calculated field by name.
semantic_aggregation_method String (enum) N Aggregation applied to the field, e.g. SEMANTIC_AGGREGATION_METHOD_SUM, _AVG, _MIN, _MAX, _USER_AGG, _AUTO, _NONE.
row_grouping Boolean N When 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