将表合并为一个具有连续ID的视图

时间:2018-04-04 10:08:11

标签: sql sql-server view

我有以下表格:

Answer1         |   Answer2     |   Answer3
AnswerID        |       ID      |   ID
QuestionnaireID |QuestionnaireId|   QuestID
EmployeeName    | Employeename  |   EmployeeName
PcName          |   PcName      |   PcName
Answer          |   AnswerText  |   Answer
AnswerDate      |   AnswerDate  |   Ans_Date

我想在MS SQL Server中创建View,我希望将这些值合并到一个带有固定fied但具有一个修改的视图中。 每个表都有从1开始的AnswerID(或ID)。我想要做的是让它不断增加,如果最后一个来自Answer1的AnswerId 等于例如。 1000,从answer2添加记录将更新Answer2.ID为Answer2.ID + 1000.

CREATE VIEW Answer
AS
SELECT  a.AnswerID ID,
    a.Answer Text,
    a.AnswerDate Date,
FROM    Answer1 a

我现在该怎么办?我猜JOIN不是做这种任务的方法。

谢谢

2 个答案:

答案 0 :(得分:0)

我不确定你为什么要这样做,因为从视图中返回新的id无论如何都不会对你有所帮助,但是如果你想要每个表的唯一id,你可以尝试跟随。

WITH TBL1 AS
(
 SELECT ROW_NUMBER() OVER(ORDER BY ID) [NewId], * FROM Answer1
),    
 TBL2 AS
(
  SELECT  ROW_NUMBER()  OVER(ORDER BY ID) 
     + (SELECT MAX([NewId]) FROM TBL1) AS [NewId2],* FROM Answer2
),    
TBL3 AS 
(
  SELECT  ROW_NUMBER()  OVER(ORDER BY ID) 
      + (SELECT MAX([NewId2]) FROM TBL2) AS RN2,* FROM Answer3
)
SELECT * FROM TBL1
UNION 
SELECT * FROM TBL2
UNION 
SELECT * FROM TBL3

答案 1 :(得分:0)

如果您想要连续值,为什么不使用row_number()并重新分配所有ID?

select AnswerID as ID, a.Answer as Text, a.AnswerDate as Date,
       row_number() over (order by which, id) as new_id
from ((select a.*, 1 as which from answer1 a) union all
      (select a.*, 2 as which from answer2 a) union all
      (select a.*, 3 as which from answer3 a)
     ) a;