■ はじめに
https://dk521123.hatenablog.com/entry/2021/08/21/000000
の続き。 今回は、split_part について、扱う。
目次
【1】split_part 【2】構文 【3】サンプル 例1:Hello world 例2:S3パスのパース 例3:Emailのパース
【1】split_part
* 指定した区切り文字「delimiter」で分割する
【2】構文
* PostgreSQL だけでなく、Redshift も使えるので記録しておく
PostgreSQL
https://www.postgresql.jp/docs/9.2/functions-string.html
-- stringをdelimiterで分割し、 -- その結果から指定したフィールドを返します。 -- ★注意★ field ... 1から始まる(0発進じゃない) split_part(string text, delimiter text, field int)
Redshift
https://docs.aws.amazon.com/ja_jp/redshift/latest/dg/SPLIT_PART.html
-- 指定された区切り記号で文字列を分割し、 -- 指定された位置にあるパートを返します SPLIT_PART(string, delimiter, part)
【3】サンプル
* 試すDBがなければ、以下のサイトで行うといいかも、、、 * PostgreSQL15を想定
SQL Fiddle
https://www.db-fiddle.com/
例1:Hello world
SELECT 'hello@world@!!' AS v, SPLIT_PART('hello@@world@@!!', '@@', 1) AS v1, SPLIT_PART('hello@@world@@!!', '@@', 2) AS v2 , SPLIT_PART('hello@@world@@!!', '@@', 3) AS v3 ;
出力結果
"v","v1","v2","v3" "hello@world@!!","hello","world","!!"
例2:S3パスのパース
select 's3://your-buket/custom/2024/10/30/sample.csv' AS v, SPLIT_PART('s3://your-buket/custom/2024/10/30/sample.csv', '/', -4) AS year, -- 2024 SPLIT_PART('s3://your-buket/custom/2024/10/30/sample.csv', '/', -3) AS month, -- 10 SPLIT_PART('s3://your-buket/custom/2024/10/30/sample.csv', '/', -2) AS day -- 30 ;
例3:Emailのパース
SELECT 'hello123@world.com' AS email, SPLIT_PART('hello123@world.com', '@', 1) AS local_part, SPLIT_PART('hello123@world.com', '@', 2) AS domain_part ;
local_part | domain_part | |
---|---|---|
hello123@world.com | hello123 | world.com |
関連記事
文字列関数 ~ string_agg ~
https://dk521123.hatenablog.com/entry/2021/08/21/000000
Snowflake ~ Partition構成のデータを取り込む ~
https://dk521123.hatenablog.com/entry/2022/10/28/000925