Common table expressions are useful whenever multiple levels of aggregation must appear within a single query. This is the case in the example used in the previous section. The task was to retrieve the department ID of the department that has the most employees. To do so, the count aggregate function is used to calculate the number of employees in each department and the MAX function is used to select the largest department.
A similar situation arises when writing a query to determine which department has the largest payroll. The SUM aggregate function is used to calculate each department's payroll and the MAX function is used to determine which is largest. The presence of both functions in the query is a clue that a common table expression may be helpful.
WITH DepartmentPayroll( DepartmentID, amount ) AS ( SELECT DepartmentID, SUM( Salary ) AS amount FROM Employees GROUP BY DepartmentID ) SELECT DepartmentID, amount FROM DepartmentPayroll WHERE amount = ( SELECT MAX( amount ) FROM DepartmentPayroll ) |
Discuss this page in DocCommentXchange.
|
Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 |