繁体   English   中英

如何在SQL中拆分单元格并创建新行

[英]How to split a cell and create a new row in sql

我有一列存储多个逗号分隔的值。 我需要以某种方式对其进行拆分,以便将其拆分为与该列中的值一样多的行以及该行中的其余值。

例如:

John 111 2Jan
Sam  222,333 3Jan
Jame 444,555,666 2Jan
Jen  777 4Jan

输出:

John 111 2Jan
Sam  222 3Jan
Sam  333 3Jan
Jame 444 2Jan
Jame 555 2Jan
Jame 666 2Jan
Jen  777 4Jan

PS:我已经看到多个与此类似的问题,但是找不到以这种方式拆分的方法。

该解决方案基于Vertica构建,但是适用于每个数据库,该数据库提供与SPLIT_PART()相对应的功能。

它的一部分对应于我在这里说明的每个符合ANSI的数据库平台都可以使用的非透视技术(只是脚本的非透视部分):

Pivot SQL将行转换为列

因此,我将在下面进行操作。 我假设简约的日期表示形式是两列输入表的第二列的一部分。 因此,在将逗号分隔的列表拆分为标记之前,我首先要在第一个Common Table Expression(以及在注释中,我列出该CTE的输出)中拆分该短日期文字。

开始:

WITH
-- input
input(name,the_string) AS (
          SELECT 'John', '111 2Jan'
UNION ALL SELECT 'Sam' , '222,333 3Jan'
UNION ALL SELECT 'Jame', '444,555,666 2Jan'
UNION ALL SELECT 'Jen' , '777 4Jan'
)
,
-- put the strange date literal into a separate column
the_list_and_the_date(name,list,datestub) AS (
SELECT
  name
, SPLIT_PART(the_string,' ',1)
, SPLIT_PART(the_string,' ',2)
FROM input
)
-- debug
-- SELECT * FROM the_list_and_the_date;
-- name|list       |datestub
-- John|111        |2Jan
-- Sam |222,333    |3Jan
-- Jame|444,555,666|2Jan
-- Jen |777        |4Jan
,
-- ten integers (too many for this example) to use as pivoting value and as "index"
ten_ints(idx) AS (
          SELECT  1 
UNION ALL SELECT  2 
UNION ALL SELECT  3 
UNION ALL SELECT  4 
UNION ALL SELECT  5 
UNION ALL SELECT  6 
UNION ALL SELECT  7 
UNION ALL SELECT  8 
UNION ALL SELECT  9 
UNION ALL SELECT 10
)
-- the final query - pivoting prepared input using a CROSS JOIN with ten_ints
-- and filter out where the SPLIT_PART() expression evaluates to the empty string
SELECT
  name
, SPLIT_PART(list,',',idx) AS token
, datestub
FROM the_list_and_the_date
CROSS JOIN ten_ints
WHERE SPLIT_PART(list,',',idx) <> ''
;

name|token|datestub
John|111  |2Jan
Jame|444  |2Jan
Jame|555  |2Jan
Jame|666  |2Jan
Sam |222  |3Jan
Sam |333  |3Jan
Jen |777  |4Jan

玩的开心...

Marco the Sane

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM