sql—如何将列中的串联值转换为行

hpcdzsge  于 2021-06-27  发布在  Hive
关注(0)|答案(1)|浏览(456)

输入:

  1. item number
  2. ABC 123

我想这样输出:

  1. item number
  2. A 1
  3. B 2
  4. C 3
sqxo8psd

sqxo8psd1#

使用拆分字符串 split() ,使用 posexplode() 使用侧视图。按空字符串拆分 '' 将生成包含额外空元素的数组,过滤掉它们,按它们在数组中的位置连接项和数字。
演示(用表替换s子查询):

  1. select i.itm as item, n.nbr as number
  2. from
  3. (--replace this subquery with your table
  4. --this is two rows example
  5. select stack(2,'ABC', '123',
  6. 'DEF', '456') as (item, number)
  7. ) s --your_table
  8. lateral view posexplode(split(s.item,'')) i as pos, itm
  9. lateral view posexplode(split(s.number,'')) n as pos, nbr
  10. where i.itm!='' and n.nbr!='' and i.pos=n.pos ;

结果:

  1. OK
  2. item number
  3. A 1
  4. B 2
  5. C 3
  6. D 4
  7. E 5
  8. F 6
  9. Time taken: 0.094 seconds, Fetched: 6 row(s)
  10. hive>

更新:简化版本

  1. select i.itm as item, substr(s.number,i.pos+1,1) as number
  2. from
  3. (--replace this subquery with your table
  4. --this is two rows example
  5. select stack(2,'ABC', '123',
  6. 'DEF', '456') as (item, number)
  7. ) s --your_table
  8. lateral view posexplode(split(s.item,'')) i as pos, itm
  9. where i.itm!='';
展开查看全部

相关问题