Example - Advanced SQL Engine - Teradata Database

SQL Operators and User-Defined Functions

Product
Advanced SQL Engine
Teradata Database
Release Number
17.00
Published
September 2020
Language
English (United States)
Last Update
2023-04-27
dita:mapPath
qqu1556127655717.ditamap
dita:ditavalPath
lze1555437562152.ditaval
dita:id
B035-1210
lifecycle
previous
Product Category
Teradata Vantage™

Consider the following table definition and inserted data:

CREATE MULTISET TABLE t
   (id INTEGER,
    v  INTEGER);
INSERT INTO t VALUES (1,1);
INSERT INTO t VALUES (1,2);
INSERT INTO t VALUES (1,2);
INSERT INTO t VALUES (1,4);
INSERT INTO t VALUES (1,5);
INSERT INTO t VALUES (1,5);
INSERT INTO t VALUES (1,5);
INSERT INTO t VALUES (1,8);
INSERT INTO t VALUES (1,);

The following is the SQL definition of a window aggregate UDF that performs the dense rank operation:

REPLACE FUNCTION dense_rank (x INTEGER)
RETURNS INTEGER
CLASS AGGREGATE (1000)
LANGUAGE C
NO SQL
PARAMETER STYLE SQL
DETERMINISTIC
CALLED ON NULL INPUT
EXTERNAL;

The dense_rank UDF evaluates dense rank over the set of values passed as arguments to the UDF. With dense ranking, items that compare equal receive the same ranking number, and the next item(s) receive the immediately following ranking number. In the following query and result, note the difference in the rank and dense rank value for v=4. The dense rank value is 4 whereas the rank of 4 is 5.

SELECT v, dense_rank(v) OVER (PARTITION BY id ORDER BY v 
   ROWS UNBOUNDED PRECEDING) as dr,
   rank() OVER (PARTITION BY id ORDER BY v) as r
FROM t ORDER BY dr;

The output from the SELECT statement is:

          v           dr            r
-----------  -----------  -----------
          ?            1            1
          1            2            2
          2            3            3
          2            3            3
          4             4              5 
          5            5            6
          5            5            6
          5            5            6
          8            6            9

For a C code example of the dense_rank UDF, see “C Window Aggregate Function” in Teradata Vantage™ - SQL External Routine Programming, B035-1147.