SQL:展开集合

时间:2010-03-02 19:36:47

标签: sql tsql

假设我在SQL中有一个这样的集合:

    Product | Quantity
       A         1
       B         2

我希望(在单个SELECT语句中)将其转换为:

    Product 
       A    
       B    
       B

有人能指出我(最好是T-SQL),这是一个如何做到这一点的技巧?

3 个答案:

答案 0 :(得分:6)

您需要一个中间数字表或一个表值函数(如果您可以使用该选项),它将产生数字。

假设您有一个Numbers表,其填充方式如下:

    Number
    ------
         1
         2
       ...
    100000

(或者你需要的那么大,而且有efficient mechanisms for generating a numbers table of large size

然后您将发出以下查询:

select
    p.Product
from
    Products as p
        inner join Numbers as n on n.Number <= p.Quantity 

这会产生你想要的结果。

数字表在SQL中非常有用,并且Itzik Ben-Gan在他的书中(在他的网站上列出)进入了它和其他伟大的查询技术。我强烈推荐他们。

答案 1 :(得分:1)

select ProductName, Quantity from Product

产品名称数量


A 1

B 2

C 4

这是一个选择,如你所愿(sql server 2005):

with result (ProductName, Q)
as
(
    select ProductName, 1 from Product where Quantity > 0
    union all
    select p1.ProductName, result.q + 1 from Product p1
    inner join result on result.ProductName = p1.ProductName
    where result.q < p1.Quantity 
)
select p2.ProductName from Product p2
    inner join result on result.ProductName = p2.ProductName
order by 1
OPTION (MAXRECURSION 0);

产品名称

一个


ç
ç
ç
C

答案 2 :(得分:-1)

试试CURSOR?

DECLARE @Cursor CURSOR
DECLARE @Product varchar(50)

SET @Cursor = CURSOR FOR
SELECT Product FROM dbo._YourTable

OPEN @Cursor

FETCH NEXT FROM @Cursor INTO @Product 

WHILE @@FETCH_STATUS = 0
BEGIN

DECLARE @Count int
SET @Count = 0

DECLARE @Quantity int
SET @Quantity = SELECT Quantity FROM dbo._YourTable WHERE Product = @Product

WHILE @Count < @Quantity
BEGIN

SELECT @Product as Product
@Count = @Count + 1

END

FETCH NEXT FROM @Cursor INTO @Product
END

DEALLOCATE @Cursor