【问题标题】:Retrieve numeric range output from varchar column in redshift sql从redshift sql中的varchar列检索数字范围输出
【发布时间】:2019-06-06 11:35:58
【问题描述】:

我正在尝试从 varchar 列中检索数值范围,但无法执行

sid_id 列是 varchar,具有数字和字母数字值,例如

09446115979980
09446115980104
09446115981633
A1X98090900900

但是,我希望只提取特定范围内的数值

已经试过了

sid_id as bigint

错误:XX000:无效数字,值“D”,位置 14,类型:长

sid_id as numeric

错误:XX000:无效数字,值“D”,位置 14,类型:十进制

sid_id as varchar: 给出空白输出

The code used is  

with tid as
(
select cast(sid_id as bigint) sid
from mf1.tb1 s                     
where 
right(sid_id,13) similar to '[0-9]{13}'
and left(sid_id,4)= '0944'
)
select tid.sid from tid
where tid.sid between 9445897133440 and 9445907133438
or tid.sid between 9446098650000 and 9446198649999

仅供参考..只有最后两行抛出错误,这是这段代码的必要性

【问题讨论】:

  • 编辑您的问题并提供示例数据和所需结果。
  • 用示例数据更新,最后两行代码中提到了所需的范围

标签: sql amazon-redshift


【解决方案1】:

只使用字符串比较怎么样:

select s.sid
from mf1.tb1 s
where s.sid ~ '^[0-9]*$' and
      (s.sid between '09445897133440' and '09445907133438' or
       s.sid between '09446098650000' and '09446198649999'
      )

有趣的是,这不适用于 similar to,但它适用于 ~

这与您的逻辑并非 100% 相同,但它可能对您拥有的数据执行您想要的操作。

Here 是一个使用 Postgres 的数据库小提琴。

【讨论】:

  • 嘿,戈登,感谢您的帮助,但是这给出了 NULL 输出
  • @SumitJain 。 . .使用 similar to 不起作用,但使用 ~ (在 Postgres 中)确实有效。它也应该在 Redshift 中工作。
猜你喜欢
  • 2022-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多