在sql中爆炸表

时间:2016-06-23 15:53:49

标签: sql

问题陈述:

我的表格中有Product_id和Quantity列 假设product_id A有2个单位,B有3个单位等

如何创建一个包含2行Product_id A,3行Product_id B的表?

2 个答案:

答案 0 :(得分:0)

我是基于递归公用表表达式进行此练习的:

;WITH CTE (Vals) 
AS (
SELECT 1 
 UNION ALL
SELECT 1 + Vals
FROM CTE WHERE Vals< 99
   )
SELECT Product_id
FROM       Mytable A 
INNER JOIN CTE C   ON C.Vals <= A.Quantity
ORDER BY A.Product_id

假设数量&lt; 99

可以帮到你

答案 1 :(得分:0)

这对我有用,在您的示例中进行了测试:

WITH tally(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM tally WHERE n<100) 

SELECT Product_id, 1 as Quantity 
FROM MyTable CROSS JOIN tally 
WHERE n<=quantity 
ORDER BY Product_id;