SQL 查找原始数据,其中 fielda+1 = fieldb 的值
SQL Find original data and where fielda+1 = value of a fieldb
我还在学习 - 感谢您的耐心等待...
让我们从数据集开始。
TRANID CODE1 CODE2
1232 1 NULL
1233 NULL DR
1234 1 NULL
1235 NULL SR
基本上,我需要一个查询,说明当 tranID 的代码 1 = 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
提前感谢您的帮助,如果您需要更多信息,请告诉我!
只需要在第一个 tranId 添加 1 的 tranId 上将您的 table 自身连接到自身。然后为每个连接添加 where 条件
SELECT *
FROM MyTable A
JOIN MyTable B ON (A.TranID + 1) = B.TranID
WHERE A.Code1 = 1 AND B.Code2 = 'SR'
除了 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
我还在学习 - 感谢您的耐心等待...
让我们从数据集开始。
TRANID CODE1 CODE2
1232 1 NULL
1233 NULL DR
1234 1 NULL
1235 NULL SR
基本上,我需要一个查询,说明当 tranID 的代码 1 = 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
提前感谢您的帮助,如果您需要更多信息,请告诉我!
只需要在第一个 tranId 添加 1 的 tranId 上将您的 table 自身连接到自身。然后为每个连接添加 where 条件
SELECT *
FROM MyTable A
JOIN MyTable B ON (A.TranID + 1) = B.TranID
WHERE A.Code1 = 1 AND B.Code2 = 'SR'
除了 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