简体   繁体   English

presto SQL - 如果日期列格式与 yyyy-MM-dd 不匹配,则过滤记录

[英]presto SQL - Filter records if date column format is not matching yyyy-MM-dd

I need to get all the records from a table that has a date not matching with the format yyyy-MM-dd.我需要从日期与格式 yyyy-MM-dd 不匹配的表中获取所有记录。

Here, column ID is unique bigint column.在这里,列 ID 是唯一的 bigint 列。 start_date is of varchar datatype. start_date 是 varchar 数据类型。

Sample input:样本输入:

在此处输入图像描述

Expected output:预期 output:

在此处输入图像描述

Thanks谢谢

Use regexp_like:使用 regexp_like:

select id, start_date
  from mytable
 where NOT regexp_like(start_date, '\d{4}-\d{2}-\d{2}')

This will work for '11-12-200' and 'None'.这适用于“11-12-200”和“无”。

If you want to include NULL values as well, add additional condition:如果您还想包含 NULL 值,请添加附加条件:

 where (NOT regexp_like(start_date, '\d{4}-\d{2}-\d{2}'))
    OR start_date is null

More strict date regexp is '^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$'更严格的日期正则表达式是'^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$'

This will restrict month to 01 .. 12 and day to 01 .. 31 and will not allow other characters before and after date( ^ and $ anchors are used).这会将月份限制为01 .. 12并将日期限制为01 .. 31 ,并且不允许在日期之前和之后的其他字符(使用^$锚点)。

One more simple and powerful method一种更简单而强大的方法

is to use try_cast(col as date) - it will return NULL if not possible to cast:是使用try_cast(col as date) - 如果无法投射,它将返回 NULL:

where try_cast(start_date as date) is not null

This will also restrict wrong dates like Feb 30 (2000-02-30)这也将限制错误的日期,例如 2 月 30 日 (2000-02-30)

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

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