简体   繁体   English

AWS Athena 根据列值创建行

[英]AWS Athena create rows based on a column value

I have a table showing simple order details as follows我有一个表格显示简单的订单详细信息如下

+---------+---------+---------+
| Order_id| Item_id |Quantity |
+---------+---------+---------+
| 10001   | 1       |   4     |
+---------+---------+---------+ 

Now I need to show each quantity as a line item as follows.现在我需要将每个数量显示为一个行项目,如下所示。

+---------+---------+---------+---------+
| Order_id| Item_id | Line_id |Quantity |
+---------+---------+---------+---------+
| 10001   | 1       | 1       |   1     |
+---------+---------+---------+---------+ 
| 10001   | 1       | 2       |   1     |
+---------+---------+---------+---------+ 
| 10001   | 1       | 3       |   1     |
+---------+---------+---------+---------+ 
| 10001   | 1       | 4       |   1     |
+---------+---------+---------+---------+ 

Can any one help me how can I write query to achieve this?任何人都可以帮助我如何编写查询来实现这一目标?

We can try using a recursive CTE here:我们可以在这里尝试使用递归 CTE:

WITH cte AS (Order_id, Item_id, Line_id, Amount) AS (
    SELECT Order_id, Item_id, Quantity, 1
    FROM yourTable
    UNION ALL
    SELECT Order_id, Item_id, Line_id - 1, 1
    FROM cte
    WHERE Line_id - 1 >= 1
)

SELECT Order_id, Item_id, Line_id, Quantity
FROM cte
ORDER BY Order_id, Item_id, Line_id;

The logic in the CTE above is that we form the base case of the recursion using the following tuple from your source table:上面 CTE 中的逻辑是我们使用源表中的以下元组形成递归的基本情况:

(10001, 1, 4, 1)

That is, we start counting for the Line_id from 4, decreasing by one in each step of the recursion.也就是说,我们从 4 开始计算Line_id ,在递归的每一步中减 1。 At the end of the recursive case, we hit a Line_id value of 1.在递归案例结束时,我们的Line_id值为 1。

You can use unnest on an array to get the value you want:您可以在数组上使用unnest来获取您想要的值:

select od.order_id, od.item_id, u.line_number, u.quantity
from order_details od cross join
     unnest(repeat(1, od.quantity)) with ordinality u(quantity, line_number)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM