[英]Extracting a year from a string in a column in Oracle SQL
I have a column titled SALE_PERIOD, which stores a string relating to when and where a product is sold.我有一个名为 SALE_PERIOD 的列,它存储了一个与产品销售时间和地点相关的字符串。 The column is filled using the following conventions:
该列使用以下约定填充:
For example, a product sold in JAN 2018 at store number 5 would be stored as "JA20185"例如,2018 年 1 月在 5 号商店销售的产品将存储为“JA20185”
I need a query which will extract the year the sale was made from this column and allow me to write it into a new column in the following way:我需要一个查询,该查询将从该列中提取销售年份,并允许我通过以下方式将其写入新列:
SELECT SALE_PERIOD, (The code used to solve the problem) AS SALE_YEAR
FROM My_Table
I am aware the final code may need to look slightly different and any alternative solutions are also greatly appreciated.我知道最终代码可能需要看起来略有不同,也非常感谢任何替代解决方案。
Use SUBSTR
to get the 4-character year substring starting from the 3rd character and then convert it to a number:使用
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;
outputs:输出:
\nSALE_PERIOD |SALE_PERIOD | SALE_YEAR |
SALE_YEAR | SALE_MONTH |
销售_MONTH | SALE_STORE
SALE_STORE\n:---------- |
:---------- | --------: |
--------: | :--------- |
:--------- | ---------:
---------:\nJA20185 |
JA20185 | 2018 |
2018 | JA |
JA | 5
5\nDE2019123 |
DE2019123 | 2019 |
2019 | DE |
德 | 123
123\n
Since the SALE_PERIOD
column has a well specified format for the sub-strings you could also add virtual columns to the table:由于
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
)
then:然后:
SELECT * FROM my_table;
gives the same output as above with those additional virtual columns.使用这些额外的虚拟列提供与上面相同的输出。
You can split through [^[:digit:]]
posix pattern by using regexp_substr()
and regexp_replace()
functions' combination :您可以通过使用
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.