我需要创建两列Flag1和Flag2,这两列包含基于范围条件的计数:
如果PostCode在000-500范围内,则Flag1elseFlag2。
原始数据
RowdID | PostCode |
---|---|
1 | 301AD、478GH、921SS、810RT、019FE |
2 | 296KS,035LC,592MW |
在这里做一些假设:
- 邮政编码列不包含特殊字符。如果是,则调整regexp_replace表达式
- 你只关心带数字的邮政编码值
- 您没有nnnAAAnn格式的邮政编码(如012ABC24(。如果您这样做了,那么使用的子字符串是(split to table,1,3(,而不是regexp_replace函数
此外,我正在postgres中写这篇文章。您没有指定dbms,因此根据需要进行调整。
查询的这一部分采用您的宽表,并生成一个高";表";。
select id,
cast(regexp_replace(regexp_split_to_table(postcode, ','), '[[:alpha:]]', '','g') as integer) as postcode_digits
from table1
部分查询:
regexp_split_to_table --> creates a tall table of your comma separated data in the postcode column.
regexp_replace(tall table, '[[:alpha:]]', '','g' ) --> this replaces letters with nothing, so that we're keeping only the numbers.
cast(inner output) to integer --> so 456 is 456 as integer, and 012 becomes 12.
看起来像什么:
id | postcode_digits |
---|---|
1 | 301 |
1 | 478 |
1 | 921 |
1 | 810 |
1 | 19 |
26 | |
2 | 35 |
2 | 592 |