列出每个数量的行数

时间:2014-02-20 15:26:36

标签: sql sql-server tsql

我可能在想这个。我有一个包含NameTicket Quantity列的简单表格。我想输出每个购买数量的名称的行列表。见下面的例子。

表格

Name           Quantity
-----------------------
Bob            1
Joe            2
Sally          1

输出:

Bob
Joe
Joe
Sally

我如何在TSQL中实现这一目标?

1 个答案:

答案 0 :(得分:2)

<强> SETUP:

DECLARE @table TABLE (
    NAME VARCHAR(10),
    Quantity INT
    )

INSERT INTO @table
SELECT 'Bob',   1 UNION ALL
SELECT 'Joe',   2 UNION ALL
SELECT 'Sally', 1

递归CTE

;WITH Members (
    NAME,
    Quantity
    )
AS (
    -- Base case
    SELECT NAME,
        Quantity
    FROM @table

    UNION ALL

    -- Recursive
    SELECT NAME,
        Members.Quantity - 1
    FROM Members
    WHERE Members.Quantity > 1
    )
SELECT NAME
FROM Members
OPTION (MAXRECURSION 0)
ORDER BY 1

<强>结果:

Bob
Joe
Joe
Sally

或者你可以(根据@Martin Smith的建议):

DECLARE @numbers TABLE (number INT)

INSERT INTO @numbers (number)
VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)

<强>最后:

SELECT NAME
FROM @table t
INNER JOIN @numbers n ON n.number <= t.Quantity
ORDER BY 1

<强>结果:

Bob
Joe
Joe
Sally

<小时/> 如果你真的喜欢递归CTE(因为它们闻起来很好),你可以使用递归CTE构建数字表。您应该使用物理表而不是变量表,因为您不必每次都构建它们。

;WITH Numbers (Value)
AS (
    -- Base case
    SELECT 32767 Value

    UNION ALL

    -- Recursive
    SELECT Numbers.Value - 1
    FROM Numbers
    WHERE Numbers.Value > 1
    )
INSERT INTO @numbers (number)
SELECT Value
FROM Numbers
OPTION (MAXRECURSION 32767)