简体   繁体   中英

Extract substrings from field sql/presto

I have columns in my database that contains values separated by /. I am trying to extract certain values from columns and create new row with them.

Example of data look like below;

user/values2/class/year/subject/18/9/2000291.csv
holiday/booking/type/1092/1921/1.csv
drink/water/juice/1/232/89.json
drink/water1/soft/90091/2/89.csv
car/type/1/001/1.json
game/mmo/1/2/3.json

I want to extract the last 3 numbers from the data eg, from

user/values2/class/year/subject/18/9/2000291.csv

I want

x = 18
y = 9
z = 200291

and display these are new field in the table.

I have been researching and playing around with presto queries but couldn't figure out how I can achieve what I want. I wrote the query below but can't get it to work.

SELECT origin
         split_part(origin, '.' & '/', 1) as z,
         split_part(origin, '.' & '/', 2) as y,
         split_part(origin, '.' & '/', 3) as x,
FROM "data_customer";

EDITED

Current table

在此处输入图片说明

Desired outcome

在此处输入图片说明

Presto code:

with your_data as(
select * from (values
'user/values2/class/year/subject/18/9/2000291.csv',
'holiday/booking/type/1092/1921/1.csv',
'drink/water/juice/1/232/89.json',
'drink/water1/soft/90091/2/89.csv',
'car/type/1/001/1.json',
'game/mmo/1/2/3.json'
)s (origin)
)

select s.origin, origin_splitted[3] x, origin_splitted[2]  y, regexp_extract(origin_splitted[1],'\d*') z
from
(
select s.origin, reverse(split(s.origin,'/')) origin_splitted from your_data s
)s

Result:

origin  x   y   z
user/values2/class/year/subject/18/9/2000291.csv    18  9   2000291
holiday/booking/type/1092/1921/1.csv              1092  1921    1
drink/water/juice/1/232/89.json                      1  232 89
drink/water1/soft/90091/2/89.csv                 90091  2   89
car/type/1/001/1.json                              1    1   1
game/mmo/1/2/3.json                                1    2   3

apply the same regexp_extract to x and y columns if necessary or another split can be applied instead of regexp_extract, hope you got the idea

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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