UNNEST多重价值观?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UNNEST多重价值观?相关的知识,希望对你有一定的参考价值。
我试图从另一张桌子上做一张桌子。原始表有一行如下所示:
------------------------
| 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每个列,然后尝试组合两个结果表(我也在努力),但理想情况下我希望一步到位。
这是我一次向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
答案
您可以使用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)
。因人而异。
另一答案
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_;
http://sqlfiddle.com/#!4/f795b9/32/0
以上是关于UNNEST多重价值观?的主要内容,如果未能解决你的问题,请参考以下文章