SQL简单按数量突破

时间:2012-08-13 16:35:09

标签: sql-server tsql

我想在SQL中按数量执行简单的分解。

我有如下:

表名:产品

product    quantity
=======    ========
Car        2
Bike       1

结果:

Car
Car
Bike

谢谢!

2 个答案:

答案 0 :(得分:2)

一种解决方案是加入数字表。这可以重复行quantity次。在T-SQL中,可以使用递归CTE生成数字列表:

; with  Numbers as
        (
        select  max(quantity) as nr
        from    YourTable
        union all
        select  nr - 1
        from    Numbers
        where   nr > 1
        )
select  yt.product
from    YourTable yt
join    Numbers nr
on      nr.nr <= yt.quantity
option  (maxrecursion 0)

Live example at SQL Fiddle.

答案 1 :(得分:1)

这是一个非CTE答案,说明你应该使用CTE的原因:)

MAIN TABLE

DECLARE @table TABLE
    (
      ID INT IDENTITY,
      Product VARCHAR(20),
      Quantity INT
    )

OUT TABLE

DECLARE @outtable TABLE
    (
      ID INT IDENTITY,
      Product VARCHAR(20)
    )

测试数据

INSERT  INTO @table
        (
          Product,
          Quantity
        )
        SELECT  'Car',
                2
        UNION ALL
        SELECT  'Bike',
                1

主要查询

DECLARE @counter INT,
    @maxcounter INT,
    @curproduct INT
SELECT TOP 1
        @curproduct = id
FROM    @table 

WHILE EXISTS ( SELECT TOP 1
                        1
               FROM     @table
               WHERE    ID >= @curproduct ) 
    BEGIN
        SELECT  @counter = 1,
                @maxcounter = quantity
        FROM    @table
        WHERE   ID = @curproduct
        WHILE @counter <= @maxcounter 
            BEGIN
                INSERT  INTO @outtable
                        (
                          Product
                        )
                        SELECT  product
                        FROM    @table
                        WHERE   id = @curproduct
                SET @counter = @counter + 1
            END
        SET @curproduct = @curproduct + 1 
    END

<强>最后

SELECT  *
FROM    @outtable