SQL For Each - 写入文件

时间:2017-03-03 11:45:13

标签: sql export

所以我们有一个生产表,其中包含以下数据(简单来说)

ID, Item, QTY
1,AAA,3
2,BBB,4

所以2个生产任务,一个数量为3,一个数量为4.我需要一个显示以下内容的导出文件(txt)

ID,Item
1,AAA
1,AAA
1,AAA
2,BBB
2,BBB
2,BBB
2,BBB

基本上,我需要一个文件,每个数量都有一行。这是因为我使用的第三方软件使用文件中的每一行来为任务创建票证/标签。

感谢上述任何帮助。

谢谢,

迪安

1 个答案:

答案 0 :(得分:1)

基本上,你需要一个数字表,所以你可以这样做:

select p.id, p.item
from production p join
     numbers n
     on n.n <= p.qty;

如果您的表有足够的行,那么将在许多数据库中使用的一个ANSI标准方法是:

select p.id, p.item
from production p join
     (select row_number() over (order by p.id) as n
      from production
     ) n
     on n.n <= p.qty;

还有其他特定于数据库的生成数字的方法。

另一种ANSI兼容方法是递归CTE:

with cte (id, item) as (
      select id, item, qty
      from production 
      union all
      select id, item, qty - 1
      from production
      where qty > 0
     )
select id, item
from cte;

(注意:有时需要recursive关键字。)