我已经尝试了几天了,我找不到合适的解决方案。
我有两张桌子:
-Adgroups:包含带有uniqueAdgroupID和AdgroupName的广告组列表。该表有重复的名称。
-Adgroup_Campaigns:包含一个广告系列列表,其中包含uniqueCampaignID和table1中的uniqueAdgroupId。
我需要做的是在表Adgroups中查找所有重复的名称,我使用以下查询:
SELECT
o.[AdGroup_Id], o.[AdGroup]
FROM (
SELECT [AdGroup], COUNT(*) as intCount
FROM [dbo].[AdGroup]
GROUP BY [AdGroup]
HAVING COUNT(*) > 1
)
AS d
INNER JOIN [dbo].[AdGroup] o ON o.[AdGroup] = d.[AdGroup]
返回如下列表:
Adgroup_Id AdGroup
----------- ----------
1 PRE-MAS--v2-LP2
2 PRE-MAS--v2-LP2
5 PRE-MAS--v2-LP2
6 UNI-A-v2-LP2
8 UNI-A-v2-LP2
10 UNI-A-v2-LP2
16 PRE-UNI-v2-LP2
17 PRE-UNI-v2-LP2
20 PRE-UNI-v2-LP2
现在我在表Adgroup_Campaigns中交叉检查AdGroupId在重复广告组列表中的所有记录,我使用以下查询:
SELECT * FROM
(
SELECT
o.[AdGroup_Id], o.[AdGroup]
FROM (
SELECT [AdGroup], COUNT(*) as intCount
FROM [dbo].[AdGroup]
GROUP BY [AdGroup]
HAVING COUNT(*) > 1
)
AS d
INNER JOIN [dbo].[AdGroup] o ON o.[AdGroup] = d.[AdGroup]
)
AS x INNER JOIN [dbo].[AdGroupCampaignMapper] t
ON t.[AdGroup_Id] = x.[AdGroup_Id]
返回如下列表:
Adgroup_Id AdGroup Campaign_Id
----------- --------- ------------
1 PRE-MAS--v2-LP2 1
2 PRE-MAS--v2-LP2 3
5 PRE-MAS--v2-LP2 5
6 UNI-A-v2-LP2 6
8 UNI-A-v2-LP2 7
10 UNI-A-v2-LP2 8
16 PRE-UNI-v2-LP2 9
17 PRE-UNI-v2-LP2 10
20 PRE-UNI-v2-LP2 11
所以我需要的是一个实际更新表Adgroup_Campaigns中字段Adgroup_Id的查询,因此每组重复项都将Adgroup_Id作为该组的第一个ID,如下所示:
Adgroup_Id AdGroup Campaign_Id
----------- --------- ------------
1 PRE-MAS--v2-LP2 1
1 PRE-MAS--v2-LP2 3
1 PRE-MAS--v2-LP2 5
6 UNI-A-v2-LP2 6
6 UNI-A-v2-LP2 7
6 UNI-A-v2-LP2 8
16 PRE-UNI-v2-LP2 9
16 PRE-UNI-v2-LP2 10
16 PRE-UNI-v2-LP2 11
非常感谢任何帮助。
答案 0 :(得分:1)
您可以使用内部联接的更新
update a
set AdGroupCampaignMapper.Adgoup_Id = t.min_id
FROM [dbo].[AdGroupCampaignMapper] as a
INNER JOIN (
SELECT [AdGroup] , min([AdGroup_Id]) min_id, COUNT(*) as intCount
FROM [dbo].[AdGroup]
GROUP BY [AdGroup]
HAVING COUNT(*) > 1 ) t on . t.AdGroup = a.AdGroup