我遇到了一个查询问题,如果使用硬编码的日期运行,它将在表中插入正确的行数(170K+)。问题是,当我尝试将其自动化时,通过用日期函数替换硬编码的日期,查询只会将一行插入到新截断的表中。
硬编码日期示例:'20150401'
同一日期的样本,使用 date 函数:
TO_CHAR(last_day(add_months(now(), -3))+1, 'YYYYMMDD')
上面的 TO_CHAR 函数在单独运行时返回所需的结果。
这是查询的清理版本,导致插入单行:
INSERT INTO SCHEMA.INSERT_TABLE(
SELECT TO_CHAR(now(), 'YYYYMM') TRAN_MONTH,
SUM(CASE WHEN B.DATE = TO_CHAR(last_day(add_months(now(), -3))+1, 'YYYYMMDD')
THEN 'Do stuff'
END) AS Stuff1,
SUM(CASE WHEN B.DATE = TO_CHAR(last_day(add_months(now(), -3))+1, 'YYYYMMDD')
THEN 'Do other stuff'
END) AS Stuff2,
SUM(CASE WHEN B.DATE = TO_CHAR(last_day(add_months(now(), -3))+1, 'YYYYMMDD')
THEN 'Do really weird stuff'
END) AS Stuff3,
SUM(CASE WHEN B.DATE = TO_CHAR(last_day(add_months(now(), -3))+1, 'YYYYMMDD')
THEN 'Do really really weird stuff'
END) AS Stuff4,
SUM(CASE WHEN A.CODE= 1
THEN 'Do ... '
END) AS Stuff5,
FROM
(SELECT Col1, Col2... FROM Table_A) A,
(SELECT Col1, Col2... FROM Table_B) B,
(SELECT Col1, Col2... FROM Table_C) C,
(SELECT Col1, Col2... FROM Table_D) D,
(SELECT Col1, Col2... FROM Table_E) E,
WHERE 'Conditions for A, B, C, D, and E are met'
AND B.DATE = TO_CHAR(last_day(add_months(now(), -3))+1,'YYYYMMDD')
GROUP BY All of the things
ORDER BY Something
);
我已经做了很多测试和研究,但我还没有找到一个可能的原因来解释为什么返回的记录数量会如此巨大的不同。
谢谢,
贾斯汀