检索Redshift SQL中varchar列的数值范围输出

时间:2019-06-06 11:35:58

标签: sql amazon-redshift

我正在尝试从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

仅供参考。.仅最后两行抛出错误,这是此代码中的必要

2 个答案:

答案 0 :(得分:0)

仅使用字符串比较怎么样?

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的db <>小提琴。

答案 1 :(得分:0)

与您的方法非常相似的方法,但有一些调整。我使用CTE根据您共享的示例输入来创建mf1.tb1

WITH source AS (
SELECT 'A1X98090900900' AS sid_id
UNION ALL
SELECT '09446115981633'
UNION ALL
SELECT '09446115980104'
UNION ALL
SELECT '0944611597998A'
),
tid AS (
SELECT CASE WHEN sid_id similar to '[0-9]*' THEN sid_id::bigint END AS sid
FROM source
WHERE sid IS NOT NULL
)
SELECT sid FROM tid
WHERE sid BETWEEN 9445897133440 and 9445907133438
OR sid BETWEEN 9446098650000 and 9446198649999;