The WITH clause is a Teradata extension to the ANSI SQL:2011 standard.
The rules and restrictions for the use of the WITH clause are:
Note that you cannot specify a scalar subquery as the argument of a WITH clause because only aggregate expressions are valid as WITH clause arguments. You can, however, specify a scalar subquery as an argument of an aggregate expression in a WITH clause.
See “Example 2: Specifying Multiple WITH Clauses in a Single SELECT Statement” on page 222.
WITH and ORDER BY clauses in the same SELECT statement function together as follows:
This is true regardless of the structure of the query or the number of WITH clauses.
See “Example 3: Combining WITH and ORDER BY Clauses” on page 223.
Specifying WITH and GROUP BY clauses in the same SELECT statement can produce unintended results.
See “Example 3: Combining WITH and ORDER BY Clauses” on page 223.
Also see “GROUP BY Clause” on page 127.
BY dept_no
specifies a summary for each value in the dept_no column; a summary line is generated following a listing of the values for each department
number.
If you do not specify a BY phrase, the summary line applies to the entire result as specified by the SELECT expression list.
Like the ORDER BY clause, the values of any expression specified by expression_2 can be sorted in either ascending or descending order. For example:
WITH SUM(salary) BY divno ASC, dept_no DESC
Likewise, expression_2 can specify a constant that references an expression by its position in the SELECT expression list. For example:
WITH SUM(salary) BY 2 ASC, 3 DESC
However, an expression that is specified in expression_1 or expression_2 need not be specified in the SELECT expression list.
You can specify the following expressions in a WITH clause.
An aggregate operator must be specified directly before each column to which the operator applies, for example, WITH SUM(salary) or MAX(yrsexp).
WITH dept_no, SUM(salary) BY dept_no
.
You cannot specify expressions that include LOB or UDT columns in a WITH clause.
Title is relevant only for FieldMode output for report generation and normally done only via BTEQ.
This clause lists the title Subtotal at each summary row:
WITH SUM(salary)(TITLE 'Subtotal')
This clause specifies a blank title:
WITH SUM(salary)(TITLE ' ')