2016-02-25 61 views
-1

您好我正在嘗試在Teradata V14 sql中做。 我的源表是這樣的:基於另一列排序生成新列 - SQL

acc col1 col2 

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

我的目標表應該是:

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。否則應該生成其他新的序列號 任何可以幫助我實現這一點。

+1

而這些新列的背後是你的邏輯....? – Siyual

+0

添加了Siyual。謝謝 – Madan

回答

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 
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;