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

拆分数据行的问题
记录如下:

1 椅子 10
2 凳子 5  
............
............

如何把所有数据根据总数量拆分成单条数据,如椅子有10把,拆分形成10条数据,每条数据一把椅子。

------解决方案--------------------
SQL code
--> 测试数据:[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 ALL
SELECT 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          0
1           椅子   10          1
1           椅子   10          2
1           椅子   10          3
1           椅子   10          4
1           椅子   10          5
1           椅子   10          6
1           椅子   10          7
1           椅子   10          8
1           椅子   10          9
2           凳子   5           0
2           凳子   5           1
2           凳子   5           2
2           凳子   5           3
2           凳子   5           4

(15 行受影响)

*/

------解决方案--------------------
SQL code
declare @table table
(
    id int,
    name nvarchar(10),
    [count] int
)
insert @table
select 1, N'椅子', 10 union all
select 2, N'凳子', 5  

select
    rowno=row_number() over(order by (select 1)), id,name,cnt
from @table a
outer apply
(select top(a.[count]) [cnt]=1 from master..spt_values where type = 'p') b