SQL查询 - 根据数量列出项目数

时间:2015-08-28 17:15:23

标签: sql

我正在使用MS SQL 2008.我想知道是否可以生成一个基于数量显示结果的查询。请让我解释一下我希望它看起来像。

让我们说,我有这个表和一个简单的查询来列出记录:

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

Select Product, ProductDesc, Qty FROM Table1

Results:
Product     ProductDesc     Qty
ABC1        Test1           2
ABC2        Test2           3

有没有办法根据Qty列查询,并列出如下结果的记录数:

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

2 个答案:

答案 0 :(得分: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

为简单起见,我使用Recursive CTE生成数字,但这可能是性能问题。检查here以获取不带循环生成数字的不同方法。

答案 1 :(得分: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