如何使用函数extract()在YYYY-MM上设置日期



只有当月份结束时,我才会尝试使用all值。我暂时这么做了:

select
extract(month from mois_entre ) as mois_finis 
from   table1
where  extract(year from mois_entre ) = extract(year from CURRENT_DATE()) and
extract(month from mois_entre ) < extract(month from CURRENT_DATE()) or extract(year from mois_entre ) < extract(year from CURRENT_DATE()) 
and to_char(mois_entre , 'yyyy/mm/dd') between  '2021/01/01'  and '2021/07/16' 

它运行得很好,但我的问题是我的结果是这样的:

mois_finis
1
2
3
4
5
6

所以"1〃;表示一月,2表示"一月";二月";等等。我没有7号,因为七月还没有结束。

但现在我的目标是拥有:

mois_finis
january-2021
February-2021
...
...
June-2021

或具有

01-2021  or 2021-01
..
...
..
06-2021  or 2021-06

提前感谢!

您可以使用TO_VARCHAR提取日期的某些部分,而不是使用extract:

with table1 as (
select '2021-01-01'::date mois_entre )
select
TO_VARCHAR(mois_entre,'MM-YYYY' ) as mois_finis,
TO_VARCHAR(mois_entre,'MMMM-YYYY' ) as mois_finis_alternative
from   table1
where  extract(year from mois_entre ) = extract(year from CURRENT_DATE()) and
extract(month from mois_entre ) < extract(month from CURRENT_DATE()) or extract(year from mois_entre ) < extract(year from CURRENT_DATE()) 
and to_char(mois_entre , 'yyyy/mm/dd') between  '2021/01/01'  and '2021/07/16' ;

+------------+------------------------+
| MOIS_FINIS | MOIS_FINIS_ALTERNATIVE |
+------------+------------------------+
| 01-2021    | January-2021           |
+------------+------------------------+

也可以提取年份和月份并将其合并,但这将是额外的努力:

with table1 as (
select '2021-01-01'::date mois_entre )
select
extract(year from mois_entre ) || '-' || ltrim(to_varchar(extract(month from mois_entre ), '00' )) as mois_finis
from   table1
where  extract(year from mois_entre ) = extract(year from CURRENT_DATE()) and
extract(month from mois_entre ) < extract(month from CURRENT_DATE()) or extract(year from mois_entre ) < extract(year from CURRENT_DATE()) 
and to_char(mois_entre , 'yyyy/mm/dd') between  '2021/01/01'  and '2021/07/16' ;

相关内容

  • 没有找到相关文章