[英]UNNEST Multiple Values?
我試圖用另一張桌子做一張桌子。 原始表的行如下所示:
------------------------
| col1 | col 2 | col 3 |
------------------------
| item | a,b,c | 1,2,3 |
------------------------
我正在嘗試將該行放入這樣的表中:
------------------------
| col1 | col 2 | col 3 |
------------------------
| item | a | 1 |
------------------------
| item | b | 2 |
------------------------
| item | c | 3 |
------------------------
因此,基本上我想同時取消兩個逗號分隔的行。 到目前為止,我能想到的最好的方法是分別對每一列進行UNNEST,然后嘗試合並兩個結果表(我也在為此而苦苦掙扎),但是理想情況下,我希望一步實現這一點。
這是我一次查詢一次UNNEST的查詢:
SELECT
col1, col2, col3
FROM
tableName,
UNNEST(SPLIT(col2)) AS col2
這是我嘗試將UNNEST用作子查詢的嘗試,但是它給出了大量結果:
SELECT sub.*
FROM (
SELECT
col1, col2, col3 AS col3
FROM
tableName,
UNNEST(SPLIT(col2)) AS col2
WHERE
randomCol = 'something'
) sub,
UNNEST(SPLIT(sub.col3)) AS col3
SQL標准允許將多個值傳遞給unnest()
函數。
所以以下應該工作(在Postgres中也可以)
select d.col1,
t.*
from data d
cross join unnest(string_to_array(d.col2, ','), string_to_array(d.col3, ',')) as t(col1, col2)
這也可以正確處理列表中不同數量的元素。
但是,我不知道您的專有DBMS是否支持該功能。
在線示例: http : //rextester.com/XPN48947
通過說原始表有“一行”:您是指一個表嗎? 如果是,這可以解決問題:
with
num_rows_ as (
select length( regexp_replace((select b from t), '[^,]+')) + 1 value_ from dual),
a_ as (
select a from t),
b_ as (
select regexp_substr( (select b from t), '[^,]', 1, level ) b,rownum rownum_
from dual
connect by level <= (select value_ from num_rows_)),
c_ as (
select regexp_substr( (select c from t), '[^,]', 1, level ) c,rownum rownum_
from dual
connect by level <= (select value_ from num_rows_))
select a_.a,b_.b,c_.c
from a_
full outer join b_ on 1=1
inner join c_ on b_.rownum_ = c_.rownum_;
http://sqlfiddle.com/#!4/f795b9/29
或更短一步:
with a_ as
(select a from t),
b_c_ as (
select regexp_substr( (select b from t), '[^,]', 1, level ) b,regexp_substr( (select c from t), '[^,]', 1, level ) c
from dual
connect by level <= (length( regexp_replace((select b from t), '[^,]+')) + 1)
)
select * from a_ cross join b_c_;
您可以使用unnest(split(col))
策略,但不要交叉連接這兩列。 您的答案暗含了逗號分隔值的隱含順序,因此您需要建立一個字段(下面的RowNumber
)以指示此順序。
with Expanded2 as (
select
tableName.col1,
col2.col2,
row_number() over (partition by col1 order by 1) RowNumber
from
tableName,
unnest(split(col2)) col2
), Expanded3 as (
select
tableName.col1,
col3.col3,
row_number() over (partition by col1 order by 1) RowNumber
from
tableName,
unnest(split(col3)) col3
)
select
Expanded2.col1,
Expanded2.col2,
Expanded3.col3
from
Expanded2
full outer join Expanded3 on
Expanded2.col1 = Expanded3.col1
and Expanded2.RowNumber = Expanded3.RowNumber
我不確定您的rdbms如何有效地處理空窗口分區。 上面的工作在PostgreSQL中。 SQL Server將要求order by (select null)
。 因人而異。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.