日期:2014-05-18  浏览次数:20490 次

记录拆分
表1:
----------------
姓名 数量
a 2
b 1
c 3


表2:
-----------------
姓名 数量
a 1
a 1
b 1
c 1
c 1
c 1

需要从表1生成表2,表2事先不存在。表2的规律为,将表1的数量拆分为以1为数量的记录条数,比如表1中a只为2,则表2中生成2行a值,b为1则表2中b只有1行,c为3则c有3行,求SQL语句,谢谢!



------解决方案--------------------
好象有点难度,先顶后想。
------解决方案--------------------
用游标拆分,while插入表
------解决方案--------------------
。。。
最勺的办法。。。
尽量不用这种了```
------解决方案--------------------
用个临时表

SQL code
select top 1000 IDENTITY(int,1,1) as id into # from sysobjects a,sysobjects b

select 姓名,1 as 数量
into 表2
from 表1 a,# t
where a.数量>=t.id

drop table #

------解决方案--------------------
Haiwer的好办法,虽然有些局限,但思路不错。赞一个!
------解决方案--------------------
非常感谢!楼上2位。
------解决方案--------------------
SQL code
select 姓名,1 as 数量
into 表2
from 表1 a,(select t1.id+t2.id+t3.id+t4.id+t5.id+t6.id+t7.id+t8.id+t9.id+t10.id+1
            from  (select 0 as id union all select 1) t1,
                           (select 0 as id union all select 2) t2,
                            (select 0 as id union all select 4) t3,
                            (select 0 as id union all select 8) t4,
                            (select 0 as id union all select 16) t5,
                            (select 0 as id union all select 32) t6,
                             (select 0 as id union all select 64) t7,
                             (select 0 as id union all select 128) t8,
                              (select 0 as id union all select 256) t9,
                             (select 0 as id union all select 512) t10  )                           ) t
where a.数量>=t.id