Put date conversion in where clause db2 sql

不打扰是莪最后的温柔 提交于 2020-03-25 19:19:22

问题


I have the following query. And I am calculating on MYDATE column which is a DECIMAL(8, 0) data type which stores datea in numeric form in YYYYMMDD format like this 20191107.

SELECT DECIMAL((TO_CHAR(TO_DATE(CAST(CAST(MYDATE AS INT) AS VARCHAR(8)), 'yyyymmdd') - 3 MONTHS, 'yyyymmdd')), 8, 0) FROM PDF_TABLE;

It works fine. However, when I use the above conversion in a WHERE clause like below, query does not return anything.

SELECT * FROM PDF_TABLE WHERE MYDATE = DECIMAL((TO_CHAR(TO_DATE(CAST(CAST(MYDATE AS INT) AS VARCHAR(8)), 'yyyymmdd') - 3 MONTHS, 'yyyymmdd')), 8, 0);

Example

Above is the data as is. Now I pass the date 20200601 as parameter in the WHERE clause of the following query, it should return the following row after subtracting 3 months from 20200601.

SELECT * FROM PDF_TABLE WHERE MYDATE = DECIMAL((TO_CHAR(TO_DATE(CAST(CAST(MYDATE AS INT) AS VARCHAR(8)), 'yyyymmdd') - 3 MONTHS, 'yyyymmdd')), 8, 0);

回答1:


Try this as is:

WITH MYTAB (PDF_VOLUME, MYDATE) AS
(
VALUES
  ('110 GB', DEC(20200101, 8))
, ('120 GB', DEC(20200301, 8))
, ('390 GB', DEC(20200601, 8))
)
SELECT * 
FROM MYTAB
WHERE MYDATE = DEC(TO_CHAR(TO_DATE(CHAR(CAST(? AS DEC(8))), 'YYYYMMDD') - 3 MONTH, 'YYYYMMDD'), 8);



回答2:


How could it possibly return anything?

WHERE MYDATE = DECIMAL((TO_CHAR(TO_DATE(CAST(CAST(MYDATE AS INT) AS VARCHAR(8)), 'yyyymmdd') - 3 MONTHS

Dropping the conversions, you're asking WHERE MYDATE = MYDATE - 3 months

That's never going to be equal... Perhaps you forgot to change the inner MYDATE to CURRENT_DATE or something? That would also require the conversion to change..

Personally, I use a user defined function for this type of conversion; either write it yourself or download Alan Campin's free iDate source

WHERE MYDATE = ConvertToIDate(CCURRENT_DATE - 3 months, '*CCYMD');



来源:https://stackoverflow.com/questions/60143431/put-date-conversion-in-where-clause-db2-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!