多重价值?

时间:2018-09-04 17:21:22

标签: sql subquery 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的查询:

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

说原始表有“一行”:您是说一个表吗?如果是这样,就可以解决问题:

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

答案 2 :(得分:0)

您可以使用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)。嗯。