简体   繁体   English

在DB2中以YYYYMM格式格式化日期

[英]Formatting date in YYYYMM format in DB2

I am getting a date as a String from a table below in the format: 我从下面的表格中以字符串形式获取日期:

2014-09-02 

which is YYYY-MM-DD format. 这是YYYY-MM-DD格式。

The query is: 查询是:

SELECT VALUE FROM MYSCHEMA.MYTABLE WHERE CODE = 'MYDATE'

I want to modify above query so that the result is: 我想修改上面的查询,以便结果是:

201402

I tried this, but not getting in correct format: 我试过了,但是格式不正确:

select char(year(date(value))) || char(month(date(value))) from MYSCHEMA.MYTABLE WHERE CODE = 'MYDATE'

The result is coming as: 结果是:

 1            
------------ 
2014       9 

I have db2 9.5 with me. 我有db2 9.5。

If you're actually getting a DATE data type (and even if you're not, in the ISO format you have there, DB2 should be smart enough to convert it automatically), then you can use the VARCHAR_FORMAT scalar function: 如果您实际上获取的是DATE数据类型(即使您没有, VARCHAR_FORMAT您拥有的ISO格式,DB2应该足够聪明以自动转换它),那么您可以使用VARCHAR_FORMAT标量函数:

SELECT VARCHAR_FORMAT(VALUE, 'YYYYMM')
FROM MYSCHEMA.MYTABLE
WHERE CODE = 'MYDATE'

If all your strings are going to be in the exact same format, why not just remove the dashes with REPLACE() and then grab a substring, like so: 如果您所有的字符串都将使用完全相同的格式,为什么不直接使用REPLACE()删除破折号,然后抓取一个子字符串,如下所示:

SELECT SUBSTR(REPLACE(VALUE,'-',''),1,6) FROM MYSCHEMA.MYTABLE WHERE CODE='MY DATE'

Also, as Dan said, in your example you only selected the year and day, but I'm assuming from your code that you want the year and month. 而且,正如Dan所说,在您的示例中,您仅选择了年和日,但是我从您的代码中假设您需要年和月。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM