1

MATCH_RECOGNIZE在带有几个 CTE 的查询中使用函数。当我运行查询时,出现以下错误:

SQL 编译错误:此上下文不支持 MATCH_RECOGNIZE。

在我的查询中,在 MATCH_RECOGNIZE 之前和之后有几个 CTE,如下所示。

WITH cte1 AS (
SELECT *
FROM dataset
WHERE ID IS NOT NULL AND STATUS IS NOT NULL ),

cte2 AS (
SELECT *
FROM cte1
QUALIFY FIRST_VALUE(STATUS) OVER (PARTITION BY ID ORDER BY CREATED_AT) = 'created' )

mr as (
SELECT *
    FROM cte2
    MATCH_RECOGNIZE (
      PARTITION BY ID
      ORDER BY CREATED_AT
      MEASURES MATCH_NUMBER() AS mn,
               MATCH_SEQUENCE_NUMBER AS msn
      ALL ROWS PER MATCH
      PATTERN (c+m+)
      DEFINE
         c AS status='created'
        ,m AS status='missing_info'
        ,p AS status='pending'
    ) m1
    QUALIFY (ROW_NUMBER() OVER(PARTITION BY mn, ID ORDER BY msn) = 1)
          OR(ROW_NUMBER() OVER(PARTITION BY mn, ID ORDER BY msn DESC)=1)
    ORDER BY ID, CREATED_AT ),

cte3 as (
SELECT *
FROM mr
-- some other operations
)

解决这个问题的理想方法是什么?例如,创建常规视图、物化视图或临时表等。我尝试创建视图但出现错误,不确定是否支持。我如何使用MATCH_RECOGNIZE其他后续 CTE 中的结果?

当我添加以下内容时,会出现此错误:

位置 0 处的语法错误行 xx 意外“创建”。

create view filtered_idents AS

SELECT *
FROM cte2
MATCH_RECOGNIZE (

)
4

2 回答 2

4

这似乎是一个未记录的限制(我要求我们很棒的文档团队解决这个问题)。

同时,我可以建议将过程划分为使用match_recognize结果的步骤。

重现错误:

with data as (
    select $1 company, $2 price_date, $3 price
    from values('a',1,10), ('a',2,15)
), cte as (

    select *
    from data match_recognize(
        partition by company
        order by price_date
        measures match_number() as "MATCH_NUMBER"
        all rows per match omit empty matches
        pattern(overavg*)
        define
            overavg as price > avg(price) over (rows between unbounded
                                      preceding and unbounded following)
    )
) 
select * from cte

-- 002362 (0A000): SQL compilation error: MATCH_RECOGNIZE not supported in this context.

2步解决方案:

with data as (
    select $1 company, $2 price_date, $3 price
    from values('a',1,10), ('a',2,15)
)

select *
from data match_recognize(
    partition by company
    order by price_date
    measures match_number() as "MATCH_NUMBER"
    all rows per match omit empty matches
    pattern(overavg*)
    define
        overavg as price > avg(price) over (rows between unbounded
                                  preceding and unbounded following)
)
;


with previous_results as (
    select *
    from table(result_scan(last_query_id()))
)

select * 
from previous_results
;
于 2021-07-27T18:49:14.923 回答
0

基米,试试我得到的你的片段:

SQL 编译错误:位置 0 的第 11 行语法错误意外'mr'。位置 6 处的第 17 行语法错误意外的“MEASURES”。

第 9 行似乎缺少一个终止逗号。当我添加一个然后用一个简单的 select 语句完成整个过程时,我不会再遇到语法错误,我只会遇到名称查找错误(当然是预期的)。

于 2021-08-14T08:28:50.567 回答