我有一个由2列组成的表:id和month_year
id month_year
1 Dec 2016
2 Jan 2017
3 Feb 2017
4 Mar 2017
.
...
.......
我需要一个包含日期格式的结果,如下所示
id month_year
1 2016-12-01
2 2017-01-01
3 2017-02-01
4 2017-03-01
..
....
......
(We can assume the date to be 1st)
我可以通过硬编码来实现它
SELECT id , case when a.month_year = 'Dec 2016' THEN
STR_TO_DATE('01/12/2016','%d/%m/%Y')
when a.month_year = 'Jan 2017' THEN
STR_TO_DATE('01/1/2017','%d/%m/%Y')
when a.month_year = 'Feb 2017' THEN
STR_TO_DATE('01/2/2017','%d/%m/%Y')
when a.month_year = 'Mar 2017' THEN
STR_TO_DATE('01/3/2017','%d/%m/%Y')
end as month_year from [table] a
但是当新数据到来时,我想要没有哈希它 这个查询不会工作......我可以继续进一步吗?
答案 0 :(得分:0)
E.g:
SELECT STR_TO_DATE(CONCAT('Dec 2016','01'),'%b %Y %d');
+-------------------------------------------------+
| STR_TO_DATE(CONCAT('Dec 2016','01'),'%b %Y %d') |
+-------------------------------------------------+
| 2016-12-01 |
+-------------------------------------------------+
答案 1 :(得分:0)
SELECT DATE_FORMAT(STR_TO_DATE('Dec 2017','%M %Y'), '01/%m/%Y');
输出:01/12/2017