sql - SQL Auto-populate ID column based on another column
问题描述
I have a workflow where source table is used to populate the destination table.
I have tried to simulate this workflow in the code below.
-- creating/populating source table
CREATE TABLE #SourceTable
(
CampaignName VARCHAR(50),
CustomerNumber INT
)
INSERT INTO #SourceTable
VALUES ('Campaign1', 1111), ('Campaign1', 2222), ('Campaign1', 3333),
('Campaign2', 4444), ('Campaign2', 2222), ('Campaign2', 1111)
-- create/populate destination table
CREATE TABLE #DestinationTable
(
CampaignID INT,
CampaignName VARCHAR(50),
CustomerNumber INT
)
-- Simulating populating the #DestinationTable
INSERT INTO #DestinationTable (CampaignName, CustomerNumber)
SELECT CampaignName, CustomerNumber
FROM #SourceTable
The source table will get created in some way, but then it is used to populate the destination table in the same way as my sample code.
The destination table is at CustomerNumber level. I want to autopopulate an ID field (without the user having to code it in) that will give a new number at CampaignName level.
So for example, I want the output of the #DestinationTable
to be:
CampaignID CampaignName CustomerNumber
------------------------------------------
1 Campaign1 1111
1 Campaign1 2222
1 Campaign1 3333
2 Campaign2 4444
2 Campaign2 2222
2 Campaign2 1111
But I need the CampaignID
column to be auto-populated whenever new rows are being inserted, like an IDENTITY
column, but instead of giving each row a number, I need it to give each CampaignName
a new number.
Is that possible?
Thanks
解决方案
这可以使用dense_rank()
.
SELECT dense_rank() over (order by CampaignName) as rn, CampaignName, CustomerNumber
FROM #SourceTable
要验证您的customer number
姓名是否campaign
已经存在于您的目的地,请使用not exists
关键字。
SELECT dense_rank() over (order by t1.CampaignName) as rn, t1.CampaignName, t1.CustomerNumber
FROM #SourceTable t1
WHERE not exists (select 1 from #DestinationTable t2
where t2.CustomerNumber = t1.CustomerNumber and t2.CampaignName = t1.CampaignName)
推荐阅读
- android - 如何在android中识别正确的微码
- google-bigquery - BigQuery:带有通配符表的“SELECT * 将扩展到零列”
- android - 用于多重访问的 SQLITE DATABASE
- c# - json 列表 MVC ajax 控制器
- tomcat - 无法在数字海洋的 CentOS 服务器中启动 tomcat
- asp.net - 有没有办法在 IIS 中托管的网站中查看实际的应用程序错误?
- c# - Botframework V4:如何发送视频附件?
- reactjs - 如何在反应中设置动态数据?
- apache-kafka-streams - 编译后更改 Kafka Streams 配置
- css - 采用高度而不是宽度的响应式 iframe(youtube/vimeo 嵌入)