GROUP BY and Window Functions

Teradata Vantageā„¢ SQL Functions, Expressions, and Predicates

brand
Software
Teradata Vantage
prodname
Teradata Database
Teradata Vantage NewSQL Engine
vrm_release
16.20
category
Programming Reference
featnum
B035-1145-162K

For window functions, the GROUP BY clause must include all the columns specified in the:

  • Select list of the SELECT clause
  • Window functions in the select list of a SELECT clause
  • Window functions in the search condition of a QUALIFY clause
  • The condition in the RESET WHEN clause

For example, the following SELECT statement specifies the column City in the select list and the column StoreID in the COUNT window function in the select list and QUALIFY clause. Both columns must also appear in the GROUP BY clause:

   SELECT City, StoreID, COUNT(StoreID) OVER ()
   FROM sales_tbl 
   GROUP BY City, StoreID
   QUALIFY COUNT(StoreID) >=3;

For window functions, GROUP BY collapses all rows with the same value for the group-by columns into a single row.

For example, the following statement uses the GROUP BY clause to collapse all rows with the same value for City and StoreID into a single row:

   SELECT City, StoreID, COUNT(StoreID) OVER ()
   FROM sales_tbl 
   GROUP BY City, StoreID;

The results look like this:

   City   StoreID  Group Count(StoreID)
   -----  -------  --------------------
   Pecos     1001                     3
   Pecos     1002                     3
   Ozona     1003                     3

Without the GROUP BY, the results look like this:

   City   StoreID  Group Count(StoreID)
   -----  -------  --------------------
   Pecos     1001                     9
   Pecos     1001                     9
   Pecos     1001                     9
   Pecos     1001                     9
   Pecos     1002                     9
   Pecos     1002                     9
   Pecos     1002                     9
   Ozona     1003                     9
   Ozona     1003                     9