GROUP BY and Window Functions - Advanced SQL Engine - Teradata Database

SQL Functions, Expressions, and Predicates

Product
Advanced SQL Engine
Teradata Database
Release Number
17.10
Published
July 2021
Language
English (United States)
Last Update
2021-07-28
dita:mapPath
SQL_Functions__Expressions__and_Predicates.Upload_071421/djk1612415574830.ditamap
dita:ditavalPath
SQL_Functions__Expressions__and_Predicates.Upload_071421/wrg1590696035526.ditaval
dita:id
B035-1145
lifecycle
previous
Product Category
Teradata Vantageā„¢

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