当前位置:网站首页>Introduction and example application of PostgreSQL string separator function (regexp\u split\u to\u table)

Introduction and example application of PostgreSQL string separator function (regexp\u split\u to\u table)

2022-06-22 22:41:00 Southejor

In project development , Sometimes you will encounter the need to split column data by a certain character , This article introduces in detail postgre Database split characters (regexp_split_to_table) And practical project application .

PostgreSQL String separator functions

--  Split into arrays , Subscript values can be used 
select (regexp_split_to_array('11,22,33',','))[2];
--  Split into virtual tables , It can be directly used as a normal table , Make a connection query , Add query criteria, etc 
select re from regexp_split_to_table('11,22,33',',') re where re='11';

PostgreSQL String separator function example application

Actual project requirements

In our project , The number of institutions and universities should be counted and ranked according to certain conditions , Some data in the database table is marked with semicolons ( ; ) Spliced multiple institutional Universities ,
such as : Wuhan University ; Electric Power Research Institute of Hebei electric power company .

In this case , Direct statistics are wrong , You need to put the data in semicolons first ( ; ) Split into independent universities and institutions , Then count the quantity .

Actual data

Directly querying data is 1168 strip .

 Insert picture description here

Split data

First use regexp_split_to_table Function to view the split data , After the split, the universities and institutions are 2797 strip .

SELECT
	regexp_split_to_table( applicant, ';' ) AS inventor_
FROM
     Table name  
--  Query criteria have been omitted 

 Insert picture description here

Here is the split data , You can see , The same query criteria , The data has been split up , The correct results can only be obtained by statistical split data .

The practical application

In the project , We will query and count the split data as a virtual table .

The query execution process is : First, find the data that meets the requirements according to the query criteria , Then split the data , Finally, count the total number .

sql sentence

SELECT
	regexp_split_to_table( applicant, ';' ) AS inventor_,
    COUNT ( * ) 
FROM
	 Table name  pt 
WHERE
	--  Query criteria have been omitted  
GROUP BY
	inventor_ 
ORDER BY
COUNT DESC 
LIMIT 10

statistics
 Insert picture description here

原网站

版权声明
本文为[Southejor]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221741341104.html