Microsoft SQL Server 2005: The Complete Reference: Full Coverage of all New and Improved Features

The COMPUTE keyword directs SQL Server to generate totals that appear as additional summary columns at the end of result sets. When you use the COMPUTE with BY, the clause forces control-breaks and subtotals in the result set. You can also specify COMPUTE BY and COMPUTE in the same query. The syntax for the COMPUTE is as follows:

[COMPUTE {{AVG | COUNT | MAX | MIN | STDEV | STDEVP |VAR | VARP | SUM } ( expression ) } [ ,…n ] [ BY expression [ , …n ] ] ]

The following list of COMPUTE arguments specifies the aggregation to be performed:

Rules to consider when using the COMPUTE arguments:

The expression placeholder specifies a variable, such as the name of a column, on which the calculation is performed. The expression must appear in the select list and must be specified exactly the same as one of the expressions in the select list. As you can see from the syntax, you place the expression after the COMPUTE argument. A column alias specified in the select list obviously cannot be used within the COMPUTE expression.

Using BY

The BY expression is used to generate control-breaks and subtotals in the result set. Listing multiple expressions after BY breaks a group into subgroups and applies the aggregate function at each level of grouping. If you use the keywords COMPUTE BY, you must also use an ORDER BY clause. The expressions must be identical to or a subset of those listed after ORDER BY, and they must be in the same sequence. For example, if the ORDER BY clause is

ORDER BY s, 1, t

then the COMPUTE clause can be any (or all) of these:

COMPUTE BY s, 1, COMPUTE BY s, 1 COMPUTE BY s

Note 

The aforementioned aggregation and computer facilities of the SELECT statement are useful for ad hoc reporting and the like. If you need to present substantial statistical analysis or create extensive or repetitive financial results, these queries can be a drain on the resources of a standard OLTP database. Rather, take your reporting to the logical level and report against the data warehouse using OLAP facilities.

Категории