2015-08-28 52 views
0

我正在使用MS SQL 2008.我不知道是否有可能產生一個基於數量顯示結果的查詢。請讓我解釋我想要它的樣子。SQL查詢 - 列表數量基於數量

比方說,我有這樣的桌子和一個簡單的查詢到列表中的記錄:

Table = "Table1" 
Product = varchar(100) 
Qty = Int 

Select Product, ProductDesc, Qty FROM Table1 

Results: 
Product  ProductDesc  Qty 
ABC1  Test1   2 
ABC2  Test2   3 

有沒有辦法基礎上,數量列和上市的像下面這樣的結果記錄數來查詢:

**Wanted Results:** 
Product  ProductDesc  Number 
ABC1  Test1   1 
ABC1  Test1   2 
ABC2  Test2   1 
ABC2  Test2   2 
ABC2  Test2   3 

回答

1

使用遞歸查詢:

with p 
as (
    select product,productDesc, 1 as number from products 
    union all 
    select products.product,products.productDesc, p.number+1 as number from products 
     inner join p on products.product = p.product 
     where number<qty 
    ) 
select * from p order by product 

一個簡單的例子:fiddle

+0

謝謝!當我嘗試點擊示例鏈接提琴時,出現此錯誤:訪問/sqlfiddle/sqlfiddle/index.html時出現問題。原因:未找到。任何想法爲什麼? – Milacay

+0

但我通常訪問它 –

+0

也許我的電腦有問題。謝謝! – Milacay

1

不知道這是正確的做法,但應該工作

with cte as 
(
select 1 as num 
union all 
select num+1 from cte where num < 1000 -- max qty from your table 
), comb as 
(
select Product,ProductDesc,num from 
(select distinct Product,ProductDesc from Table1) t cross join cte c 
) 
select * from Table1 t 
inner join comb c on t.Product = c.Product 
and t.ProductDesc = c.ProductDesc 
and c.qty <= t.num 

對於simplicit我用Recursive CTE來生成號碼,但它可能是一個性能問題。檢查here爲不同的方法來生成沒有循環的數字。