具有多个 WITH AS 案例的 DB2 查询未编译
Posted
技术标签:
【中文标题】具有多个 WITH AS 案例的 DB2 查询未编译【英文标题】:DB2 query with multiple WITH AS cases not compiling 【发布时间】:2019-10-04 17:07:42 【问题描述】:由于某种原因,我无法执行此查询,因为我遇到了错误:
Token ( was not valid. Valid tokens: , FROM INTO.
我在 DB2 中运行它,我认为这发生在第二个 with/as
的第一行 ) , A AS ( SELECT
我哪里错了?
WITH
RES (PRODUCT_ID, JOB_STATUS, JOB_STATUS_TIME) AS
(
select
T1.NAME,
t2.PRODUCT_id as PRODUCT_ID,
t3.product_id,
t3.created_at,
t5.name as JOB_STATUS,
t4.row_created_timestamp as JOB_STATUS_TIME ,
t3.expiration_timestamp
from schema.PRODUCT T1
inner join schema.PRODUCT_to_product T2
on t1.PRODUCT_id = t2.PRODUCT_id
inner join schema.product t3
on t2.product_id = t3.product_id
inner join schema.product_to_job_statust t4
on t3.product_id = t4.product_id
inner join schema.job_statust t5
on t4.job_statust_id = t5.job_statust_id
where t3.job_typet_id = 2
and t3.created_at >= '2019-09-20'
and t5.name <> 'D'
order by t1.name,t3.product_id
)
, A AS
(
SELECT
PRODUCT_ID, JOB_STATUS
, JOB_STATUS_TIME
, LEAD (JOB_STATUS_TIME) OVER (PARTITION BY PRODUCT_ID ORDER BY JOB_STATUS_TIME) AS JOB_STATUS_TIME_NEXT
FROM RES
)
SELECT
PRODUCT_ID
, COUNT(CASE JOB_STATUS WHEN 'O' THEN 1 END) AS CREATED
, COUNT(CASE JOB_STATUS WHEN 'C' THEN 1 END) AS COMPLETED
, COUNT(CASE JOB_STATUS WHEN 'X' THEN 1 END) AS CANCELLED
, SUM
(
CASE JOB_STATUS WHEN 'P' THEN
(DAYS(JOB_STATUS_TIME_NEXT) - DAYS(JOB_STATUS_TIME)) * 86400
+ MIDNIGHT_SECONDS(JOB_STATUS_TIME_NEXT) - MIDNIGHT_SECONDS(JOB_STATUS_TIME)
END
) / 60 AS ACTIVE_MINUTES
FROM A
GROUP BY PRODUCT_ID;
【问题讨论】:
删除order by
。它不属于 CTE(或子查询)。我不知道 DB2 是否会检查,但它也可能是错误的原因。
我确实在您提出的那个主体上删除了它,但不幸的是它没有解决这个问题
您的RES
字段列表与其SELECT
语句不匹配,并且您的A
查询根本没有字段列表...
其实除非运行递归CTE,否则不需要字段列表。
因此,即使将字段列表添加到 A
或从 RES
中删除,我也会遇到相同的错误。这也在 IBM iSeries 版本 7 上
【参考方案1】:
使用支持您正在使用的 Db2 版本的 SQL 编辑器总是一个好主意。
在验证设置为DB2 for i 7.2
的 IBM Data Studio 中查看您的 SQL,以红色下划线突出显示以下行
, LEAD (JOB_STATUS_TIME) OVER (PARTITION BY PRODUCT_ID ORDER BY JOB_STATUS_TIME) AS JOB_STATUS_TIME_NEXT`
交叉引用手册,我可以看到LEAD
在 Db2 for i 7.3 中支持,但在 Db2 for i 7.2 中不支持
https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_74/db2/rbafzolapexp.htm
所以我猜你的语法错误
【讨论】:
以上是关于具有多个 WITH AS 案例的 DB2 查询未编译的主要内容,如果未能解决你的问题,请参考以下文章
如何在一个 PostgreSQL 查询中使用多个 WITH 语句?
参数筛选查询——多表求交集(INTERSECT)+WITH AS