SQL 在 DB2 中以 YYYYMM 格式格式化日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26182841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Formatting date in YYYYMM format in DB2
提问by Vicky
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。
回答by bhamby
If you're actuallygetting 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
数据类型(即使您没有获得,在您拥有的 ISO 格式中,DB2 应该足够智能以自动转换它),那么您可以使用VARCHAR_FORMAT
标量函数:
SELECT VARCHAR_FORMAT(VALUE, 'YYYYMM')
FROM MYSCHEMA.MYTABLE
WHERE CODE = 'MYDATE'
回答by Emily Goetz
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.
另外,正如丹所说,在您的示例中,您只选择了年份和日期,但我从您的代码中假设您想要年份和月份。