![](/img/trans.png)
[英]Oracle SQL: Extracting the week of the year from date gives random results
[英]Extracting a year from a string in a column in Oracle SQL
我有一個名為 SALE_PERIOD 的列,它存儲了一個與產品銷售時間和地點相關的字符串。 該列使用以下約定填充:
例如,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.