您好我想在Teradata V14 sql中做。 我的源表是这样的:
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
我的目标表应为:
{{1}}
New_Col1 - 行号 New_Col2 - 如果col1和col2顺序相同,则应为New_COl2。否则应生成新的序列号 能帮助我实现这一目标。
答案 0 :(得分:2)
您需要嵌套的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
答案 1 :(得分:0)
看起来第二个新列只是 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;