简体   繁体   中英

Counters in Teradata while inserting records

I am trying to insert records in a table in the below format

Name              Amount       Date       Counter    
A                  100        Jan 1          1
A                  100        Jan2           1
A                  200        Jan 10         2
A                  300        Mar 30         3
B                   50        Jan 7          1
C                   20        Jan 7          1

Could someone tell me the sql for generating the value for the Counter field . The counter value should increment whenever the amount changes and reset when the name changes.

What you need is a DENSE_RANK function. Unfortunately it's not natively implemented before TD14.10, but it can be written using nested OLAP-functions:

SELECT
   Name
   ,Amount
   ,date_col
   ,SUM(flag)
    OVER (PARTITION BY Name
          ORDER BY date_col
          ROWS UNBOUNDED PRECEDING) AS "DENSE_RANK"
FROM
 (
   SELECT
      Name
      ,Amount
      ,date_col
      ,CASE
          WHEN Amount = MIN(Amount)
                        OVER (PARTITION BY Name 
                              ORDER BY date_col
                              ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING)
          THEN 0 
          ELSE 1
       END AS flag
   FROM dropme
 ) AS dt;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM