使用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
一个澄清:当我使用不在CTE
内的带有PARTITION BY \ ORDER BY部件的Windows函数运行语句时,它运行良好。
工作代码示例:
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;
答案 0 :(得分:-1)
您应该告诉我们您使用哪个数据库。如果您使用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;