根据另一个列排序生成新列 - SQL

Generate new column based on another column sequencing - SQL

您好,我正在尝试在 Teradata V14 sql 中进行。 我的来源 table 是这样的:

acc  col1  col2

100  12     13
100  13     14
100  17     23
100  22     109
100  23     110
100  29     130

我的目标 table 应该是:

New_Col1 New_Col2 Acc col1 col2

1          1      100  12     13
2          1      100  13     14
3          2      100  17     23
4          3      100  22     109
5          3      100  23     110
6          4      100  29     130

New_Col1 - 行号 New_Col2 - 如果 col1 和 col2 在序列中相同的值应该是 New_COl2。否则应生成新的序列号 任何人都可以帮助我实现这一目标。

看来第二个新列就是col1是否有顺序。您可以使用 row_number():

select row_number() over (partition by acc order by col1),
       dense_rank() over (partition by acc order by grp),
       acc, col1, col2
from (select t.*,
             (col1 - row_number() over (partition by acc order by col1)) as grp
      from t
     ) t;

您需要嵌套的 OLAP 函数:

SELECT dt.*,
   sum(flag) 
   OVER (PARTITION BY acc
         ORDER BY new_col1
         ROWS UNBOUNDED PRECEDING)
FROM
 (
   SELECT t.*,
      ROW_NUMBER() OVER (PARTITION BY acc ORDER BY col1, col2) AS new_col1,
      CASE WHEN col1 = MIN(col1) -- col1 is sequential
                       OVER (PARTITION BY acc
                             ORDER BY col1,col2
                             ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) + 1
            AND col2 = MIN(col2) -- col2 is sequential
                       OVER (PARTITION BY acc
                             ORDER BY col1,col2
                             ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) + 1
           THEN 0 -- will be assigned to the previous group
           ELSE 1 -- will be assigned to a new group
      END AS flag   
   FROM tab AS t
 ) AS dt