问题
I am passing Elastic Load Balancing Access logs to Athena and I want to get a value that is located in the URL column. The below works for mySQL but Athena uses SQL is there a way I can grab the value of county from the below?
create table elb_logs(row varchar(100), url varchar(100));
insert into elb_logs values("Row1", "Lauguage=English&Country=USA&Gender=Male");
insert into elb_logs values("Row2", "Gender=Female&Language=French&Country=");
insert into elb_logs values("Row3", "Country=Canada&Gender=&Language=English");
insert into elb_logs values("Row4", "Gender=&Language=English");
SELECT `row`, IF(LOCATE('Country=', url)>0,
COALESCE(
NULLIF(SUBSTRING_INDEX(SUBSTRING_INDEX(url, 'Country=', -1), '&', 1), ''),
'Blank string is not valid!'),
'Missing Country!') AS ColumnB
FROM `elb_logs`
+------+----------------------------+
| row | ColumnB |
+------+----------------------------+
| Row1 | USA |
| Row2 | Blank string is not valid! |
| Row3 | Canada |
| Row4 | Missing Country! |
+------+----------------------------+
回答1:
The SPLIT_PART
function would seem to be usable here:
SELECT
row,
CASE WHEN POSITION('Country=' IN url) > 0
THEN SPLIT_PART(SPLIT_PART(url, 'Country=', 2), '&', 1)
ELSE 'Missing Country!' END AS ColumnB
FROM elb_log;
回答2:
Use Cross Apply
SELECT row, CASE WHEN LEFT(T2.URL, charindex('&', T2.URL) - 1) = '' THEN 'Blank string is not valid!'
WHEN LEFT(T2.URL, charindex('&', T2.URL) - 1) LIKE '%=%' THEN 'Missing Country!'
ELSE LEFT(T2.URL, charindex('&', T2.URL) - 1) END AS Country
FROM elb_logs AS T
CROSS APPLY (SELECT STUFF(T.URL, 1, charindex('&Country', T.URL) + 8, '')+'&') as T2(URL);
来源:https://stackoverflow.com/questions/58691164/locate-value-in-column