ORDER BY Phrase - Advanced SQL Engine - Teradata Database

SQL Functions, Expressions, and Predicates

Product
Advanced SQL Engine
Teradata Database
Release Number
17.05
17.00
Published
June 2020
Language
English (United States)
Last Update
2021-01-30
dita:mapPath
tpt1555966086716.ditamap
dita:ditavalPath
lze1555437562152.ditaval
dita:id
B035-1145
lifecycle
previous
Product Category
Teradata Vantageā„¢

ORDER BY specifies how the rows are ordered in a partition, which determines the sort order of the rows over which the function is applied.

To add the monthly sales for a store in the sales_tbl table to the sales for previous months, compute the cumulative sales sum and order the rows in each partition by SMonth:

   SELECT StoreID, SMonth, ProdID, Sales,
   SUM(Sales) OVER (PARTITION BY StoreID ORDER BY SMonth 
              ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
   FROM sales_tbl;
   
   StoreID  SMonth  ProdID      Sales  Cumulative Sum(Sales)
   -------  ------  ------  ---------  ---------------------
      1001       1  C        35000.00               35000.00
      1001       2  C        25000.00               60000.00
      1001       3  C        40000.00              100000.00
      1001       4  C        25000.00              125000.00
      1001       5  C        30000.00              155000.00
      1001       6  C        30000.00              185000.00
      1002       1  C        40000.00               40000.00
      1002       2  C        35000.00               75000.00
      1002       3  C       110000.00              185000.00
      1002       4  C        60000.00              245000.00
      1002       5  C        35000.00              280000.00
      1002       6  C       100000.00              380000.00