0

例如,我有第一个表,我想使用第一个表填充第二个表。

           Table A              
 Name   A    B   C   D
-----------------------
 name1  a1  b1  c1  d1
 name2  a2  b2  c2  d2



      Table B (Desired Format)      
  ID    Name    Code
 ----------------------
  1     name1   a1
  2     name1   b1
  3     name1   c1
  4     name1   d1
  5     name2   a2
  6     name2   b2
  7     name2   c2
  8     name2   d2  

根据@Surendra Nath GM 的建议,我尝试了这个

   DECLARE @counter as int
   SET @counter = 1;
  ;WITH Actual AS 
  (
  SELECT ROW_NUMBER() OVER( ORDER BY IDKEY) as ID  FROM Northwind.dbo.Table1
  WHERE 
   ),FIRST AS
  (
  SELECT ((ROW_NUMBER() OVER( ORDER BY IDKEY))*4-3) AS ID,Name, A 
  FROM Northwind.dbo.Table1

   ),SECOND AS
  (
   SELECT ((ROW_NUMBER() OVER( ORDER BY IDKEY))*4-2) AS ID, Name ,B
  from Northwind.dbo.Table1
   ), NEXT AS
  (
 SELECT ((ROW_NUMBER() OVER( ORDER BY IDKEY))*4-1) AS ID, Name, C
  from Northwind.dbo.Table1next
 ), ________ as
 (
  SELECT ((ROW_NUMBER() OVER( ORDER BY IDKEY))*4) AS ID, Name, D
from Northwind.dbo.Table1
 )

 @counter = @counter+1;
  )
  SELECT * FROM FIRST
  UNION ALL
  SELECT * FROM SECOND
  UNION ALL
  SELECT * FROM NEXT
  UNION ALL
  SELECT * FROM _________
  ORDER BY ID

在这里,我在“SECOND AS”之后使用什么。我尝试编写“THIRD AS”,但显然不存在这样的命令,因此经过一番搜索,我可以使用“NEXT AS”编写第三行,但我完全不知道如何插入第四行。

我知道我可以简单地为 A、B、C 和 D 中的每一个编写 4 个插入命令,但是我将按以下顺序获得非代码,这是不需要的:

Table B(NOT DESIRED IN THIS FORMAT)     
  ID    Name    Code
 ----------------------
  1     name1   a1
  2     name2   a2
  3     name1   b1
  4     name2   b2
  5     name1   c1
  6     name2   c2
  7     name1   d1
  8     name2   d2  

此外,可以使用简单的循环来实现所需的格式,但在我正在处理的项目中,大约有 200000 行,简单的循环方法需要很多时间。所以,我想用 CTE 来做。请帮忙。

4

2 回答 2

1

你可以用两个插入来做到这一点:

insert into tableB(A, B)
    select A1, B1
    from tableA;

insert into tableB(A, B)
    select A2, B2
    from tableA;

或者将表与一个插入合并:

insert into tableB(A, B)
    select A1, B1
    from tableA union all
    select A2, B2
    from tableA;

这假设它id被定义为id int indentity(1, 1)自动递增。

如果没有,您可以将其分配为:

insert into tableB(id, A, B)
    select row_number() over (order by (select NULL)) as id, A1, B1
    from (select A1, B1
          from tableA union all
          select A2, B2
          from tableA
         ) t
于 2013-06-28T05:17:11.120 回答
0

在这里获取 ID 将是棘手的部分,为了做到这一点并使用设置的操作,您必须将作业分成两部分并为 A1、B1 的选择生成奇数 ID,并为 A2 的选择生成事件 ID ,B2

如下图所示

;WITH Actual AS 
(
  SELECT ROW_NUMBER() OVER( ORDER BY Name) as RN, * FROM Table1
),FIRST AS
(
  SELECT ((RN*2)-1) AS ID,A1,B1 
  FROM TABLE1
  ORDER BY RN
),SECOND AS
(
  SELECT (RN*2) AS ID,A2,B2
  FROM TABLE1
  ORDER BY RN
)
SELECT * FROM FIRST
UNION ALL
SELECT * FROM SECOND

如果您有四列,那么您可以使用以下查询

;WITH Actual AS 
(
  SELECT ROW_NUMBER() OVER( ORDER BY Name) as RN, * FROM Table1
),FIRST AS
(
  SELECT ((RN*2)-1) AS ID,A1,B1,C1,D1
  FROM TABLE1
  ORDER BY RN
),SECOND AS
(
  SELECT (RN*2) AS ID,A2,B2,C2,D2
  FROM TABLE1
  ORDER BY RN
)
SELECT * FROM FIRST
UNION ALL
SELECT * FROM SECOND
于 2013-06-28T05:26:00.387 回答