如何将csv字符串拆分为多个值

时间:2016-03-04 23:08:51

标签: sql vertica

我正在使用vertica,我在尝试将条目分成多个条目时遇到了麻烦。为了澄清,请考虑以下示例。假设我有以下表条目(让我们称之为pizza_toppings)

customer_name | order_date | toppings
--------------+------------+----------
sally         | 1/1/2011   | peppers, olives
mike          | 2/2/2011   | pepperoni, mushrooms

如何将浇头条目拆分成多行?下表是我想要的:

customer_name | order_date | toppings
--------------+------------+----------
sally         | 1/1/2011   | peppers
sally         | 1/1/2011   | olives
mike          | 2/2/2011   | pepperoni
mike          | 2/2/2011   | mushrooms

我一直在寻找多个论坛,我遇到了SPLIT_PART,但这需要您知道分隔条目中有多少部分。最重要的是,我不知道如何在INSERT中使用它。

感谢。

1 个答案:

答案 0 :(得分:3)

使用Vertica的txt索引包非常简单。假设你有一个这样的表:

SQL> select * from stest;
 customer_name | order_date |       toppings       
---------------+------------+----------------------
 sally         | 2011-01-01 | peppers, olives
 Robert        | 2011-04-04 | olives
 mike          | 2011-02-02 | pepperoni, mushrooms
 John          | 2011-03-03 | one, two, three
(4 rows)

您可以使用以下SQL来获取您要查找的内容:

SQL> select customer_name, order_date, trim(words) as toppings from (
       select customer_name, order_date,   
              v_txtindex.StringTokenizerDelim(toppings,',')  
                over(partition by customer_name, order_date) 
       from stest ) a ;
 customer_name | order_date | toppings  
---------------+------------+-----------
 mike          | 2011-02-02 | pepperoni
 mike          | 2011-02-02 | mushrooms
 Robert        | 2011-04-04 | olives
 sally         | 2011-01-01 | peppers
 sally         | 2011-01-01 | olives
 John          | 2011-03-03 | one
 John          | 2011-03-03 | two
 John          | 2011-03-03 | three
(8 rows)

如果您没有安装txt索引包...作为dbadmin:

$ cd /opt/vertica/packages/txtindex/ddl
$ vsql -f install.sql