分解为单个单元级别

Deaggregate into single unit level

我有以下 table 需要分解或分解:

Order Table:

Order Id Item   Qty
O1       A1      5
O2       A2      1
O3       A3      3

请提供SQL,这会将上述数据分解为单个单位级别的记录,如下所示:

期望的输出:

Order Id    Item    Qty
O1          A1       1
O1          A1       1
O1          A1       1
O1          A1       1
O1          A1       1
O2          A2       1
O3          A3       1
O3          A3       1
O3          A3       1

我如何在 Teradata 中执行此操作?

您可以使用 on n between 1 and Qty 加入从 1 到 n 的 table(导致 产品加入)或利用 EXPAND ON:

select OrderId, Item, 1
from tab
expand on period (current_date, current_date + Qty) as pd

具有递归 cte 的方法。

with recursive cte(orderid,item,qty,val) as 
        (select orderid, item, qty, 1
         from t --this is your tablename
         union all
         select c.orderid, c.item, c.qty-1, c.val
         from t
         join cte c on t.orderid=c.orderid and t.item=c.item and c.qty>1
        )
select orderid,item,val as qty
from cte 
order by 1,2

或使用数字 table(生成所有数字 = 您可以拥有的最大数量)

with recursive cte(num) as (select 1 num
                            union all
                            select num+1 from cte where num < 1000 --change this to max quantity
                            )
select orderid, item, 1 as qty
from t
join cte c on t.qty >= c.num
order by 1,2

另一种使用复制和 string_split

的解决方案
select order_id, item, value
from (
select order_id, item, 
iif(quantity = 1, '1', concat('1',replicate(',1',(quantity-1)))) as split_quant
from orders) a
  CROSS APPLY STRING_SPLIT(split_quant,',') ;

有关 string_split 的更多信息:https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql?view=sql-server-2017

with main1 as(
select orderid,item, qty, rownum rn from orders)
select orderid,item, '1' from (select * from 
main1
where rn = 1) 
connect by level <= qty
union all
select orderid,item,'1' from (select * from 
main1
where rn = 2) 
connect by level <= qty
union all
select orderid,item,'1' from (select * from 
main1
where rn = 3) 
connect by level <= qty
;