gpt4 book ai didi

sql - PostgreSQL-拆分行

转载 作者:行者123 更新时间:2023-11-29 14:10:40 26 4
gpt4 key购买 nike

我有一个看起来像这样的表:

ID      |  name  | details
---------------------------
1.3.1-3 | Jack | a
5.4.1-2 | John | b
1.4.5 | Alex | c

以及像这样拆分它的内容:

ID      |  name  | details
---------------------------
1.3.1 | Jack | a
1.3.2 | Jack | a
1.3.3 | Jack | a
5.4.1 | John | b
5.4.2 | John | b
1.4.5 | Alex | c

我怎样才能在 postgresql 中做到这一点?

最佳答案

CREATE TABLE tosplit
( id text NOT NULL
, name text
, details text
);

INSERT INTO tosplit( id , name , details ) VALUES
( '1.3.1-3' , 'Jack' , 'a' )
,( '5.4.1-2' , 'John' , 'b' )
,( '1.4.5' , 'Alex' , 'c' )


WITH zzz AS (
SELECT id
, regexp_replace(id, '([0-9\.]+\.)([0-9]+)-([0-9]+)', e'\\1', e'g') AS one
, regexp_replace(id, '([0-9\.]+\.)([0-9]+)-([0-9]+)', e'\\2', e'g') AS two
, regexp_replace(id, '([0-9\.]+\.)([0-9]+)-([0-9]+)', e'\\3', e'g') AS three
, name
, details
FROM tosplit
)
SELECT z1.id
-- , z1.one
, z1.one || generate_series( z1.two::integer, z1.three::integer)::text AS four
, z1.name, z1.details
FROM zzz z1
WHERE z1.two <> z1.one
UNION ALL
SELECT z0.id
-- , z0.one
, z0.one AS four
, z0.name, z0.details
FROM zzz z0
WHERE z0.two = z0.one
;

结果:

CREATE TABLE
INSERT 0 3
id | four | name | details
---------+-------+------+---------
1.3.1-3 | 1.3.1 | Jack | a
1.3.1-3 | 1.3.2 | Jack | a
1.3.1-3 | 1.3.3 | Jack | a
5.4.1-2 | 5.4.1 | John | b
5.4.1-2 | 5.4.2 | John | b
1.4.5 | 1.4.5 | Alex | c

关于sql - PostgreSQL-拆分行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35575481/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com