在hive/mysql中实现sum\u reverse()[explode table result]

4dbbbstv  于 2021-06-26  发布在  Hive
关注(0)|答案(3)|浏览(363)

我们要平均分配数量。表销售如下

product category qty
123     A        3
345     B        2

输出

product category qty
123     A        1
123     A        1
123     A        1
345     B        1
345     B        1
oknrviil

oknrviil1#

如果您有一个数字表,您可以:

select s.product, s.category, 1 as qty
from sales s join
     numbers n
     on n.n <= s.qty and n.n > 0;

在mysql中,可以使用变量生成这样的表。例如,如果 sales 足够大:

select s.product, s.category, 1 as qty
from sales s join
     (select (@rn := @rn + 1) as n
      from sales s cross join
           (select @rn := 0) params
     ) n
     on n.n <= s.qty and n.n > 0;
wkftcu5l

wkftcu5l2#

Hive

select  t.product
       ,t.category
       ,1           as qty

from    mytable t
        lateral view explode(split(space(t.qty - 1),' ')) e
;
+---------+----------+-----+
| product | category | qty |
+---------+----------+-----+
| 123     | A        | 1   |
+---------+----------+-----+
| 123     | A        | 1   |
+---------+----------+-----+
| 123     | A        | 1   |
+---------+----------+-----+
| 345     | B        | 1   |
+---------+----------+-----+
| 345     | B        | 1   |
+---------+----------+-----+
ovfsdjhp

ovfsdjhp3#

我自己想办法回答(这是在Hive里)

select category,main1.product,main2.qty from (select category,product,
split(substring(repeat(concat(1,','),int(qty)),0,int(qty*2)-1),",") as qty from 
(select collect_set(product) product,category,
sum(qty) qty
from sales) main
lateral view explode(product) main1 as product
lateral view explode(qty) main2 AS qty;

相关问题