假设我有下表:
camp_1, camp_2
0, 048
00, 048
000, 042
000, 043
我现在想将这些值插入到新表dim_promotion中,它应该如下所示:
PromotionID, CampaignID, CouponID
1, 1, 1
2, 2, 1,
3, 3, 2,
4, 3, 3
我知道如何填写表格(dim_campaigns和dim_coupons,它们支持CampaignID和CouponID):
INSERT INTO [REPORTING].dbo.dim_campaigns
SELECT DISTINCT
camp_2 AS CampaignID
FROM [reporting2].[dbo].[reporting_rawdata_v2]
相应三个表(dim_coupons,dim_campaigns和dim_promotion)的主键都设置为“Identity Specification = YES”
那我怎么填补dim_promotion?什么是自然秩序? FIrst派生dim_campaigns和dim_coupons,然后将其变为dim_promotion或反过来?
编辑:我有以下数据库模型(仅摘录)我只是指黄色字段。
现在,我们只有大表(rawdatatbl)存储所有数据(CampaignCode,CouponCode,Campaign Name,CouponName)。这不是真正有效的,这就是我想强制重组模型的原因(见截图)。因此,由于目前数据根本不包含任何ID,我需要ID来填充新表dim_campaigns和dim_coupons。这意味着:要填充dim_campaigns,我将在当前的rawdatatbl上运行SELECT DISTINCT campaign_code,然后将其插入dim_campaigns(CampaignID通过使用auto_increment自动填充,CampaignName填充'Dummy')。我可以为dim_coupons做同样的事情。但是,如何使用此数据初始化Dim_promotion表?或者,将当前数据从rawdatatbl转换为ID的最佳流程是什么?
答案 0 :(得分:0)
一种可能的方法是: -
---- insert your all distinct Campaign data
Insert Into dim_campaigns(CampaignCode,CampaignName)
Select Distinct
cm.CampaignCode
,cm.CampaignName
From rawdatatbl As cm
---- insert your all distinct Coupon data
Insert Into dim_coupons(CouponCode,CouponName)
Select Distinct
c.CouponCode
,c.CouponName
From rawdatatbl As c
Declare @Total Int
,@Inc Int
,@RowId Int
,@CampaignCode Varchar(100)
,@CouponCode Varchar(100)
----Primary keys
,@CampaignId Int
,@CouponId Int
,@PromotionID Int
Select @CampaignCode = ''
,@CouponCode = ''
----loop through one by one and take necessary action
Select @Total = Count(1)
,@Inc = 0
,@RowId = 0
From rawdatatbl As c With (Nolock)
While (@Inc < @Total)
Begin
Select Top 1
@RowId = [TableUniqueId]
,@CampaignCode = c.CampaignCode
,@CouponCode = c.CouponCode
---- others columns
From rawdatatbl As c
Where [TableUniqueId] > @RowId
Order By [TableUniqueId] Asc
Select @CampaignId = dc.CampaignId
From dim_campaigns As dc
Where dc.CampaignCode = @CampaignCode
Select @CouponId = dc.CouponId
From dim_coupons As dc
Where dc.CouponCode = @CouponCode
If (@CampaignId > 0 And @CouponId > 0)
Begin
Insert Into dim_promotion(CampaignID,CouponID)
Select @CampaignId,@CouponId
Select @PromotionID = @@Identity
---- other operation insert/update based on @PromotionID you can do here.
End
Select @Inc = @Inc + 1
,@CampaignCode = ''
,@CouponCode = ''
,@CampaignId = 0
,@CouponId = 0
End