Extract substrings from field sql/presto

左心房为你撑大大i 提交于 2020-01-05 03:46:10

问题


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 e.g., 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


回答1:


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



来源:https://stackoverflow.com/questions/57506639/extract-substrings-from-field-sql-presto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!