如何查询位置在SQL的多个子字符串?
How to query for multiple sub strings with position in SQL?
我有以下查询:
select position( '/s/' in col)
from table
这有效。
现在,我希望能够找到 /s/
或 /d/
或 /c/
的位置
我试过了:
select position( '[/s/][/c/][/d/]' in col)
from table
但它 returns 是一个错误的值。
示例:
select position( '/s/' in '/s/')
returns1.
select position( '[/s/][/d/][/c/]' in '/s/')
returns 0
我该如何解决这个问题?
编辑:
只能包含/s/
或/d/
或/c/
之一。该字符串将不包含 /s/d/
等...
匹配的子字符串不能超过一次。该字符串将不包含 '/s/..../s/'
简单来说 - 我正在寻找 /s/ or /d/ or /c/
的第一次出现,不要担心边缘情况。
这可能会成功:
SELECT MAX(patlist.pattern) FROM (VALUES (POSITION('/s/' IN col)), (POSITION('/d/' IN col)), (POSITION('/c/' IN col))) AS patlist(pattern)
包裹在查询中:
SELECT (SELECT MAX(patlist.pattern) FROM (VALUES (POSITION('/s/' IN col)), (POSITION('/d/' IN col)), (POSITION('/c/' IN col))) AS patlist(pattern))
FROM MyTable
免责声明:在没有 prestodb 实例的情况下,我只能在备用数据库引擎上对其进行测试。它可能适用于也可能不适用于 prestodb。
由于您在评论中写道,只有一个子字符串会出现并且 position()
返回 0
,如果找不到子字符串,您可以检查多个子字符串的总和position()
s.
SELECT position('/s/' in col)
+
position('/d/' in col)
+
position('/c/' in col)
FROM table;
或者更好,因为 Presto 有一个 greatest()
函数,你可以这样做:
SELECT greatest(position('/s/' in col),
position('/d/' in col),
position('/c/' in col))
FROM table;
这样你就得到了最好的位置。
我有以下查询:
select position( '/s/' in col)
from table
这有效。
现在,我希望能够找到 /s/
或 /d/
或 /c/
我试过了:
select position( '[/s/][/c/][/d/]' in col)
from table
但它 returns 是一个错误的值。
示例:
select position( '/s/' in '/s/')
returns1.
select position( '[/s/][/d/][/c/]' in '/s/')
returns 0
我该如何解决这个问题?
编辑:
只能包含
/s/
或/d/
或/c/
之一。该字符串将不包含/s/d/
等...匹配的子字符串不能超过一次。该字符串将不包含
'/s/..../s/'
简单来说 - 我正在寻找 /s/ or /d/ or /c/
的第一次出现,不要担心边缘情况。
这可能会成功:
SELECT MAX(patlist.pattern) FROM (VALUES (POSITION('/s/' IN col)), (POSITION('/d/' IN col)), (POSITION('/c/' IN col))) AS patlist(pattern)
包裹在查询中:
SELECT (SELECT MAX(patlist.pattern) FROM (VALUES (POSITION('/s/' IN col)), (POSITION('/d/' IN col)), (POSITION('/c/' IN col))) AS patlist(pattern))
FROM MyTable
免责声明:在没有 prestodb 实例的情况下,我只能在备用数据库引擎上对其进行测试。它可能适用于也可能不适用于 prestodb。
由于您在评论中写道,只有一个子字符串会出现并且 position()
返回 0
,如果找不到子字符串,您可以检查多个子字符串的总和position()
s.
SELECT position('/s/' in col)
+
position('/d/' in col)
+
position('/c/' in col)
FROM table;
或者更好,因为 Presto 有一个 greatest()
函数,你可以这样做:
SELECT greatest(position('/s/' in col),
position('/d/' in col),
position('/c/' in col))
FROM table;
这样你就得到了最好的位置。