我有一个表,用eff_dte = WK_BCC_DATES查找一行。 WK_BCC_DATES是在PL1程序中计算的变量,现在我需要在一个查询中完成此计算,因此QMF将进行计算。计算是WK_BCC_DATES = DTE1 + NO_DAYS。
SELECT SUBSTR(PARM_VALUE,1,10)
FROM BCD75DBA.BCCA6000 T60
WHERE T60.COUNTRY_CODE = '896'
AND T60.SUBSIDIARY_CODE = '01'
AND T60.PARM_NAME = 'BCC_DATES'
AND T60.EFF_DTE = (SELECT MAX(T60A.EFF_DTE)
FROM BCD75DBA.BCCA6000 T60A
WHERE T60A.COUNTRY_CODE = '896'
AND T60A.SUBSIDIARY_CODE = '01'
AND T60A.PARM_NAME = 'BCC_DATES')`
和
SELECT SUBSTR(PARM_VALUE,1,3)
FROM BCD75DBA.BCCA6000 T60
WHERE T60.COUNTRY_CODE = '896'
AND T60.SUBSIDIARY_CODE = '01'
AND T60.PARM_NAME = 'BCC_DAYS'
AND T60.EFF_DTE = (SELECT MAX(T60A.EFF_DTE)
FROM BCD75DBA.BCCA6000 T60A
WHERE T60A.COUNTRY_CODE = '896'
AND T60A.SUBSIDIARY_CODE = '01'
AND T60A.PARM_NAME = 'BCC_DAYS')`
我尝试将第一个查询AS DTE1分组,然后将第二个AS NO_DAYS分组,但我收到错误“在使用的上下文中无效”。
请告知我还能做些什么。我正在使用DB2 v9。感谢。
答案 0 :(得分:0)
那么,您想要结合这些查询吗?这实际上非常简单。没有你的综合查询,有点难以分辨出导致错误的原因,但你可能已经把别名放在了原位。
(为了将来参考,您的表格似乎是EAV的一些 - 实体属性值。将其用作未来查询的搜索词)
我认为轻微的重写会帮助你解决这个问题:
WITH Most_Recent_Rows AS (SELECT parm_name, parm_value,
ROW_NUMBER() OVER(PARTITION BY parm_name
ORDER BY eff_dte DESC) AS rn
FROM BCD75DBA.BCCA6000
WHERE country_code = '896'
AND subsidiary_code = '01'
AND parm_name IN ('BCC_DAYS', 'BCC_DATES'))
SELECT CAST(SUBSTR(bcc_dates.parm_value, 1, 10) AS DATE) +
CAST(SUBSTR(bcc_days.parm_value, 1, 3) AS INTEGER) DAYS
FROM Most_Recent_Rows bcc_days
JOIN Most_Recent_Rows bcc_dates
ON bcc_dates.parm_name = 'BCC_DATES'
AND bcc_dates.rn = 1
WHERE bcc_days.parm_name = 'BCC_DAYS'
AND bcc_days.rn = 1
顺便说一句,我想你正在尝试以下内容:
SELECT bcc_days, bcc_dates
FROM (SELECT SUBSTR(rw.parm_value, 1, 3) AS bcc_days
FROM BCD75DBA.BCCA6000 rw
JOIN (SELECT country_code, subsidiary_code, parm_name, MAX(eff_date) AS eff_date
FROM BCD75DBA.BCCA6000
WHERE parm_name = 'BCC_DAYS'
GROUP BY country_code, subsidiary_code, parm_name) ref
ON ref.country_code = rw.country_code
AND ref.subsidiary_code = rw.subsidiary_code
AND ref.parm_name = rw.parm_name
AND ref.eff_date = rw.eff_date) bcc_days
CROSS JOIN (SELECT SUBSTR(rw.parm_value, 1, 10) AS bcc_dates
FROM BCD75DBA.BCCA6000 rw
JOIN (SELECT country_code, subsidiary_code, parm_name, MAX(eff_date) AS eff_date
FROM BCD75DBA.BCCA6000
WHERE parm_name = 'BCC_DATES'
GROUP BY country_code, subsidiary_code, parm_name) ref
ON ref.country_code = rw.country_code
AND ref.subsidiary_code = rw.subsidiary_code
AND ref.parm_name = rw.parm_name
AND ref.eff_date = rw.eff_date) bcc_dates
由于子子查询中的重复,这不太理想。这可以与答案的前一部分结合使用(使用CTE表示GROUP BY
,然后连接两次)。我不确定哪种方法会产生更好的性能。
由于缺少样本数据和预期结果,以及我目前没有实例的事实,这两个查询都没有经过测试。