我遇到一个查询问题,如果使用硬编码日期运行,会在表格中插入正确的行数(170K +)。问题是,当我尝试自动化它时,通过用日期函数替换硬编码日期,查询将只在一个新截断的表中插入一行。
硬编码日期示例:' 20150401'
同一日期的样本,使用日期函数:
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
);
我做了很多测试和研究,但我还没有找到可能的原因,为什么返回的记录数量会有如此大的差异。
谢谢,
贾斯汀
答案 0 :(得分:0)
我认为这是因为您在last_day
函数产生的字符串中添加了1。检查括号:
WHERE 'Conditions for A, B, C, D, and E are met'
AND B.DATE = TO_CHAR(last_day(add_months(now(), -3)+1)
如果不是那样(或者你真的想在字符串中添加1),那么我将走出困境并假设B.DATE
是date
类型的列。 1}}。如果是这样,它没有正确比较的原因是因为你依赖于隐式转换。更改日期过滤器以显式转换双方。
WHERE 'Conditions for A, B, C, D, and E are met'
AND B.DATE::date = (last_day(add_months(now(), -3)+1)::date