SQL查找原始数据,其中fielda + 1 = fieldb的值

时间:2015-10-28 18:37:26

标签: sql teradata

我还在这里学习 - 感谢您的耐心......

让我们从数据集开始。

TRANID              CODE1                   CODE2
1232                1                       NULL
1233                NULL                    DR
1234                1                       NULL
1235                NULL                    SR

基本上,我需要一个查询,说明当tranID的code1 = 1时,查找TranID + 1(紧邻的下一个tranID)的代码2为“SR”的位置

此查询应该撤回以下内容:

带有上述数据集的

TRANID, CODE1 (TRANID), CODE2(TRANID), TRANID+1, CODE1 (TRANID+1), CODE2 (TRANID+1)如下所示:

1234, 1, NULL, 1235, NULL, SR

提前感谢您的帮助,如果您需要更多信息,请告诉我们!

2 个答案:

答案 0 :(得分:3)

只需要在第一个tranId添加1的tranIds上自己将表连接到自己..然后为每个连接添加where条件

SELECT * 
FROM MyTable A
JOIN MyTable B ON (A.TranID + 1) = B.TranID
WHERE A.Code1 = 1 AND B.Code2 = 'SR'

答案 1 :(得分:0)

除了JamieD77的连接解决方​​案,您还可以尝试OLAP功能,具体取决于实际数据,这可能更有效:

SELECT t.*,
   TRANID + 1 AS next_TRANID,
--   if there might be a gap between TRANIDs you can switch to this instead:
--   MIN(TRANID) OVER (ORDER BY TRANID ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING) AS next_TRANID,

   MIN(CODE1)  OVER (ORDER BY TRANID ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING) AS next_CODE1,
   MIN(CODE2)  OVER (ORDER BY TRANID ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING) AS next_CODE2
FROM MyTable AS t
QUALIFY CODE1 = 1
    AND next_CODE2 = 'SR'

 -- if there might be a gap between TRANIDs 
 -- AND nextTRANID = TRANID + 1