繁体   English   中英

从 Oracle SQL 中的列中的字符串中提取年份

[英]Extracting a year from a string in a column in Oracle SQL

我有一个名为 SALE_PERIOD 的列,它存储了一个与产品销售时间和地点相关的字符串。 该列使用以下约定填充:

  1. 两个字母,代表进行销售的月份
  2. 销售年份
  3. 发生销售的商店编号

例如,2018 年 1 月在 5 号商店销售的产品将存储为“JA20185”

我需要一个查询,该查询将从该列中提取销售年份,并允许我通过以下方式将其写入新列:

SELECT SALE_PERIOD, (The code used to solve the problem) AS SALE_YEAR
FROM My_Table

我知道最终代码可能需要看起来略有不同,也非常感谢任何替代解决方案。

使用SUBSTR获取从第 3 个字符开始的 4 个字符的年份子字符串,然后将其转换为数字:

SELECT sale_period,
       TO_NUMBER( SUBSTR( sale_period, 3, 4 ) ) AS sale_year,
       -- and for the other components:
       SUBSTR( sale_period, 1, 2 ) AS sale_month,
       TO_NUMBER( SUBSTR( sale_period, 7 ) ) AS sale_store
FROM   my_table;

输出:

\n SALE_PERIOD |  SALE_YEAR | 销售_MONTH |  SALE_STORE\n :---------- |  --------: |  :--------- |  ---------:\n JA20185 |  2018 |  JA |  5\n DE2019123 |  2019 | 德 |  123\n

由于SALE_PERIOD列具有明确指定的子字符串格式,因此您还可以向表中添加虚拟列:

ALTER TABLE my_table ADD (
  sale_year  NUMBER(4,0) GENERATED ALWAYS AS ( TO_NUMBER( SUBSTR( sale_period, 3, 4 ) ) ) VIRTUAL,
  sale_month CHAR(2)     GENERATED ALWAYS AS ( CAST( SUBSTR( sale_period, 1, 2 ) AS CHAR(2) ) ) VIRTUAL,
  sale_store NUMBER(5,0) GENERATED ALWAYS AS ( TO_NUMBER( SUBSTR( sale_period, 7 ) ) ) VIRTUAL
)

然后:

SELECT * FROM my_table;

使用这些额外的虚拟列提供与上面相同的输出。

db<> 在这里摆弄

您可以通过使用regexp_substr()regexp_replace()函数的组合来拆分[^[:digit:]] posix 模式:

with my_table( sale_period ) as
(
 select 'a product sold in JAN 2018 at store number 5' from dual
)
select substr(substr(trim(regexp_substr(sale_period,'[^[:digit:]]+')),-3),1,2) 
       ||regexp_replace(sale_period,'[^[:digit:]]') as sale_year
  from my_table

演示

暂无
暂无

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

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