1

我有一个包含三列的表,其中包含标识、名称和位置的 ID,对于这些列,我的值为

(1,'RAM','CA'), 
(2,'SAM','IA'),
(3,'PAM','MI')
etc....

现在想要获得 100 行,比如说在第 3 行之后,第 4 行应该再次以相同的名称和相同的位置开始,但添加一个值,例如第 4 行将是 (4,'RAM1','CA1'),类似第 5 行(5,'SAM1','IA1')和第 6 行的值(6,'PAM1','MI1')。同样对于第 7 行,它应该给出值(7,'RAM2','CA2'),依此类推。所以它应该像这样一直持续到第 100 行,因为我需要编写代码,我无法弄清楚,请你帮帮我。

谢谢, 阿帕兰吉特

4

2 回答 2

1

尝试这个:

小提琴演示

--Your table
create table t (id int identity(1,1), col1 varchar(10),
                                  col2 varchar(10))
--Insert query
insert into t
select c1 + case when number = 1 then '' else convert(varchar(10),number-1) end col1,
       c2 + case when number = 1 then '' else convert(varchar(10),number-1) end col2
from master..spt_values cross join 
    (values ('RAM','CA'),('SAM','IA'),('PAM','MI')) AS temp (c1,c2)
where type='p' and number between 1 and 100

--Results
|  ID |  COL1 | COL2 |
------|-------|------|--
| 1 |   RAM |   CA |
| 2 |   SAM |   IA |
| 3 |   PAM |   MI |
| 4 |  RAM1 |  CA1 |
| 5 |  SAM1 |  IA1 |
| 6 |  PAM1 |  MI1 |
| 7 |  RAM2 |  CA2 |
| 8 |  SAM2 |  IA2 |
| 9 |  PAM2 |  MI2 |
| 10 |  RAM3 |  CA3 |
| 11 |  SAM3 |  IA3 |
| 12 |  PAM3 |  MI3 |
...
于 2013-10-03T07:39:01.903 回答
0

使用递归 CTE你可以尝试类似

DECLARE @Table TABLE(
        ID INT IDENTITY(1,1),
        [name] VARCHAR(20),
        location varchar(20)
)
INSERT INTO @Table VALUES ('RAM','CA'), ('SAM','IA'), ('PAM','MI')

DECLARE @NumberOfRows INT = 100

;WITH RowIDs AS (
        SELECT  1 RowID
        UNION ALL
        SELECT RowID + 1
        FROM    RowIDs
        WHERE   RowID + 1 <= @NumberOfRows
)
, JoinIDs AS (
        SELECT  RowID,
                ((RowID - 1) % 3 + 1) JoinID
        FROM    RowIDs
)
SELECT  j.RowID,
        t.name,
        t.location

FROM    JoinIDs j INNER JOIN
        @Table t    ON  j.JoinID = t.ID
OPTION (MAXRECURSION 0)

SQL 小提琴演示

于 2013-10-03T07:43:42.010 回答