我正在尝试创建一个基于现有表的新视图。我希望这个新视图有插入的记录。
这是原始表,称为population
:
Agency Year Total PopGroup
01 2017 3467 3C
01 2018 3444 3C
01 2019 3567 3C
02 2017 1000 1C
02 2018 1354 1C
02 2019 1333 1C
03 2017 6784 2C
03 2018 3453 2C
04 2017 3333 2C
如果一个机构有2019年的一行,我想复制这一行并称之为2020年(基本上,2020年的估计人口)。下面是我的视图想要的结果:
Agency Year Total PopGroup
01 2017 3467 3C
01 2018 3444 3C
01 2019 3567 3C
01 2020 3567 3C
02 2017 1000 1C
02 2018 1354 1C
02 2019 1333 1C
02 2020 1333 1C
03 2017 6784 2C
03 2018 3453 2C
04 2017 3333 2C
这是我尝试创建视图的代码:
Use MY_PROJECTS
Go
CREATE VIEW population_w2020Estimates AS
SELECT *
FROM [MY_PROJECTS].[dbo].[population]
WHERE Year in (2017,2018,2019)
GO
INSERT INTO population_w2020Estimates (Agency, Year, Total, PopGroup)
SELECT Agency, 2020 as Year, Total, PopGroup
FROM population_w2020Estimates
视图已创建,但插入失败,出现以下错误:
Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object...
我正在使用Microsoft SQL Server Management Studio.
您正在为population_w2020Estimates
视图中的每个当前行创建一个带有2020的新行。因此,对于01
机构来说,SELECT
将带回三排- 2017年,2018年,2019年。因此出现了主键错误。试一试:
INSERT INTO population_w2020Estimates (Agency, Year, Total, PopGroup)
SELECT Agency, 2020 as Year, Total, PopGroup
FROM population_w2020Estimates
WHERE Year = 2019
如果您只想让视图显示每个机构的额外一行,作为从2019年数据派生的2020年数据,则创建如下视图:
CREATE VIEW population_w2020Estimates AS
SELECT *
FROM [population]
WHERE Year in (2017,2018,2019)
union all
SELECT Agency, 2020 as Year, Total, PopGroup
FROM population where year='2019'