如何根据SQL中的数量显示重复项?

时间:2015-01-19 05:04:17

标签: sql sql-server-2008

我有一个包含字段内容的表格:

item    qty
-----  -----
tea      2

我想显示如下

item   qty
----  ------
tea     1 
tea     1

如何像上面那样创建SQL查询?

2 个答案:

答案 0 :(得分:0)

使用Recursive CTE

;WITH cte
     AS (SELECT item,qty,1 num from yourtable
         UNION ALL
         SELECT item,
                qty,
                num + 1
         FROM   cte
         WHERE  num < qty)
SELECT item,
       1 as Qty
FROM   cte 

或使用Tally表。与Recursive CTE

相比,它会有更好的表现
;WITH e1(n) AS
(
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), -- 10
     e2(n)
     AS (SELECT 1 FROM   e1 CROSS JOIN e1 AS b) -- 10*10
     --e3(n) AS (SELECT 1 FROM e2 CROSS JOIN e2 AS b), -- 100*100
SELECT a.item,
       1 AS qty
FROM   yourtable a
       JOIN (SELECT n = Row_number()OVER (ORDER BY n)
             FROM   e2) b
         ON b.n <= a.qty; 

注意:根据Quantity,您可能需要增加CTE的cross join

查看here了解详情

答案 1 :(得分:0)

样本表

CREATE TABLE #TEMP(ITEM VARCHAR(10),QTY INT)    

INSERT INTO #TEMP
SELECT 'TEA',2
UNION ALL
SELECT 'COFFEE',3

如果您有多于一种类型的商品并且想要获得商品数量,则可以使用以下查询。

<强> QUERY

;WITH CTE AS      
(
    -- You will get each ITEM from your table
    SELECT ITEM,  QTY, 1     NEWQTY
     FROM #TEMP 
     UNION ALL
     -- Here it will loop and shows the repeated values of each ITEM 
     SELECT C1.ITEM,C1.QTY,NEWQTY + 1
     FROM   CTE C1
     JOIN #TEMP T1 ON C1.item= T1.ITEM
     WHERE  C1.NEWQTY < T1.qty
)
SELECT ITEM,
       1 QTY
FROM   CTE 
ORDER BY ITEM