H2数据库:在CTE内使用窗口函数时出错

问题描述 投票:0回答:2

使用H2数据库(版本1.4.200)我在使用内部窗口函数时遇到了非常奇怪的错误

CTE
。当我将窗口函数字段包含到
CTE
并且
OVER()
子句为空时,它可以正常工作,但是当我尝试在
ORDER BY/PARTITION BY
子句中添加
OVER()
时,我遇到以下错误:
'[42000][42000] Syntax error in SQL statement "WITH statement supports only SELECT, TABLE, VALUES, CREATE TABLE, INSERT, UPDATE, MERGE or DELETE statements" '
非工作代码示例:

WITH cte AS( 
  SELECT ROW_NUMBER() OVER (PARTITION BY CUST_NAME ORDER BY ORDER_DATE) AS rn 
  FROM TEST.HOLDING
)    
SELECT * 
FROM cte

一个澄清:当我使用 Windows 函数运行语句时,PARTITION BY\ORDER BY 部分不在

CTE
内,效果很好。 工作代码示例:

SELECT ROW_NUMBER() OVER (PARTITION BY CUST_NAME ORDER BY ORDER_DATE) AS rn 
FROM TEST.HOLDING

问题的测试用例:

CREATE TABLE PUBLIC.HOLDING(
CUST_NAME VARCHAR(50),
ORDER_DATE DATE
);

INSERT INTO PUBLIC.HOLDING(CUST_NAME, ORDER_DATE)
VALUES('Customer1',TO_DATE('20200201','YYYYMMDD')),
      ('Customer1',TO_DATE('20200202','YYYYMMDD')),
      ('Customer2',TO_DATE('20200201','YYYYMMDD')),
      ('Customer2',TO_DATE('20200202','YYYYMMDD'));

WITH cte AS(
SELECT CUST_NAME,
       ORDER_DATE,
       ROW_NUMBER() OVER (PARTITION BY CUST_NAME ORDER BY ORDER_DATE) AS rn
FROM PUBLIC.HOLDING
)

SELECT *
FROM cte;

SELECT CUST_NAME,
       ORDER_DATE,
       ROW_NUMBER() OVER (PARTITION BY CUST_NAME ORDER BY ORDER_DATE) AS rn
FROM PUBLIC.HOLDING;
sql h2 common-table-expression window-functions
2个回答
0
投票

如果您想使用像 Partition By/Order By 这样的窗口函数,请使用 #temp 表而不是 CTE。


-2
投票

你应该告诉我们你使用的是哪个数据库。如果你使用sql server,请检查你的代码,我在'with'前面加,是否没有';'。

;WITH cte AS( 
  SELECT ROW_NUMBER() OVER (PARTITION BY CUST_NAME ORDER BY ORDER_DATE) AS rn 
  FROM TEST.HOLDING
)    
SELECT * 
FROM cte;
© www.soinside.com 2019 - 2024. All rights reserved.