将值转换为单行

时间:2012-03-22 21:58:32

标签: sql sql-server sql-server-2008

当前

Name   Quantity
---------------
Stella       2
Jennifer     2
Greg         3 

请求结果

Name    Quantity 
---------------
Stella       1
Stella       1
Jennifer     1
Jennifer     1
Greg         1
Greg         1 
Greg         1 

我该怎么做?

declare @T table  
(  
  Name varchar(50),  
  Sales int  
)  
insert into @T values  
('Stella',   '2'),  
('Jennifer', '2'), 
('Greg',     '3')

3 个答案:

答案 0 :(得分:4)

如果已知quantity列中的最大值小于32,767,您可以使用Recursion生成数字并加入数字以获得结果。

/*******************************************
  Max Recursion Count in SQL Server is 32767
  Limitation of 32767 Numbers!
 ******************************************/
;WITH Numbers (Number) AS 
(
    SELECT 1 
    UNION ALL
    SELECT 1 + Number FROM Numbers WHERE Number < 100
)
SELECT  m.Name,
        Quantity = 1
  FROM  MyTable m 
        JOIN @numbers n ON m.Quantity <= n.Number
OPTION (MAXRECURSION  32767);

答案 1 :(得分:2)

您可能希望有一个预先填充的数字表来执行此操作:

declare @T table (  
  Name varchar(50),  
  Sales int  
)  

declare @numbers table (
  Number int
)

insert into @numbers values (1)
insert into @numbers values (2)
insert into @numbers values (3)
insert into @numbers values (4)
-- Etc... up to however many numbers is the max possible value for sales...

insert into @T values ('Stella',   '2')  
insert into @T values ('Jennifer', '2') 
insert into @T values ('Greg',     '3')

SELECT
    t.Name,
    1 AS Sales
FROM
    @T t JOIN
    @numbers n ON
        t.Sales >= n.Number
ORDER BY t.Name

你可以这样做,但我不确定为什么你会想要这样做。

答案 2 :(得分:2)

使用递归并借用Michael Fredrickson的设置代码:

declare @T table (  
  Name varchar(50),  
  Sales int  
)

insert into @T values ('Stella',   '2')  
insert into @T values ('Jennifer', '2') 
insert into @T values ('Greg',     '3')

-- Recursive verion
;with People (Name, Sales) as
(
    select Name, Sales
    from @T
    union all
    select Name, Sales - 1
    from People
    where Sales - 1 > 0
)
select Name, 1 as Quantity
from People
option (maxrecursion 0) -- Recurse without limit

这似乎在我的盒子上运行得更快(根据查询计划,比Michael Fredrickson快5倍,但有更多逻辑读取),并不重要。