如何制作重复记录并重新索引列值?

时间:2018-03-30 03:40:56

标签: sql sql-server sql-server-2005 common-table-expression

这是一张表:

declare @t table(id int,name varchar(10),count int,quantity int)

insert @t(id,name,count,quantity) values( 1,'aaa',1,100)
insert @t(id,name,count,quantity) values( 3,'bbb',3,200)
insert @t(id,name,count,quantity) values( 2,'ccc',2,50)
insert @t(id,name,count,quantity) values( 6,'ddd',1,300)
insert @t(id,name,count,quantity) values( 5,'eee',5,20)

SELECT * FROM @t

输出:

id  name    count   quantity
1   aaa     1       100
3   bbb     3       200
2   ccc     2       50
6   ddd     1       300
5   eee     5       20

如何通过sql-server语句获得以下结果,一个简单的cte sql server语句是否有效?

id  name    count   quantity
1   aaa     1       100
3   bbb     1       200
3   bbb     2       200
3   bbb     3       200
2   ccc     1       50
2   ccc     2       50
6   ddd     1       300
5   eee     1       20
5   eee     2       20
5   eee     3       20
5   eee     4       20
5   eee     5       20

谢谢!

2 个答案:

答案 0 :(得分:1)

尝试使用master数据库中的SPT_Values表。

SELECT t.id, t.name, c.number as [count], t.quantity
FROM @t t
CROSS APPLY
(SELECT * FROM master.dbo.spt_values where type='P' 
and number between 1 and t.[count] )c

<强>结果:

+----+------+-------+----------+
| id | name | count | quantity |
+----+------+-------+----------+
|  1 | aaa  |     1 |      100 |
|  3 | bbb  |     1 |      200 |
|  3 | bbb  |     2 |      200 |
|  3 | bbb  |     3 |      200 |
|  2 | ccc  |     1 |       50 |
|  2 | ccc  |     2 |       50 |
|  6 | ddd  |     1 |      300 |
|  5 | eee  |     1 |       20 |
|  5 | eee  |     2 |       20 |
|  5 | eee  |     3 |       20 |
|  5 | eee  |     4 |       20 |
|  5 | eee  |     5 |       20 |
+----+------+-------+----------+

答案 1 :(得分:1)

感谢米尔扎先生的帮助@Shakeer Mirza,我已将此编码为此。

declare @t TABLE (id int,name varchar(10),count int,quantity int)

insert @t(id,name,count,quantity) values( 1,'aaa',1,100)
insert @t(id,name,count,quantity) values( 3,'bbb',3,200)
insert @t(id,name,count,quantity) values( 2,'ccc',2,50)
insert @t(id,name,count,quantity) values( 6,'ddd',1,300)
insert @t(id,name,count,quantity) values( 5,'eee',5,20)

--SELECT * FROM @t

DECLARE @maxcount INT
SET @maxcount = 10000;--if count exceed 2048
;WITH CTE AS (
                       SELECT 1 AS number
                       UNION ALL
                       SELECT number + 1
                       FROM   CTE
                       WHERE  number < @maxcount
                   )

SELECT t.id, t.name, c.number as [count], t.quantity
FROM @t t
CROSS APPLY
(SELECT * FROM CTE where number between 1 and t.[count] )c
ORDER BY t.id,c.number
option (MAXRECURSION 0)-- if recursion exceed 100