拆分数据行的问题
记录如下:
1 椅子 10
2 凳子 5
............
............
如何把所有数据根据总数量拆分成单条数据,如椅子有10把,拆分形成10条数据,每条数据一把椅子。
[解决办法]
--> 测试数据:[tb]IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb]GO CREATE TABLE [tb]([id] INT,[name] VARCHAR(4),[num] INT)INSERT [tb]SELECT 1,'椅子',10 UNION ALLSELECT 2,'凳子',5--------------开始查询--------------------------SELECT tb.*,s.number FROM [tb],master..spt_values s WHERE tb.num>s.number AND s.TYPE='p' ----------------结果----------------------------/* id name num number----------- ---- ----------- -----------1 椅子 10 01 椅子 10 11 椅子 10 21 椅子 10 31 椅子 10 41 椅子 10 51 椅子 10 61 椅子 10 71 椅子 10 81 椅子 10 92 凳子 5 02 凳子 5 12 凳子 5 22 凳子 5 32 凳子 5 4(15 行受影响)*/
[解决办法]
declare @table table( id int, name nvarchar(10), [count] int)insert @tableselect 1, N'椅子', 10 union allselect 2, N'凳子', 5 select rowno=row_number() over(order by (select 1)), id,name,cntfrom @table aouter apply(select top(a.[count]) [cnt]=1 from master..spt_values where type = 'p') b