1

有什么方法可以通过一个值将一行分成多行到行列?做我的查询,我得到了结果:

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可以做到这一点吗?

4

3 回答 3

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上的演示

于 2013-06-04T14:15:53.630 回答
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);
于 2013-06-04T14:05:29.960 回答
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
于 2013-06-04T13:56:05.740 回答