【问题标题】:teradata recursive query scenarioteradata 递归查询场景
【发布时间】:2016-11-20 23:06:44
【问题描述】:

我有一个如下的输入表

Order_id    previous_order_id   ordertype_opprotunity   global_order_id
 103        102                "in progress"            11111
 102        101                "in progress             22222
 101        xx                 "new order"              33333

我需要递归检查 order_id 和 previous_order_id 直到 ordertype_opprotunity 匹配“new_order”,然后选择 global_order_id 的值。
例如,对于 103 prev 是 102 然后对于 102 prev 是 101 对于 101 ordertype_opprotunity 是“新订单”,值为 33333。
输出会像

Order_id  global_order_id
103       33333

【问题讨论】:

  • 它必须是查询,或者它可以是存储过程选择你想要的东西在最后?
  • 它应该是一个查询,因为我们想将它用作查找。
  • 请对此提供任何帮助

标签: sql teradata


【解决方案1】:

有几种方法可以得到预期的结果。

您可以从“最后一个”订单开始,沿着链条往上走,直到找到“新订单”:

WITH RECURSIVE cte AS
 (
   SELECT t.*, Order_id AS baseOrder_id
   FROM tab AS t
   WHERE NOT EXISTS -- last order in chain
    (
      SELECT * 
      FROM tab AS t2
      WHERE t.Order_id = t2.previous_order_id
    )

   UNION ALL

   SELECT t.*, cte.baseOrder_id
   FROM tab AS t
   JOIN cte 
     ON t.Order_id = cte.previous_order_id 
   WHERE cte.ordertype_opprotunity <> 'new order' -- stop when the previous recursion was a "new order"
 )
SELECT * FROM cte
WHERE ordertype_opprotunity = 'new order' -- only return the "new order" type

【讨论】:

  • 感谢dnoeth的解决方案和详细解释。
  • 确保接受答案作为解决方案,@OmprakashRathi
猜你喜欢
  • 2021-09-16
  • 1970-01-01
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
  • 1970-01-01
  • 2019-06-08
  • 2012-04-18
  • 2020-09-05
相关资源
最近更新 更多