search
HomeDatabaseSQLSQL case study: merging and splitting strings

This article brings you relevant knowledge about SQL server. It mainly introduces you to the relevant information about the merging and splitting of strings in SQL case study. The article introduces the two methods respectively. This method has certain reference learning value for everyone to learn or use Oracle. Friends in need can refer to it.

SQL case study: merging and splitting strings

Recommended study: "SQL Tutorial"

Merge of strings

There may be multiple implementation methods in Oracle. Currently, there are two known to me. The implementation of these two types is recorded below:

String merging method One:

Implement SQL:

--方法一
SELECT d.dept_name,wm_concat(e.emp_name) FROM employee e
INNER JOIN department d ON d.dept_id=e.dept_id
GROUP BY d.dept_name;

Execution result:

SQL analysis:

Use Oracle's own wm_concat() function to merge strings. There is a disadvantage here. The merged connection symbol can only be the default comma, and other symbols cannot be used.

String merging method two:

Implement SQL:

--方法二
SELECT d.dept_name,
LISTAGG (e.emp_name, ',') WITHIN GROUP (ORDER BY e.emp_name) names
FROM employee e
INNER JOIN department d ON d.dept_id=e.dept_id
GROUP BY d.dept_name;

Execution result:

SQL analysis:

Use Oracle's own LISTAGG() function to merge strings. Its advantage is that the merged connection symbol can be specified as any characters, and can easily implement ORDER BY sorting.

String splitting

There may be multiple implementation methods in Oracle, the ones I know so far There are two types. The implementation of these two types is recorded below:

String splitting method one:

Implementation of SQL:

--方法一
WITH  t (id, name, sub, str) AS (
    SELECT id, name, substr(class, 1, instr(class, '、')-1), substr(concat(class,'、'), instr(class, '、')+1) 
    FROM movies
    
    UNION ALL
    
    SELECT id, name,substr(str, 1, instr(str, '、')-1), substr(str, instr(str, '、')+1)
    FROM t WHERE instr(str, '、')>0
) 
 
SELECT id, name, sub
FROM t
ORDER BY id;

Execution result:

##SQL analysis:

This statement is a little complicated, and it will be explained step by step below:

First look at the original data of the movies table:

1. The first step is to divide the value of the class field according to the delimiter (here is a comma) Perform a preliminary split into two parts. The first part is the first value of the class field to be split, and the second part is the value of the remaining parts of the class field to be split.

2. The second step uses WITH expression to implement recursive query, and loops the unsplit values ​​in the first step according to the delimiter (here is the comma) (Part 2) Split until the last delimiter of the field, and the data at the end of the recursion is placed in the temporary table t.

3. The third step is a simple query to query and sort the records from the temporary table t in the second step.

String splitting method two:

Implement SQL:

--方法二
SELECT m.name,t.column_value FROM movies m,TABLE(SPLIT(m.class,'、')) t;

Execution result:

SQL analysis:

This method actually processes strings by customizing a function. , the logic of function split is actually similar to the logic of method 1. They both use recursion to split the values ​​in the string one by one according to the delimiter, and finally return the split string. Personally, I feel this method is better because it encapsulates the splitting logic, making it simpler to use and clearer in logic.

The following is the creation script of the split function:

create or replace function split (p_list clob, p_sep varchar2 := ',')
  return tabletype
  pipelined
 
is
  l_idx    pls_integer;
  v_list  varchar2 (32676) := to_char(p_list);
begin
  loop
      l_idx  := instr (v_list, p_sep);
 
      if l_idx > 0
      then
        pipe row (substr (v_list, 1, l_idx - 1));
        v_list  := substr (v_list, l_idx + length (p_sep));
      else
        pipe row (v_list);
        exit;
      end if;
  end loop;
end;

The return value type of the function, tabletype, is also a custom type.

The following is the creation script of this type:

create or replace type tabletype as table of varchar2(32676);

Recommended learning: "

SQL Tutorial"

The above is the detailed content of SQL case study: merging and splitting strings. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:脚本之家. If there is any infringement, please contact admin@php.cn delete
OLTP vs OLAP: What about big data?OLTP vs OLAP: What about big data?May 14, 2025 am 12:06 AM

OLTPandOLAParebothessentialforbigdata:OLTPhandlesreal-timetransactions,whileOLAPanalyzeslargedatasets.1)OLTPrequiresscalingwithtechnologieslikeNoSQLforbigdata,facingchallengesinconsistencyandsharding.2)OLAPusesHadoopandSparktoprocessbigdata,withsetup

What is Pattern Matching in SQL and How Does It Work?What is Pattern Matching in SQL and How Does It Work?May 13, 2025 pm 04:09 PM

PatternmatchinginSQLusestheLIKEoperatorandregularexpressionstosearchfortextpatterns.Itenablesflexibledataqueryingwithwildcardslike%and_,andregexforcomplexmatches.It'sversatilebutrequirescarefulusetoavoidperformanceissuesandoveruse.

Learning SQL: Understanding the Challenges and RewardsLearning SQL: Understanding the Challenges and RewardsMay 11, 2025 am 12:16 AM

Learning SQL requires mastering basic knowledge, core queries, complex JOIN operations and performance optimization. 1. Understand basic concepts such as tables, rows, and columns and different SQL dialects. 2. Proficient in using SELECT statements for querying. 3. Master the JOIN operation to obtain data from multiple tables. 4. Optimize query performance, avoid common errors, and use index and EXPLAIN commands.

SQL: Unveiling Its Purpose and FunctionalitySQL: Unveiling Its Purpose and FunctionalityMay 10, 2025 am 12:20 AM

The core concepts of SQL include CRUD operations, query optimization and performance improvement. 1) SQL is used to manage and operate relational databases and supports CRUD operations. 2) Query optimization involves the parsing, optimization and execution stages. 3) Performance improvement can be achieved through the use of indexes, avoiding SELECT*, selecting the appropriate JOIN type and pagination query.

SQL Security Best Practices: Protecting Your Database from VulnerabilitiesSQL Security Best Practices: Protecting Your Database from VulnerabilitiesMay 09, 2025 am 12:23 AM

Best practices to prevent SQL injection include: 1) using parameterized queries, 2) input validation, 3) minimum permission principle, and 4) using ORM framework. Through these methods, the database can be effectively protected from SQL injection and other security threats.

MySQL: A Practical Application of SQLMySQL: A Practical Application of SQLMay 08, 2025 am 12:12 AM

MySQL is popular because of its excellent performance and ease of use and maintenance. 1. Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2. Insert and query data: operate data through INSERTINTO and SELECT statements. 3. Optimize query: Use indexes and EXPLAIN statements to improve performance.

Comparing SQL and MySQL: Syntax and FeaturesComparing SQL and MySQL: Syntax and FeaturesMay 07, 2025 am 12:11 AM

The difference and connection between SQL and MySQL are as follows: 1.SQL is a standard language used to manage relational databases, and MySQL is a database management system based on SQL. 2.SQL provides basic CRUD operations, and MySQL adds stored procedures, triggers and other functions on this basis. 3. SQL syntax standardization, MySQL has been improved in some places, such as LIMIT used to limit the number of returned rows. 4. In the usage example, the query syntax of SQL and MySQL is slightly different, and the JOIN and GROUPBY of MySQL are more intuitive. 5. Common errors include syntax errors and performance issues. MySQL's EXPLAIN command can be used for debugging and optimizing queries.

SQL: A Guide for Beginners - Is It Easy to Learn?SQL: A Guide for Beginners - Is It Easy to Learn?May 06, 2025 am 12:06 AM

SQLiseasytolearnforbeginnersduetoitsstraightforwardsyntaxandbasicoperations,butmasteringitinvolvescomplexconcepts.1)StartwithsimplequerieslikeSELECT,INSERT,UPDATE,DELETE.2)PracticeregularlyusingplatformslikeLeetCodeorSQLFiddle.3)Understanddatabasedes

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),