简体   繁体   中英

SQL and Oracle query to extract every thing before last two periods

I need to extract every thing before last two periods

eg.

Input: AA.BBB.12.11.cc

Output: AA.BBB.12

Following is the sample query I am using but that returns only the characters before first period, but that is not I needed.

SELECT REGEXP_SUBSTR(t.column,'[^.]+',1,1)
 AS output
 FROM MY_Table  t where t.column is not null and rownum=1

I would use REGEXP_REPLACE here:

SELECT REGEXP_REPLACE(t.column, '\.[^.]+\.[^.]+$', '')
FROM MY_table
WHERE t.column IS NOT NULL AND rownum = 1;

The regex pattern \\.[^.]+\\.[^.]+$ will match starting with the second to last dot, all content until the end (including also the last dot).

You can simply use INSTR and SUBSTR as following:

SQL> SELECT
  2      SUBSTR('AA.BBB.12.11.ccCC', 1, INSTR('AA.BBB.12.11.ccCC', '.', -2, 2) - 1) AS RESULT
  3  FROM DUAL;

RESULT
---------
AA.BBB.12

SQL>

-- Update --

For the question asked in the comment, use the following query:

SQL> SELECT
  2      SUBSTR('AA.BB.CC.DD', 1, INSTR('AA.BB.CC.DD', '.', 1, 3) - 1) AS RESULT
  3  FROM DUAL;

RESULT
--------
AA.BB.CC

SQL>

Cheers!!

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