![](/img/trans.png)
[英]Rolling Multiple Rows into a Single Row Based on Matching Data in SQL Server
[英]SQL for splitting a single row data into multiple rows based on character
到目前为止,我已经编写了一个查询,将第一行分为多行,但随后的N行的结果将是N行返回空值。
这是场景。
select address from sample;
它将返回以下4行,
Stack Overflow# is a# question and# answer site
Stack Overflow# is a# question and# answer site
Stack Overflow# is a# question and# answer site
Stack Overflow# is a# question and# answer site
当尝试使用以下查询将每一行拆分为多行时,
with test as (select address as str from sample)
select regexp_substr (str, '[^#]+', 1, rownum) split
from test
connect by level <= length (regexp_substr (str, '[^#]+', 1, rownum)) + 1
;
将返回以下值。
Stack Overflow
is a
question and
answer site
(null)
(null)
(null)
为什么无法获得所有行的结果?
为什么无法获得所有行的结果?
您的查询有两点不正确。
因为使用ROWNUM是不正确的。 您在同一查询中使用ROWNUM作为条件,但是ROWNUM尚未增加到next value 。 因此,它的价值只是其中之一。 因此,您仅获得1行。
您需要对所有行进行拆分,而不仅仅是第一行。 您需要遍历所有行。 但是,与此同时,您应该避免循环循环并消除重复项。
有多种方法可以对多行进行字符串拆分。 我已经在这里的文章中演示了http://lalitkumarb.wordpress.com/2015/03/04/split-comma-delimited-strings-in-a-table-using-oracle-sql/
例如,您可以这样做:
SQL> WITH t AS(
2 SELECT 'Stack Overflow# is a# question and# answer site' text FROM dual UNION ALL
3 SELECT 'Stack Overflow# IS a# question and# answer site' text FROM dual UNION ALL
4 SELECT 'Stack Overflow# is a# question and# answer site' text FROM dual UNION ALL
5 SELECT 'Stack Overflow# IS a# question and# answer site' text FROM dual
6 )
7 SELECT trim(regexp_substr(t.text, '[^#]+', 1, lines.column_value)) text
8 FROM t,
9 TABLE (CAST (MULTISET
10 (SELECT LEVEL FROM dual CONNECT BY LEVEL <= regexp_count(t.text, '#')+1)
11 AS sys.odciNumberList
12 )
13 ) lines
14 /
TEXT
-----------------------------------------------
Stack Overflow
is a
question and
answer site
Stack Overflow
IS a
question and
answer site
Stack Overflow
is a
question and
answer site
Stack Overflow
IS a
question and
answer site
16 rows selected.
SQL>
因此,您现在得到16行 。 完美的作品!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.