【问题标题】:Recursive CTE cyles in SnowflakeSnowflake 中的递归 CTE 循环
【发布时间】:2021-11-04 02:26:12
【问题描述】:

我发现这个例子可以处理递归 CTE 中的循环: Recursive CTE stop condition for loops

https://dbfiddle.uk/?rdbms=postgres_13&fiddle=dfe8858352afad6411609d157d3fe85e

我想在雪花中做同样的事情,我该怎么做?我试图“移植”这个例子,但我不清楚数组部分应该如何转换为雪花?

【问题讨论】:

    标签: common-table-expression cycle snowflake-sql


    【解决方案1】:

    我有下面,它返回与 Postgres 中的示例相同的结果:

    WITH RECURSIVE paths AS (
      -- For simplicity assume node 1 is the start
      -- we'll have two starting nodes for data = 1 and 2
      SELECT DISTINCT
        src           as node
        , data        as data
        , 0           as depth
        , src::text   as path
        , false       as is_cycle
        , ARRAY_CONSTRUCT(src)  as path_array
      FROM edges
      WHERE src IN ( 1,2)
      UNION ALL
      SELECT 
        edges.dst
        , edges.data
        , depth + 1
        , paths.path || '->' || edges.dst::text
        , ARRAY_CONTAINS(dst::variant, path_array)
        , ARRAY_APPEND(path_array, dst)
      FROM paths
      JOIN edges 
        ON edges.src = paths.node 
        AND edges.data = paths.data
        AND NOT is_cycle
    )
    SELECT * FROM paths;
    

    但是,我必须删除递归部分中的 DISTINCT,因为它在 Snowflake 中是不允许的:

    SQL compilation error: DISTINCT is not allowed in a CTEs recursive term.
    

    【讨论】:

      猜你喜欢
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多