Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL查询-根据数量列出项目数_Sql - Fatal编程技术网

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

SQL查询-根据数量列出项目数,sql,Sql,我正在使用MS SQL 2008。我想知道是否可以生成一个查询,根据数量显示结果。请让我解释一下我希望它是什么样子 比方说,我有这个表和一个简单的查询来列出记录: Table = "Table1" Product = varchar(100) Qty = Int Select Product, ProductDesc, Qty FROM Table1 Results: Product ProductDesc Qty ABC1 Test1 2

我正在使用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   

不确定这是正确的方法,但应该有效

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
为了简单起见,我使用了递归CTE来生成数字,但这可能是一个性能问题。检查不同的方法以生成无循环的数字。

使用递归查询:

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时,我遇到了以下错误:访问/sqlfiddle/sqlfiddle/index.html时出现问题。原因:找不到。知道为什么吗?但我正常访问它可能我的电脑有问题。非常感谢。