如何通过列中的值将行拆分为多个等于行?

时间:2013-06-04 13:50:09

标签: sql sql-server linq sql-server-2008-r2 union

有什么方法可以通过行列中的行将行划分为多行? 做我的查询,我得到了结果:

ID TmpShoppingCart_ID StoreSKU_ID QuantityΞΞ Enabled 
26 34                 448         2          True 
27 34                 3465        4          True 
28 34                 3468        1          True 

但我想:

ID TmpShoppingCart_ID StoreSKU_ID QuantityΞΞ Enabled 
26 34                 448         1          True 
26 34                 448         1          True 
27 34                 3465        1          True 
27 34                 3465        1          True 
27 34                 3465        1          True 
27 34                 3465        1          True 
28 34                 3468        1          True 

有没有简单的sintax呢?

3 个答案:

答案 0 :(得分:2)

master..spt_values系统表的另一个选项。您也可以在自己的序列表上替换系统表

SELECT ID, TmpShoppingCart_ID, StoreSKU_ID, o.Quantity, [Enabled]
FROM [dbo].[tmpShoppingCartItem] t 
CROSS APPLY (
             SELECT 1
             FROM master..spt_values v
             WHERE v.type = 'P' AND v.number < t.Quantity
             )o(Quantity)

SQLFiddle上的演示

答案 1 :(得分:1)

您可以使用递归CTE在SQL Server中生成数字。获得数字列表后,即可进行查询。

这是一个以100作为最大值的示例:

with nums as (
      select 1 as n
      union all
      select n + 1
      from nums
      where n < 100
     ),
     t as (select 26 as id, 34 as TmpShoppingCart_id, 448 as storesku_id, 2 as quantity, 'true' as enabled)
select id, TmpShoppingCart_id, storesku_id, 1, enabled
from t join
     nums
     on nums.n <= t.quantity;

如果这还不够大,你可以让它变得动态,但必须注意MAX_RECURSION选项:

with t as (
      select 26 as id, 34 as TmpShoppingCart_id, 448 as storesku_id, 200 as quantity, 'true' as enabled
     ),
     nums as (
      select 1 as n, MAX(quantity) as maxq
      from t
      union all
      select n + 1, maxq
      from nums
      where n <= maxq
     )
select id, TmpShoppingCart_id, storesku_id, 1, enabled
from t join
     nums
     on nums.n <= t.quantity
option (MAXRECURSION 1000);

答案 2 :(得分:0)

这很简单吗?

begin transaction
declare @rowcount int
set @rowcount = 1

while @rowcount > 0 
begin

    insert into shoppingcart(tmpShoppingCart_id,StoreSKU_Id,Quantity,Enabled)
    select tmShoppingCart_id,StoreSku_id,1,enabled
    from shoppingcart where quantity > 1

    update shoppingcart
    set quantity = quantity - 1
    where quantity > 1

    select @rowcount = @@rowcount

end
commit transaction