有没有办法在Redshift中从字符串中提取所有日期?

时间:2019-06-06 19:19:00

标签: sql amazon-redshift

对于给定的字符串,是否可以计算(并提取)其中有多少个日期?例如,字符串可能看起来像(2019-06-01, 2019-06-02, 2019-06-03)(This is the first date: 2019-06-01; This is the second date: 2019-06-02)或其他形式。在第一个示例中,它应该返回3。在第二个示例文本中,它应该返回2。

我不确定从哪里开始。在Redshift / PostgreSQL中有可能吗?

任何指导将不胜感激。预先感谢!

1 个答案:

答案 0 :(得分:2)

这应该有效

select regexp_count(str_field, '[0-9]{4}-[0-9]{2}-[0-9]{2}') from your table

为了测试我已经使用了这个

with test_data as (
select '2019-06-01, 2019-06-02, 2019-06-03' str_field union all
select 'This is the first date: 2019-06-01; This is the second date: 2019-06-02'
)
select regexp_count(str_field, '[0-9]{4}-[0-9]{2}-[0-9]{2}') date_count from test_data

结果是

date_count
3
2

对于提取,您可以使用以下sql,您可能要根据最大日期数添加更多行

with test_data as (select '2019-06-01, 2019-06-02, 2019-06-03' str_field union all
select 'This is the first date: 2019-06-01; This is the second date: 2019-06-02'
)
select regexp_substr(str_field, '[0-9]{4}-[0-9]{2}-[0-9]{2}',1,1) date1,
       regexp_substr(str_field, '[0-9]{4}-[0-9]{2}-[0-9]{2}',1,2) date2,
       regexp_substr(str_field, '[0-9]{4}-[0-9]{2}-[0-9]{2}',1,3) date3
  from test_data

结果:

date1       date2       date3
2019-06-01  2019-06-02  2019-06-03
2019-06-01  2019-06-02