20.4. Grouping on Computed Columns

SQL-99 allows queries that are grouped on the result of a computed column. For example, to do a report by months on sales, you would write:

SELECT EXTRACT(MONTH FROM sale_date) AS rpt_month,
SUM(sales_amt)
  FROM Sales
 GROUP BY rpt_month;

This is a departure from the SQL processing model in previous standards, which allowed only column names. In the original model, the SELECT statement computes the expressions in the SELECT clause last, so the computed columns do not exist until after the grouping is done, so there should be no way to group them.

However, you can fake it in older versions of SQL by using a subquery expression in the FROM clause to build a working table with the computation in it.

SELECT salesmonth, ...

Get Joe Celko's SQL for Smarties, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.