我试图在仅允许t-sql的系统上运行导出。我知道足够多的php来进行foreach循环,但是我不太了解t-sql来生成给定数量的多行。我需要一个结果来列出具有“ 1 of 4”的项目列表,例如结果中包含的数据
给像这样的桌子
orderid, product, quantity
1000,ball,3
1001,bike,4
1002,hat,2
Run Code Online (Sandbox Code Playgroud)
我如何获得选择查询结果,例如:
orderid,item_num,total_items,产品
1000、1、3,球
1000、2、3,球
1000、3、3,球
1001,1,4,自行车
1001,2,4,自行车
1001、3、4,自行车
1001、4、4,自行车
1002,1,2,帽子
1002,2,2,帽子
您可以借助辅助数字表来完成此操作。
;WITH T(orderid, product, quantity) AS
(
select 1000,'ball',3 union all
select 1001,'bike',4 union all
select 1002,'hat',2
)
SELECT orderid, number as item_num, quantity as total_items, product
FROM T
JOIN master..spt_values on number> 0 and number <= quantity
where type='P'
Run Code Online (Sandbox Code Playgroud)
注意:上面的代码使用了表格 - 这仅用于演示目的,我建议您使用此处的一种技术master..spt_values创建自己的统计表。