我想执行一个查询,该查询仅显示特定字段中破折号之前的所有字符串。
例如:
原始数据:AB-123
查询后:AB
您可以使用substr
:
SQL> WITH DATA AS (SELECT 'AB-123' txt FROM dual)
2 SELECT substr(txt, 1, instr(txt, '-') - 1)
3 FROM DATA;
SUBSTR(TXT,1,INSTR(TXT,'-')-1)
------------------------------
AB
或regexp_substr
(10g+):
SQL> WITH DATA AS (SELECT 'AB-123' txt FROM dual)
2 SELECT regexp_substr(txt, '^[^-]*')
3 FROM DATA;
REGEXP_SUBSTR(TXT,'^[^-]*')
---------------------------
AB
您可以使用regexp_replace
.
例如
WITH DATA AS (
SELECT 'AB-123' as text FROM dual
UNION ALL
SELECT 'ABC123' as text FROM dual
)
SELECT
regexp_replace(d.text, '-.*$', '') as result
FROM DATA d;
会导致
WITH DATA AS (
2 SELECT 'AB-123' as text FROM dual
3 UNION ALL
4 SELECT 'ABC123' as text FROM dual
5 )
6 SELECT
7 regexp_replace(d.text, '-.*$', '') as result
8 FROM DATA d;
RESULT
------------------------------------------------------
AB
ABC123
我发现这很简单
SELECT distinct
regexp_replace(d.pyid, '-.*$', '') as result
FROM schema.table d;
pyID 列包含 ABC-123、DEF-3454
SQL 结果:
ABC DEF