Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --START OF PROCESS
- -- There are 7 steps
- --Step 1 Executes; exec BDM.GETBDMasterReferralData
- --step 2 Executes; exec bdm.GETBDMasterMatterBilledCollected
- --Step 3 Executes; exec BDM.GetBDMasterMatterDataFrom3E
- --step 4 Executes; exec bdm.GETBDMasterSource
- --Step 5 Executes; exec bdm.ValidateBDMasterSourceData
- --step 6 Executes; exec [BDM].[proc_UnPublishedBDMasterMatterData] 1
- --Step 7 Executes; exec CPACombinedReportData
- --Below are the stored procedure definition for each step
- -- definitions are labeled by each steps in order of execution, i.e. step 1 - step 7
- --Step 1
- USE [FP&A]
- GO
- /****** Object: StoredProcedure [BDM].[GETBDMasterReferralData] Script Date: 2/6/2025 9:54:04 AM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- CREATE PROCEDURE [BDM].[GETBDMasterReferralData]
- AS BEGIN
- if object_id('tempdb.dbo.#bdmOppOnCrsRecord','U') is not null
- drop table #bdmOppOnCrsRecord;
- select distinct oncrs.id, oncrs.Opportunity__c, oncrs.RecordTypeId
- into #bdmOppOnCrsRecord
- from SalesforceClone..Opportunity_Non_CPA_Referral_Source__c oncrs
- JOIN SalesforceClone..RecordType rt on rt.id = oncrs.RecordTypeId
- if object_id('tempdb.dbo.#bdmOppRecordType','U') is not null
- drop table #bdmOppRecordType;
- select p.Opportunity__c, p.RecordType1, p.RecordType2, p.RecordType3, p.RecordType4
- into #bdmOppRecordType
- from (
- select oncrs.Opportunity__c, oncrs.RecordTypeId --, rt.name
- , CONCAT('RecordType' , ROW_NUMBER() OVER(PARTITION BY OPPortunity__c order by oncrs.recordtypeid desc)) as rn
- from #bdmOppOnCrsRecord oncrs
- --where Opportunity__c in
- --('0061W00001HstToQAJ','0061W00001MpxrrQAB','0061W00001UCOYOQA5',
- --'0061W00001GFxW6QAL','0061W00001U9UbiQAF','0061W00001SJcdQQAT')
- ) a
- PIVOT (
- min(RecordTypeId)
- For rn in ([RecordType1],[RecordType2],[RecordType3],[RecordType4])
- )p
- if object_id('tempdb.dbo.#bdmOppOnCRSwithCampaign','U') is not null
- drop table #bdmOppOnCRSwithCampaign
- ;
- select o.*
- , oncrs1.Referral_Information__c [RF1]
- , oncrs2.Referral_Information__c [RF2]
- , oncrs3.Referral_Information__c [RF3]
- , oncrs4.Referral_Information__c [RF4]
- , oncrs1.Campaign__c [Campaign1]
- , oncrs2.Campaign__c [Campaign2]
- , oncrs3.Campaign__c [Campaign3]
- , oncrs4.Campaign__c [Campaign4]
- , oncrs1.Account__c [Account1]
- , oncrs2.Account__c [Account2]
- , oncrs3.Account__c [Account3]
- , oncrs4.Account__c [Account4]
- , oncrs1.Referring_CPA_Firm__c [RefAccount1]
- , oncrs2.Referring_CPA_Firm__c [RefAccount2]
- , oncrs3.Referring_CPA_Firm__c [RefAccount3]
- , oncrs4.Referring_CPA_Firm__c [RefAccount4]
- , ISNULL(oncrs1.Non_Conference__c, oncrs1.Non_conference_Other__c) [NonConference1]
- , ISNULL(oncrs2.Non_Conference__c, oncrs2.[Non_conference_Other__c]) [NonConference2]
- , ISNULL(oncrs3.Non_Conference__c, oncrs3.Non_conference_Other__c) [NonConference3]
- , ISNULL(oncrs4.Non_Conference__c, oncrs4.Non_conference_Other__c) [NonConference4]
- , ISNULL(oncrs1.ag_Employee_1__c, oncrs1.Other_Employee_1__c) [Employee1-1]
- , ISNULL(oncrs1.ag_Employee_2__c, oncrs1.Other_Employee_2__c) [Employee2-1]
- , ISNULL(oncrs1.ag_Employee_3__c, oncrs1.Other_Employee_3__c) [Employee3-1]
- , ISNULL(oncrs2.ag_Employee_1__c, oncrs2.Other_Employee_1__c) [Employee1-2]
- , ISNULL(oncrs2.ag_Employee_2__c, oncrs2.Other_Employee_2__c) [Employee2-2]
- , ISNULL(oncrs2.ag_Employee_3__c, oncrs2.Other_Employee_3__c) [Employee3-2]
- , ISNULL(oncrs3.ag_Employee_1__c, oncrs3.Other_Employee_1__c) [Employee1-3]
- , ISNULL(oncrs3.ag_Employee_2__c, oncrs3.Other_Employee_2__c) [Employee2-3]
- , ISNULL(oncrs3.ag_Employee_3__c, oncrs3.Other_Employee_3__c) [Employee3-3]
- , ISNULL(oncrs4.ag_Employee_1__c, oncrs4.Other_Employee_1__c) [Employee1-4]
- , ISNULL(oncrs4.ag_Employee_2__c, oncrs4.Other_Employee_2__c) [Employee2-4]
- , ISNULL(oncrs4.ag_Employee_3__c, oncrs4.Other_Employee_3__c) [Employee3-4]
- , oncrs1.Referral_Source__c [RefSource1]
- , oncrs2.Referral_Source__c [RefSource2]
- , oncrs3.Referral_Source__c [RefSource3]
- , oncrs4.Referral_Source__c [RefSource4]
- , CASE WHEN bdm.OpportunityIDCCC is not null and oncrs1.LastModifiedDate > GETDATE()-1 THEN 1
- WHEN bdm.OpportunityIDCCC is not null and oncrs2.LastModifiedDate > GETDATE()-1 THEN 1
- WHEN bdm.OpportunityIDCCC is not null and oncrs3.LastModifiedDate > GETDATE()-1 THEN 1
- WHEN bdm.OpportunityIDCCC is not null and oncrs4.LastModifiedDate > GETDATE()-1 THEN 1
- ELSE 0 END [RecordForUpdate]
- into #bdmOppOnCRSwithCampaign
- from #bdmOppRecordType o
- outer apply (select top 1 * from SalesforceClone..Opportunity_Non_CPA_Referral_Source__c c where c.Opportunity__c = o.Opportunity__c and c.RecordTypeId = o.recordtype1 order by LastModifiedDate desc) oncrs1 --on oncrs1.Opportunity__c = o.Opportunity__c and oncrs1.RecordTypeId = o.recordtype1
- outer apply (select top 1 * from SalesforceClone..Opportunity_Non_CPA_Referral_Source__c c where c.Opportunity__c = o.Opportunity__c and c.RecordTypeId = o.recordtype2 order by LastModifiedDate desc) oncrs2 --on oncrs1.Opportunity__c = o.Opportunity__c and oncrs1.RecordTypeId = o.recordtype1
- outer apply (select top 1 * from SalesforceClone..Opportunity_Non_CPA_Referral_Source__c c where c.Opportunity__c = o.Opportunity__c and c.RecordTypeId = o.recordtype3 order by LastModifiedDate desc) oncrs3 --on oncrs1.Opportunity__c = o.Opportunity__c and oncrs1.RecordTypeId = o.recordtype1
- outer apply (select top 1 * from SalesforceClone..Opportunity_Non_CPA_Referral_Source__c c where c.Opportunity__c = o.Opportunity__c and c.RecordTypeId = o.recordtype4 order by LastModifiedDate desc) oncrs4 --on oncrs1.Opportunity__c = o.Opportunity__c and oncrs1.RecordTypeId = o.recordtype1
- OUTER APPLY (select top 1 OpportunityIDCCC from BDM.BDMasterSOurce where OpportunityIDCCC = o.Opportunity__c) bdm
- if object_id('tempdb.dbo.#BDMOppRefData','U') is not null
- drop table #BDMOppRefData;
- select b.Opportunity__c, b.RecordType1, b.RecordType2, b.RecordType3, b.RecordType4
- , CASE
- WHEN rt1.Name = 'Raving Fan' and b.Account1 is not null Then a1.Name
- WHEN rt2.Name = 'Raving Fan' and b.Account2 is not null Then a2.Name
- WHEN rt3.Name = 'Raving Fan' and b.Account3 is not null Then a3.Name
- WHEN rt4.Name = 'Raving Fan' and b.Account4 is not null Then a4.Name
- ELSE NULL END [OpRefSourceRavingFan]
- , CASE
- WHEN rt1.Name = 'CPA' and b.RefAccount1 is not null Then rf1.Name
- WHEN rt2.Name = 'CPA' and b.RefAccount2 is not null Then rf2.Name
- WHEN rt3.Name = 'CPA' and b.RefAccount3 is not null Then rf3.Name
- WHEN rt4.Name = 'CPA' and b.RefAccount4 is not null Then rf4.Name
- ELSE NULL END [OpRefSourceCPA]
- , CASE
- WHEN rt1.Name = 'Conference' and c1.Type = 'Seminar / Conference' Then c1.Name
- WHEN rt2.Name = 'Conference' and c2.Type = 'Seminar / Conference' Then c2.Name
- WHEN rt3.Name = 'Conference' and c3.Type = 'Seminar / Conference' Then c3.Name
- WHEN rt4.Name = 'Conference' and c4.Type = 'Seminar / Conference' Then c4.Name
- ELSE NULL END [OpRefSourceConference]
- , CASE
- WHEN rt1.Name = 'Non-Conference' and NonConference1 is not null Then NonConference1
- WHEN rt2.Name = 'Non-Conference' and NonConference2 is not null Then NonConference2
- WHEN rt3.Name = 'Non-Conference' and NonConference3 is not null Then NonConference3
- WHEN rt4.Name = 'Non-Conference' and NonConference4 is not null Then NonConference4
- ELSE NULL END [OpRefSourceNonConference]
- , CASE
- WHEN rt1.Name = 'Direct' and c1.Type in ('Bubble', 'Seminar / Conference') Then c1.Name
- WHEN rt2.Name = 'Direct' and c2.Type in ('Bubble', 'Seminar / Conference') Then c2.Name
- WHEN rt3.Name = 'Direct' and c3.Type in ('Bubble', 'Seminar / Conference') Then c3.Name
- WHEN rt4.Name = 'Direct' and c4.Type in ('Bubble', 'Seminar / Conference') Then c4.Name
- ELSE NULL END [OpRefSourceDirect]
- , CASE
- WHEN rt1.Name = 'E&A' Then c1.Name
- WHEN rt2.Name = 'E&A' Then c2.Name
- WHEN rt3.Name = 'E&A' Then c3.Name
- WHEN rt4.Name = 'E&A' Then c4.Name
- ELSE NULL END [OpRefSourceEA]
- , CASE
- WHEN rt1.Name = 'Referral Source' and rs1.Name is not Null Then rs1.Name
- WHEN rt2.Name = 'Referral Source' and rs2.Name is not Null Then rs2.Name
- WHEN rt3.Name = 'Referral Source' and rs3.Name is not Null Then rs3.Name
- WHEN rt4.Name = 'Referral Source' and rs4.Name is not Null Then rs4.Name
- ELSE NULL END [OpRefSourceReferralSource]
- , CASE
- WHEN rt1.Name in ('E&A Other','Direct') and c1.Type in ('Website') Then c1.Name
- WHEN rt2.Name in ('E&A Other','Direct') and c2.Type in ('Website') Then c2.Name
- WHEN rt3.Name in ('E&A Other','Direct') and c3.Type in ('Website') Then c3.Name
- WHEN rt4.Name in ('E&A Other','Direct') and c4.Type in ('Website') Then c4.Name
- ELSE NULL END [OpRefSourceWebsite]
- , CASE
- WHEN rt1.Name in ('E&A Other','Direct') and c1.Type in ('Webinar') Then c1.Name
- WHEN rt2.Name in ('E&A Other','Direct') and c2.Type in ('Webinar') Then c2.Name
- WHEN rt3.Name in ('E&A Other','Direct') and c3.Type in ('Webinar') Then c3.Name
- WHEN rt4.Name in ('E&A Other','Direct') and c4.Type in ('Webinar') Then c4.Name
- ELSE NULL END [OpRefSourceWebinar]
- , CASE
- WHEN ISNULL(b.[Employee1-1],ISNULL(b.[Employee1-2], ISNULL(b.[Employee1-3],b.[Employee1-4]))) IS NOT NULL
- Then (SELECT [Name] from [SalesforceClone].dbo.[AG_Employee__c] where id = (ISNULL(b.[Employee1-1],ISNULL(b.[Employee1-2], ISNULL(b.[Employee1-3],b.[Employee1-4])))))
- ELSE NULL END [OpRefSourceEmployee1]
- , CASE
- WHEN ISNULL(b.[Employee2-1],ISNULL(b.[Employee2-2], ISNULL(b.[Employee2-3],b.[Employee2-4]))) IS NOT NULL
- Then (SELECT [Name] from [SalesforceClone].dbo.[AG_Employee__c] where id = (ISNULL(b.[Employee2-1],ISNULL(b.[Employee2-2], ISNULL(b.[Employee2-3],b.[Employee2-4])))))
- ELSE NULL END [OpRefSourceEmployee2]
- , CASE
- WHEN ISNULL(b.[Employee3-1],ISNULL(b.[Employee3-2], ISNULL(b.[Employee3-3],b.[Employee3-4]))) IS NOT NULL
- Then (SELECT [Name] from [SalesforceClone].dbo.[AG_Employee__c] where id = (ISNULL(b.[Employee3-1],ISNULL(b.[Employee3-2], ISNULL(b.[Employee3-3],b.[Employee3-4])))))
- ELSE NULL END [OpRefSourceEmployee3]
- , CASE WHEN b.RecordForUpdate = 1 THEN 1
- WHEN rt1.LastModifiedDate > GETDATE()-1 THEN 1
- WHEN rt2.LastModifiedDate > GETDATE()-1 THEN 1
- WHEN rt3.LastModifiedDate > GETDATE()-1 THEN 1
- WHEN rt4.LastModifiedDate > GETDATE()-1 THEN 1
- WHEN c1.LastModifiedDate > GETDATE()-1 THEN 1
- WHEN c2.LastModifiedDate > GETDATE()-1 THEN 1
- WHEN c3.LastModifiedDate > GETDATE()-1 THEN 1
- WHEN c4.LastModifiedDate > GETDATE()-1 THEN 1
- ELSE 0 END [RecordForUpdate]
- into #BDMOppRefData
- from #bdmOppOnCRSwithCampaign b
- LEFT JOIN SalesforceClone..RecordType rt1 on rt1.id = b.RecordType1
- LEFT JOIN SalesforceClone..RecordType rt2 on rt2.id = b.RecordType2
- LEFT JOIN SalesforceClone..RecordType rt3 on rt3.id = b.RecordType3
- LEFT JOIN SalesforceClone..RecordType rt4 on rt4.id = b.RecordType4
- LEFT JOIN SalesforceClone..Campaign c1 on c1.id = b.Campaign1
- LEFT JOIN SalesforceClone..Campaign c2 on c2.id = b.Campaign2
- LEFT JOIN SalesforceClone..Campaign c3 on c3.id = b.Campaign3
- LEFT JOIN SalesforceClone..Campaign c4 on c4.id = b.Campaign4
- LEFT JOIN SalesforceClone..Account a1 on a1.id = b.Account1
- LEFT JOIN SalesforceClone..Account a2 on a2.id = b.Account2
- LEFT JOIN SalesforceClone..Account a3 on a3.id = b.Account3
- LEFT JOIN SalesforceClone..Account a4 on a4.id = b.Account4
- LEFT JOIN SalesforceClone..Account rf1 on rf1.id = b.RefAccount1
- LEFT JOIN SalesforceClone..Account rf2 on rf2.id = b.RefAccount2
- LEFT JOIN SalesforceClone..Account rf3 on rf3.id = b.RefAccount3
- LEFT JOIN SalesforceClone..Account rf4 on rf4.id = b.RefAccount4
- LEFT JOIN SalesforceClone..Account rs1 on rs1.id = b.RefSource1
- LEFT JOIN SalesforceClone..Account rs2 on rs2.id = b.RefSource2
- LEFT JOIN SalesforceClone..Account rs3 on rs3.id = b.RefSource3
- LEFT JOIN SalesforceClone..Account rs4 on rs4.id = b.RefSource4
- OUTER APPLY (select top 1 OpportunityIDCCC from BDM.BDMasterSOurce where OpportunityIDCCC = b.Opportunity__c) bdm
- IF EXISTS(select count(*) from #BDMOppRefData)
- BEGIN
- truncate table BDM.[BDMasterOppReferralInfo]
- insert into BDM.[BDMasterOppReferralInfo]
- (
- [Opportunity__c] ,
- [RecordType1] ,
- [RecordType2] ,
- [RecordType3] ,
- [RecordType4] ,
- [OpRefSourceRavingFan] ,
- [OpRefSourceCPA] ,
- [OpRefSourceConference] ,
- [OpRefSourceNonConference] ,
- [OpRefSourceDirect] ,
- [OpRefSourceEA] ,
- [OpRefSourceEmployee1] ,
- [OpRefSourceEmployee2] ,
- [OpRefSourceEmployee3] ,
- [OpRefSourceReferralSource],
- [OpRefSourceWebsite],
- [OpRefSourceWebinar],
- [RecordForUpdate]
- )
- (select [Opportunity__c] ,
- [RecordType1] ,
- [RecordType2] ,
- [RecordType3] ,
- [RecordType4] ,
- [OpRefSourceRavingFan] ,
- [OpRefSourceCPA] ,
- [OpRefSourceConference] ,
- [OpRefSourceNonConference] ,
- [OpRefSourceDirect] ,
- [OpRefSourceEA] ,
- [OpRefSourceEmployee1] ,
- [OpRefSourceEmployee2] ,
- [OpRefSourceEmployee3] ,
- [OpRefSourceReferralSource],
- [OpRefSourceWebsite],
- [OpRefSourceWebinar],
- [RecordForUpdate]
- from #BDMOppRefData)
- END
- END
- GO
- --Step 2
- USE [FP&A]
- GO
- /****** Object: StoredProcedure [BDM].[GETBDMasterMatterBilledCollected] Script Date: 2/6/2025 10:09:00 AM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- CREATE PROCEDURE [BDM].[GETBDMasterMatterBilledCollected]
- AS BEGIN
- truncate table BDM.BDMasterMatterBilledCollected
- INSERT INTO BDM.BDMasterMatterBilledCollected
- SELECT Number
- ,CASE WHEN RIGHT(MIN(Year),2) = RIGHT(MAX(Year),2) THEN RIGHT(MIN(Year),2) ELSE RIGHT(MIN(Year),2) + '-' + RIGHT(MAX(Year),2) END YearDesc
- ,FutureYear
- , SUM(AdjWIPPerYearFEDState) AdjWIPPerYearFEDState
- , SUM(BilledSplit) BilledSplit
- , SUM(CollectedSplit) CollectedSplit
- , MIN(Year) [MinYear]
- --into BDM.BDMasterMatterBilledCollected
- FROM
- (
- SELECT
- m.Number
- , m.EngSignedDate_CCC
- , pc.Year
- , m.Month_CCC
- , MattStatus
- , pc.Total
- , ph.FeeCapPct
- , CASE WHEN [PracticeGroup] in ('110','120','130') THEN
- CASE WHEN pc.Year>YEAR(DATEADD(M,-m.Month_CCC,m.EngSignedDate_CCC)) THEN 1
- -- WHEN pc.Year=YEAR(DATEADD(M,-m.Month_CCC,m.EngSignedDate_CCC)) THEN 1
- ELSE 0 END
- ELSE NULL END FutureYear
- , IsFederal
- , State
- , Billed
- , Collected
- , pc.Total * ph.FeeCapPct/100 AdjWIPPerYearFEDState
- , PH.AdjWIP - (COALESCE(priorCredits,0))*(ph.FeeCapPct/100) RemWIPbeforeRecord
- , PH.AdjWIP - (COALESCE(priorCredits,0)+pc.Total)*(ph.FeeCapPct/100) RemWIPAfterRecord
- ,ph.AdjWIP
- ---Need these Cases
- , CASE
- WHEN Billed > (PH.AdjWIP - (COALESCE(priorCredits,0))*(ph.FeeCapPct/100)) AND PH.AdjWIP - (COALESCE(priorCredits,0)+pc.Total)*(ph.FeeCapPct/100) <=0 and ROW_NUMBER()OVER(PArtition BY NUmber,Billed Order by YEar desc,Isfederal desc, State) = 1 AND Billed > ph.AdjWIP + (pc.Total)*(ph.FeeCapPct/100) THEN Billed - ph.AdjWIP + (pc.Total)*(ph.FeeCapPct/100)
- WHEN (COALESCE(priorCredits,0)+pc.Total)*(ph.FeeCapPct/100)<=Billed THEN (pc.Total)*(ph.FeeCapPct/100)
- WHEN Billed BETWEEN (COALESCE(priorCredits,0))*(ph.FeeCapPct/100) AND (COALESCE(priorCredits,0)+pc.Total)*(ph.FeeCapPct/100) THEN Billed - (COALESCE(priorCredits,0))*(ph.FeeCapPct/100)
- ELSE 0
- END BilledSplit
- --, CASE
- -- WHEN Billed > (PH.AdjWIP - (COALESCE(priorCredits,0))*(ph.FeeCapPct/100)) AND PH.AdjWIP - (COALESCE(priorCredits,0)+pc.Total)*(ph.FeeCapPct/100) <=0 and ROW_NUMBER()OVER(PArtition BY NUmber,Billed Order by YEar desc,Isfederal desc, State) = 1 THEN 1
- -- WHEN (COALESCE(priorCredits,0)+pc.Total)*(ph.FeeCapPct/100)<=Billed THEN 2
- -- WHEN Billed BETWEEN (COALESCE(priorCredits,0))*(ph.FeeCapPct/100) AND (COALESCE(priorCredits,0)+pc.Total)*(ph.FeeCapPct/100) THEN 3
- -- ELSE 0
- -- END BilledSplitid
- , CASE
- WHEN Collected > (PH.AdjWIP - (COALESCE(priorCredits,0))*(ph.FeeCapPct/100)) AND PH.AdjWIP - (COALESCE(priorCredits,0)+pc.Total)*(ph.FeeCapPct/100) <=0 and ROW_NUMBER()OVER(PArtition BY NUmber,Billed Order by YEar desc,Isfederal desc, State) = 1 AND Collected > ph.AdjWIP + (pc.Total)*(ph.FeeCapPct/100) THEN Collected - ph.AdjWIP + (pc.Total)*(ph.FeeCapPct/100)
- WHEN (COALESCE(priorCredits,0)+pc.Total)*(ph.FeeCapPct/100)<=Collected THEN (pc.Total)*(ph.FeeCapPct/100)
- WHEN Collected BETWEEN (COALESCE(priorCredits,0))*(ph.FeeCapPct/100) AND (COALESCE(priorCredits,0)+pc.Total)*(ph.FeeCapPct/100) THEN Collected - (COALESCE(priorCredits,0))*(ph.FeeCapPct/100)
- ELSE 0
- END CollectedSplit
- FROM
- TE_3E_Prod_Clone..matter m
- JOIN
- TE_3E_PROD_Clone..PGDetHdr_CCC ph on ph.matterlkup = m.Mattindex and ph.NxEndDate = '99991231' and ph.NxStartDate != '99991231' --and LEFT(NUmber,6) = '009475'
- JOIN
- (SELECT PGDetHdr,MAX(PGDetChild_CCCID) PGDetChild_CCCID
- , IsFederal
- , State
- ,SUM(Total) Total
- ,Year
- FROM
- TE_3E_PROD_Clone..PGDetChild_CCC pc
- WHERE
- IsGeneralWork = 0 and pc.Total>=0
- GROUP BY
- PGDetHdr
- , IsFederal
- , State
- ,Year) pc on pc.PGDetHdr = ph.PGDetHdr_CCCID
- left join
- (
- select
- row_number() over(partition by md.MatterLkUp order by md.effstart desc, md.nxStartDate desc, md.nxEndDate desc) [Rn]
- , md.MatterLkUp
- , md.[PracticeGroup]
- , TimeStamp
- from
- TE_3E_PROD_Clone.dbo.MattDate md
- ) md on md.MatterLkUp = m.MattIndex and md.[Rn] = 1
- OUTER APPLY -- need this function
- (SELECT SUM(Total) priorCredits
- FROM
- TE_3E_PROD_Clone..PGDetChild_CCC ipc
- WHERE
- (ipc.Year<pc.Year OR (ipc.Year=pc.Year and ipc.PGDetChild_CCCID != pc.PGDetChild_CCCID AND ipc.State<COALESCE(pc.State,'zz')))
- and ipc.PGDetHdr = pc.PGDetHdr and IsGeneralWork = 0
- ) pcp
- LEFT JOIN
- (SELECT
- NewMattIndex Matter
- , SUM(Billed) Billed
- , SUM(Collected) Collected
- FROM
- (SELECT
- CASE WHEN Billed>BillableWIPatDAte THEN COALESCE(MIN(Case when BillableWIPatDate>Billed THEN MattIndex /*ELSE MattIndex*/ END)OVER(Partition By InvMaster),MattINdex) ELSE MattIndex END NewMattIndex
- ,*
- FROM
- (SELECT
- m.MattIndex
- , m.Number
- , m.MattStatus
- , COALESCE(M.CloseDate,CASE WHEN m.MattStatus IN ('TERM','COMP','CLOSING') THEN MattStatusDate END) CloseDate
- , md.PracticeGroup
- , md.Arrangement
- , PH.AdjWIP
- , PH.FeeCapPct
- , SUM(
- CASE WHEN FinalCredit Is not null and (Adjustments is null OR COALESCE(State,'') not in ('PA','VA','MN','NH','DE','FL','LA','MD')) THEN FinalCredit + COALESCE(INterest,0) + COALESCE(Adjustments,0)
- WHEN md.PracticeGRoup = 130 then COALESCE(EngineerReview,0)
- WHEN pc.TriggerType IN ('RQ','PQ','NQ') THEN 0
- ELSE COALESCE(ValueAssessment,0) * 0.8 END) BillableCredit
- , SUM(
- CASE WHEN FinalCredit Is not null and (Adjustments is null OR COALESCE(State,'') not in ('PA','VA','MN','NH','DE','FL','LA','MD')) THEN FinalCredit + COALESCE(INterest,0) + COALESCE(Adjustments,0)
- WHEN md.PracticeGRoup = 130 then COALESCE(EngineerReview,0)
- WHEN pc.TriggerType IN ('RQ','PQ','NQ') THEN 0
- ELSE COALESCE(ValueAssessment,0) * 0.8 END) * (COALESCE(PH.FeeCapPct,0)/100)
- -COALESCE(SUM(Billed)OVER(Partition By m.MattIndex Order by InvDate, InvMaster),0)+COALESCE(Billed,0)
- BillableWIPatDate
- , Billed
- , Collected
- , InvMaster
- , InvDate
- FROM
- (SELECT
- Matter
- , SUM(CASE WHEN ARList IN ('Bill','BillRev','Woff','WoffRev') THEN ARFee ELSE 0 END) Billed
- , SUM(CASE WHEN ARList IN ('Receipt','RcptRev') THEN -ARFee ELSE 0 END) Collected
- , InvMaster
- , InvDate
- FROM
- TE_3E_PROD_Clone..ARMaster
- -- where matter = 7042
- GROUP BY Matter
- , InvMaster
- , InvDate ) AR
- JOIN
- (
- SELECT m.MattIndex,m.Number,m.client, m.Description,m.MattStatus,m.CloseDate,m.MattStatusDate, m.EngSignedDate_CCC,DATEADD(d,1,COALESCE(Lead(NxEndDate,1)OVER(Partition By MattIndex Order by NxEndDate desc),0)) NxStartDate, NxEndDate
- FROM (
- SELECT m.MattIndex,m.Number,m.client, m.Description,m.MattStatus,m.CloseDate,m.MattStatusDate, m.EngSignedDate_CCC,DATEADD(d,0,DATEDIFF(d,0,TimeStamp)) NxStartDate,'99991231' NxEndDate
- FROM
- [TE_3E_PROD_Clone].[dbo].matter m
- UNION ALL
- SELECT m.MattIndex,m.Number,m.client, m.Description,m.MattStatus,m.CloseDate,m.MattStatusDate, m.EngSignedDate_CCC,DATEADD(d,0,DATEDIFF(d,0,TimeStamp)) NxStartDate,DATEADD(d,-1,DATEDIFF(d,0,AuditTimeStamp)) NxEndDate
- FROM
- [TE_3E_PROD_Clone].[dbo].matter_audit m
- )m)m on AR.Matter = m.MattIndex and AR.InvDate between m.NxStartDate and m.NxEndDate
- JOIN
- TE_3E_PROD_Clone..MattDate MD on MD.Matterlkup = m.MattIndex and AR.InvDate between md.NxStartDate and md.NxEndDate and md.NxStartDate != '99991231'
- JOIN
- TE_3E_PROD_Clone..PGDetHdr_CCC PH on PH.Matterlkup = m.MattIndex and AR.InvDate between ph.NxStartDate and ph.NxEndDate and ph.NxStartDate != '99991231'
- JOIN
- TE_3E_PROD_Clone..PGDetChild_CCC PC on PC.PGDetHdr = PH.PGDetHdr_CCCID
- --WHERE
- --m.MattIndex = 58865
- GROUP BY
- m.MattIndex
- , m.Number
- , m.MattStatus
- , COALESCE(M.CloseDate,CASE WHEN m.MattStatus IN ('TERM','COMP','CLOSING') THEN MattStatusDate END)
- , md.PracticeGroup
- , md.Arrangement
- , PH.AdjWIP
- , PH.FeeCapPct
- , Billed
- , Collected
- , InvMaster
- , InvDate
- ) AR
- ) AR
- GROUP BY
- AR.NewMattIndex) BC on BC.Matter = m.MattIndex
- -- where number in ('003790.0012','003790.0019')
- --300025.0001','009401.0007')
- )Splits
- GROUP BY
- Number,FutureYear,FutureYear*Year
- order by 1,2
- END
- GO
- --Step 3
- USE [FP&A]
- GO
- /****** Object: StoredProcedure [BDM].[GETBDMasterMatterDataFrom3E] Script Date: 2/6/2025 10:25:24 AM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- CREATE PROCEDURE [BDM].[GETBDMasterMatterDataFrom3E]
- AS BEGIN
- if object_id('tempdb.dbo.#Duals','U') is not null
- drop table #Duals;
- SELECT MattINdex
- INTO #Duals
- FROM (
- SELECT MattIndex, COUNT(mattindex)Over(partition by OpportunityID_CCC) - COUNT(mattindex)Over(partition by OpportunityID_CCC,year(minday),month(minday)) dual
- FROM (
- SELECT MattIndex,OpportunityID_CCC,DATEADD(d,0,DATEDIFF(d,0,MIN(TimeStamp))) MinDay
- FROM (
- SELECT MattIndex,OpportunityID_CCC,TimeStamp
- FROM
- TE_3E_PROD_Clone..Matter
- UNION ALL
- SELECT MattIndex,OpportunityID_CCC,TimeStamp
- FROM
- TE_3E_PROD_Clone..Matter_audit
- UNION ALL
- SELECT MattIndex,OpportunityID_CCC,OpenDate
- FROM
- TE_3E_PROD_Clone..Matter
- where OpenDate<='20181015') a
- where
- OpportunityID_CCC is not null
- GROUP BY
- MattIndex,OpportunityID_CCC
- ) b
- ) c
- WHERE dual >1
- if object_id('tempdb.dbo.#bdmMatterInfo','U') is not null
- drop table #bdmMatterInfo;
- select
- cast(a.[OpportunityID_CCC] as nvarchar(64)) [OpportunityID_CCC]
- , a.[Number]
- , cast(a.[MattIndex] as int) [MattIndex]
- , cast(a.[AltNumber] as nvarchar(64)) [AltNumber]
- , a.DisplayName
- , a.Description
- , a.Client
- , a.ClientId
- , a.CloseDate
- , a.Currency
- , a.IsEvergreenCCC
- , a.ServiceLine
- , a.State
- , cast(a.[Signed_Date] as datetime) [EngSignedDateCCC]
- , cast(a.[BD1_ID] as int) [BD1ID]
- , cast(a.[BD2_ID] as int) [BD2ID]
- , cast(a.[BD3_ID] as int) [BD3ID]
- , cast(a.[SOE_1_ID] as int) [SOE1ID]
- , cast(a.[SOE_2_ID] as int) [SOE2ID]
- , cast(a.[QC_ID] as int) [QCID]
- , cast(a.[TD_ID] as int) [TDID]
- , cast(a.[PM_ID] as int) [PMID]
- , cast(a.[PBD] as nvarchar(200)) [PBD]
- , cast(a.[SBD] as nvarchar(200)) [SBD]
- , cast(a.[PRD] as nvarchar(200)) [PRD]
- , cast(a.[SRD] as nvarchar(200)) [SRD]
- , cast(a.[PM] as nvarchar(200)) [PM]
- , cast(a.[Original_WIP] as decimal(16,2)) [OriginalWIP]
- , cast(a.[Fees_Collected] as decimal(16,2)) [Collected]
- , cast(a.[Credit] as decimal(16,2)) [Credit]
- , cast(a.[Total_Invoiced] as decimal(38,2)) [Billed] --Billed Amount to be change to Total_Invoiced
- , cast(a.[Worked_WIP] as decimal(17,2)) [WorkedWIP]
- , cast(a.[Pending_Invoices] as decimal(38,2)) [PendingInvoices]
- , cast(coalesce(case
- when a.[179DWriteDownFlag] = 1 then 0
- when coalesce(a.[VAERFNDeliveredCnt],0) >= 0 then a.[Adjusted_WIP]
- else a.[Original_WIP]
- end,0) as decimal(16,2)) [TotalWIP]
- , cast(a.[Hours_Worked] as decimal(38,5)) [HoursWorked]
- , cast(coalesce(a.[Remaining_WIP],0) as decimal(16,2)) [RemainingWIP]
- --, CASE WHEN a.MattStatus IN ('COMP','CLOSING','CLOSING_ERCLIVE') THEN cast(coalesce(a.[Total_Invoiced],0) as decimal(16,2)) ELSE
- -- cast(coalesce(a.[Adjusted_WIP],0) as decimal(16,2)) END [AdjustedWIP]
- , cast(coalesce(a.[Adjusted_WIP],0) as decimal(16,2)) [AdjustedWIP]
- , cast(coalesce(a.[Unbilled_WIP],0) as decimal(38,2)) [UnbilledWIP]
- , cast(coalesce(a.[Unbilled_Worked_WIP],0) as decimal(38,2)) [UnbilledWorkedWIP]
- , cast(coalesce(case when a.[Balance] < 0 then 0 else a.[Balance] end,0) as decimal(38,2)) [Balance]
- , cast(coalesce(a.[Unworked_Unbilled],0) as decimal(38,2)) [UnworkedUnbilled] --find not in use
- , cast(a.[BD1_Allocation] as decimal(38,2)) [BD1Allocation]
- , cast(a.[BD2_Allocation] as decimal(38,2)) [BD2Allocation]
- , cast(a.[BD3_Allocation] as decimal(38,2)) [BD3Allocation]
- , cast(a.[RD1_Allocation] as decimal(38,2)) [RD1Allocation]
- , cast(a.[RD2_Allocation] as decimal(38,2)) [RD2Allocation]
- , cast(coalesce(a.[Original_WIP] * a.[BD1_Allocation],0) as decimal(38,2)) [BD1OrgWIPAlloc]
- , cast(coalesce(a.[Original_WIP] * a.[BD2_Allocation],0) as decimal(38,2)) [BD2OrgWIPAlloc]
- , cast(coalesce(a.[Original_WIP] * a.[BD3_Allocation],0) as decimal(38,2)) [BD3OrgWIPAlloc]
- , cast(coalesce(a.[Original_WIP] * a.[RD1_Allocation],0) as decimal(38,2)) [RD1OrgWIPAlloc]
- , cast(coalesce(a.[Original_WIP] * a.[RD2_Allocation],0) as decimal(38,2)) [RD2OrgWIPAlloc]
- , cast(coalesce(a.[Adjusted_WIP] * a.[BD1_Allocation],0) as decimal(38,2)) [BD1AdjWIPAlloc]
- , cast(coalesce(a.[Adjusted_WIP] * a.[BD2_Allocation],0) as decimal(38,2)) [BD2AdjWIPAlloc]
- , cast(coalesce(a.[Adjusted_WIP] * a.[BD3_Allocation],0) as decimal(38,2)) [BD3AdjWIPAlloc]
- , cast(coalesce(a.[Adjusted_WIP] * a.[RD1_Allocation],0) as decimal(38,2)) [RD1AdjWIPAlloc]
- , cast(coalesce(a.[Adjusted_WIP] * a.[RD2_Allocation],0) as decimal(38,2)) [RD2AdjWIPAlloc]
- , cast(a.[BD1_Fees_Billed] as decimal(38,2)) [BD1FeesBilled]
- , cast(a.[BD2_Fees_Billed] as decimal(38,2)) [BD2FeesBilled]
- , cast(a.[BD3_Fees_Billed] as decimal(38,2)) [BD3FeesBilled]
- , cast(a.[RD1_Fees_Billed] as decimal(38,2)) [RD1FeesBilled]
- , cast(a.[RD2_Fees_Billed] as decimal(38,2)) [RD2FeesBilled]
- , cast(a.[BD1_Fees_Collected] as decimal(38,2)) [BD1FeesCollected]
- , cast(a.[BD2_Fees_Collected] as decimal(38,2)) [BD2FeesCollected]
- , cast(a.[BD3_Fees_Collected] as decimal(38,2)) [BD3FeesCollected]
- , cast(a.[RD1_Fees_Collected] as decimal(38,2)) [RD1FeesCollected]
- , cast(a.[RD2_Fees_Collected] as decimal(38,2)) [RD2FeesCollected]
- , a.[OriginalSignedDate]
- , a.VAERFNDeliveredCnt
- , Case When a.MaxTaxYear> a.MinTaxYear then 'Multi' else 'Single' end [StudyYears]
- , a.MajorIndustry
- , a.PracticeGroupCode [Code]
- , a.MattStatus
- , a.MattCategory
- , a.EngType_CCC [EngTypeCCC]
- , a.EngStatus_CCC [EngStatusCCC]
- , a.Updated_WIP [UpdatedWIP]
- , a.MinTaxYear
- , a.MaxTaxYear
- , CASE WHEN IsCloned_CCC = 1 OR a.EngType_CCC = 'FU' then 0 else a.[1x_Adj._Flag] end [1TimeAdj]
- , a.StudyYear
- , RecordForUpdate
- ,IsCloned_CCC
- into #bdmMatterInfo
- from
- (
- select
- m.*
- , CAST(coalesce(Case when [1x_Adj._Flag] = 1 and NOT(IsCloned_CCC = 1 OR EngType_CCC = 'FU') and YEAR([OriginalSignedDate])>YEAR(GETDATE()) THEN [RevSFAmount] WHEN (IsCloned_CCC = 1 OR EngType_CCC = 'FU') THEN [OrigWIP] ELSE [RevSFAmount] END,[OrigWIP] ,0) as decimal(38,2)) [Original_WIP]
- , CAST(coalesce(case
- when /*m.[PracticeGroupCode] IN (225) AND*/ m.[MattStatus] in ('KO','CANCELDUP','Cancel_NOEL','TERM','TERM_EG') THEN 0
- --when [VAERFNDeliveredCnt] = 0 and m.[PracticeGroupCode] IN (225) THEN [OrigWIP]
- when m.[PracticeGroupCode] IN (225,150,175) OR [NxUnit] = 20 THEN AdjWIP
- when m.[MattStatus] in ('Cancel_NOEL','CANCELDUP') then 0
- when [179DWriteDownFlag] = 1 then 0
- when m.[PracticeGroupCode] IN (130) and [179DUnder60Flag] = 1 and [RevSFAmount]>[AdjWIPrvs] THEN [RevSFAmount]
- when m.[MattStatus] in ('COMP','CLOSING','KO','TERM','CLOSING_ERCLIVE','COMP_ERCLIVE','TERM_ERCLIVE') then [AdjWIPrvs]
- when [VAERFNDeliveredCnt] = 0 and [NxUnit] != 20 and (([FutureTaxYearPct] = 1 and (m.[MattCategory] != 'FU' or m.[MattCategory] is null)) OR (IsCloned_CCC = 1 AND m.[MattCategory] != 'NEW')) then [AdjWIPrvs]
- when [VAERFNDeliveredCnt] = 0 and [NxUnit] != 20 then coalesce([RevSFAmount], [AdjWIPrvs])
- when m.[MattStatus] not in ('Cancel_NOEL','CANCELDUP') then [AdjWIPrvs]
- else
- case
- when [OpportunityID_CCC] is null then [OrigWIP]
- when row_number() over (partition by [OpportunityID_CCC] order by m.[MattIndex]) > 1 then 0
- else coalesce(case
- when [NxUnit] = 20 and [OrigWIP] = 0 then [Amount]
- when [NxUnit] = 20 or [Amount] = 0 then [OrigWIP]
- else [RevSFAmount]
- end, [OrigWIP])
- end
- end
- , 0) as decimal(38,2)) [Adjusted_WIP]
- , CAST(coalesce(case --Per Harry 3/29/2022 should be the same as Adj WIP excluding alterations based on Status -KR
- --when m.[MattStatus] in ('Cancel_NOEL','CANCELDUP') then 0
- when /*m.[PracticeGroupCode] IN (225) AND*/ m.[MattStatus] in ('KO','CANCELDUP','Cancel_NOEL','TERM','TERM_EG') THEN 0
- when m.[PracticeGroupCode] IN (225,150,175) OR [NxUnit] = 20 THEN AdjWIP
- when [179DWriteDownFlag] = 1 then 0
- --when m.[MattStatus] in ('COMP','CLOSING','KO','TERM','CLOSING_ERCLIVE','COMP_ERCLIVE','TERM_ERCLIVE') then [AdjWIPrvs]
- when [VAERFNDeliveredCnt] = 0 and [NxUnit] != 20 and (([FutureTaxYearPct] = 1 and (m.[MattCategory] != 'FU' or m.[MattCategory] is null)) OR (IsCloned_CCC = 1 AND m.[MattCategory] != 'NEW')) then [AdjWIPrvsUW]
- when [VAERFNDeliveredCnt] = 0 and [NxUnit] != 20 then coalesce([RevSFAmount], [AdjWIPrvsUW])
- --when m.[MattStatus] not in ('Cancel_NOEL','CANCELDUP') then [AdjWIPrvs]
- else [AdjWIPrvsUW]
- --case
- -- when [OpportunityID_CCC] is null then [OrigWIP]
- -- when row_number() over (partition by [OpportunityID_CCC] order by m.[MattIndex]) > 1 then 0
- -- else coalesce(case
- -- when [NxUnit] = 20 and [OrigWIP] = 0 then [Amount]
- -- when [NxUnit] = 20 or [Amount] = 0 then [OrigWIP]
- -- else [RevSFAmount]
- -- end, [OrigWIP])
- -- end
- end
- , 0) as decimal(38,2)) [Updated_WIP]
- , coalesce(case
- when [179DWriteDownFlag] = 1 then 0
- when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 then 0
- when [VAERFNDeliveredCnt] = 0 then [RevSFCredit]
- end
- , [PHCredit], 0) [Credit]
- , coalesce(case
- when [179DWriteDownFlag] = 1 then 0
- when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 then 0
- when [VAERFNDeliveredCnt] = 0 and [WorkAmt] < [RevSFAmount] then [WorkAmt]
- when [VAERFNDeliveredCnt] = 0 and [WorkAmt] >= [RevSFAmount] then [RevSFAmount]
- end
- , [AdjWIPrvs] - [RemainingWIP], 0) [Worked_WIP]
- , CAST(coalesce(case
- when [179DWriteDownFlag] = 1 then 0
- when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] != 'FU' then 0
- when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] is null then 0
- when [VAERFNDeliveredCnt] = 0 and [WorkAmt] < [RevSFAmount] then [RevSFAmount] - [WorkAmt]
- when [VAERFNDeliveredCnt] = 0 and [WorkAmt] >= [RevSFAmount] then 0
- end
- , [RemainingWIP]) as decimal(38,2)) [Remaining_WIP]
- , CAST(coalesce(case
- when [179DWriteDownFlag] = 1 then 0
- when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] != 'FU' then 0
- when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] is null then 0
- when [VAERFNDeliveredCnt] = 0 then [RevSFAmount] - [Total_Invoiced]
- end
- , [AdjWIPrvs] - [Total_Invoiced]) as decimal(38,2)) [Unbilled_WIP]
- , coalesce(case
- when [179DWriteDownFlag] = 1 then 0
- when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] != 'FU' then 0
- when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] is null then 0
- when [VAERFNDeliveredCnt] = 0 then [RevSFAmount] - [RevSFAmount] - [WorkAmt] - [Total_Invoiced] - [Pending_Invoices]
- end
- , [AdjWIPrvs] - [RemainingWIP] - [Total_Invoiced] - [Pending_Invoices]) [Unbilled_Worked_WIP]
- , coalesce(case
- when [179DWriteDownFlag] = 1 then 0
- when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] != 'FU' then 0
- when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] is null then 0
- when [VAERFNDeliveredCnt] = 0 then ([RevSFAmount] * [CurrentTaxYearPct]) - [RevSFAmount] - [WorkAmt] - [Total_Invoiced] - [Pending_Invoices]
- end
- , [AdjWIPrvs] - [RemainingWIP] - [Total_Invoiced] - [Pending_Invoices]) [Balance]
- , coalesce(case
- when [179DWriteDownFlag] = 1 then 0
- when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] != 'FU' then 0
- when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] is null then 0
- when [VAERFNDeliveredCnt] = 0 and [WorkAmt] < [RevSFAmount] then [RevSFAmount] - [WorkAmt]
- when [VAERFNDeliveredCnt] = 0 and [WorkAmt] >= [RevSFAmount] then 0
- end
- , [RemainingWIP]) [Unworked_Unbilled]
- , [Total_Invoiced] * [BD1_Allocation] [BD1_Fees_Billed]
- , [Total_Invoiced] * [BD2_Allocation] [BD2_Fees_Billed]
- , [Total_Invoiced] * [BD3_Allocation] [BD3_Fees_Billed]
- , [Total_Invoiced] * [RD1_Allocation] [RD1_Fees_Billed]
- , [Total_Invoiced] * [RD2_Allocation] [RD2_Fees_Billed]
- , [Fees_Collected] * [BD1_Allocation] [BD1_Fees_Collected]
- , [Fees_Collected] * [BD2_Allocation] [BD2_Fees_Collected]
- , [Fees_Collected] * [BD3_Allocation] [BD3_Fees_Collected]
- , [Fees_Collected] * [RD1_Allocation] [RD1_Fees_Collected]
- , [Fees_Collected] * [RD2_Allocation] [RD2_Fees_Collected]
- , bd1.EmployeeFullName [PBD]
- , bd2.EmployeeFullName [SBD]
- , SOE1.EmployeeFullName [PRD]
- , SOE2.EmployeeFullName [SRD]
- , PM.EmployeeFullName [PM]
- , CASE WHEN f.Number IS NOT NULL AND TimeStampFromYesterday > 0 THEN 1 ELSE 0 END [RecordForUpdate]
- from
- (
- select
- ma.*
- , coalesce(case
- when ma.[PracticeGroupCode] = 175 then ma.[AdjWIP]
- when ma.[FutureTaxYearTodayCnt] > 0 then 0
- when [1x_Adj._Flag] = 1 --1xadj
- AND ma.[Total_Invoiced] = 0
- AND [MattStatus] in ('COMP','CLOSING','KO','TERM','CLOSING_ERCLIVE','COMP_ERCLIVE','TERM_ERCLIVE') THEN ma.[AdjWIP]
- when [MattStatus] in ('COMP','CLOSING','KO','TERM','CLOSING_ERCLIVE','COMP_ERCLIVE','TERM_ERCLIVE') and DATEDIFF(d,ma.CloseDate2,GETDATE())>30 then ma.[AdjWIP]--ma.[Total_Invoiced]
- else ma.[AdjWIP]
- end,0) [AdjWIPrvs]
- , coalesce(case
- when ma.[PracticeGroupCode] = 175 then ma.[AdjWIP]
- when ma.[FutureTaxYearTodayCnt] > 0 then 0
- when [1x_Adj._Flag] = 1 --1xadj
- AND ma.[Total_Invoiced] = 0
- AND [MattStatus] in ('COMP','CLOSING','KO','TERM','CLOSING_ERCLIVE','COMP_ERCLIVE','TERM_ERCLIVE') THEN ma.[AdjWIP]
- when [MattStatus] in ('COMP','CLOSING','KO','TERM','CLOSING_ERCLIVE','COMP_ERCLIVE','TERM_ERCLIVE') then ma.[AdjWIP]
- else ma.[AdjWIP]
- end,0) [AdjWIPrvsUW]
- , case
- when ma.[PracticeGroupCode] = 175 then ma.[Amount]
- when ma.[FutureTaxYearTodayCnt] > 0 then 0
- when ma.[MattStatus] IN ('CANCELDUP','Cancel_NOEL') then 0
- when (ma.[FutureTaxYearPct] = 1 and ma.[NxUnit] != 20 and COALESCE(ma.[EngType_CCC],'New') = 'FU' and [1x_Adj._Flag] = 1) then ma.[OrigWIP]
- else cast(ma.[Amount] as float) * COALESCE((CAST([CurrentTaxYearCnt] as decimal(38,10))/NULLIF(SUM([CurrentTaxYearCnt])OVER(Partition By CASE WHEN ma.[MattStatus] NOT IN ('Cancel_NOEL','CANCELDUP') THEN OpportunityID_CCC END,[YearEngSigned]),0)),1)
- end [RevSFAmount]
- , case
- when ma.[PracticeGroupCode] = 175 then ma.[SFCredit]
- when ma.[FutureTaxYearTodayCnt] > 0 then 0
- when ma.[MattStatus] IN ('CANCELDUP','Cancel_NOEL') then 0
- when (ma.[FutureTaxYearPct] = 1 and ma.[NxUnit] != 20 and COALESCE(ma.[EngType_CCC],'New') = 'FU' and [1x_Adj._Flag] = 1) then ma.[PHCredit]
- else cast(ma.[SFCredit] as float) * cast(coalesce(case when (ma.[FutureTaxYearPct] = 1 and ma.[NxUnit] != 20 and COALESCE(ma.[EngType_CCC],'New') = 'FU' and [1x_Adj._Flag] = 1) then 0 when ma.[MattStatus] = 'CANCELDUP' then 0 end, 1 / NULLIF(cast(sum(coalesce(case when (ma.[FutureTaxYearPct] = 1 and ma.[NxUnit] != 20 and COALESCE(ma.[EngType_CCC],'New') = 'FU' and [1x_Adj._Flag] = 1) then 0 when ma.[MattStatus] = 'CANCELDUP' then 0 end, 1)) over(partition by ma.[OpportunityID_CCC]) as float),0)) as float)
- end [RevSFCredit]
- --, case
- -- when ma.[BillingGroup] = 0 then ma.[Billed_Amount]
- -- when ma.[AdjWIP] <= case when ma.[Rn] = 1 then ma.[TotalBilledClient] else lag(ma.[TotalBilledClient] - ma.[SubtotalAdjWIPClient],1) over(partition by ma.[Client] order by ma.[Number]) end then ma.[AdjWIP]
- -- when case when ma.[Rn] = 1 then ma.[TotalBilledClient] else lag(ma.[TotalBilledClient] - ma.[SubtotalAdjWIPClient],1) over(partition by ma.[Client] order by ma.[Number]) end < 0 then 0
- -- else case when ma.[Rn] = 1 then ma.[TotalBilledClient] else lag(ma.[TotalBilledClient] - ma.[SubtotalAdjWIPClient],1) over(partition by ma.[Client] order by ma.[Number]) end SELECT * FROM TE_3E_PROD_Clone..PracticeGRoup
- -- end [BilledAdj]
- FROM
- (SELECT ma.*
- , coalesce(case
- when (((COALESCE(ma.[EngType_CCC],'New') = 'FU' and COALESCE(ma.[IsEvergreen_CCC],0) = 1 and (COALESCE(ma.[evergreen_2__c],'-1') = 'Yes' OR Id is null OR NULLIF(dual,FirstFU) is not null)) AND FirstFU is null and ma.[MinTaxYear] >= ma.[YearEngSigned] AND YEAR([OriginalSignedDate])<2021) OR (IsCloned_CCC = 1 AND COALESCE(ma.[EngType_CCC],'New') != 'NEW')) and ma.[PracticeGroupCode] in (110,120,130,160,170,140) then 1
- -- when COALESCE(ma.[EngType_CCC],'New') = 'FU' and ma.[MinTaxYear] > ma.[YearEngSigned] and ma.[PracticeGroupCode] in (110,120,130) then 1
- when COALESCE(ma.[EngType_CCC],'New') IN ('NEW','CONT') and ma.[MinTaxYear] >= ma.[YearEngSigned] and ma.[PracticeGroupCode] in (110,120,130) then 1
- end, 0) [1x_Adj._Flag]
- from
- (
- select
- m.[OpportunityID_CCC]
- , m.[MattIndex]
- , m.[Number]
- , m.[Client] [ClientId]
- , m.DisplayName [DisplayName]
- , c.DisplayName [Client]
- , m.AltNumber [AltNumber]
- , m.Description [Description]
- , m.CloseDate [CloseDate]
- , TRY_CAST(COALESCE(m.CloseDate,CASE WHEN m.MattStatus in ('Closing','CLOSING_ERCLIVE','CLOSING_MEMO','COMP','COMP_ERCLIVE') THEN M.MattStatusDate END) as datetime) [CloseDate2]
- , m.Currency [Currency]
- , m.IsEvergreen_CCC [IsEvergreenCCC]
- , m.EngStatus_CCC
- , COALESCE(case
- WHEN pg.[Code] = 225 THEN 'NEW'
- WHEN Cloned.IsCloned_CCC = 1 AND m.MattCategory != 'NEW' then 'FU'
- when et.[Description] = 'New Business' then 'NEW'
- when et.[Description] = 'Follow - Up' then 'FU'
- when et.[Description] = 'Continuation' then 'CONT'
- end,m.MattCategory) [EngType_CCC]
- , a.State as [State]
- , mi.Description [MajorIndustry]
- , m.[EngSignedDate_CCC]
- , CASE WHEN d.Mattindex is not null THEN coalesce( case when eu.[NxUnit] = 20 then coalesce(ph.[SignedDate], ph.[EffStart]) else ph.[SignedDate] end,o.[Engagement_Letter_Signed_Date__c], o.[CloseDate]) ELSE coalesce(o.[Engagement_Letter_Signed_Date__c], case when eu.[NxUnit] = 20 then coalesce(ph.[SignedDate], ph.[EffStart]) else ph.[SignedDate] end, o.[CloseDate]) END [Signed_Date]
- , CASE WHEN d.Mattindex is not null THEN coalesce(m.[EngSignedDate_CCC], o.[Engagement_Letter_Signed_Date__c], o.[CloseDate]) ELSE coalesce(o.[Engagement_Letter_Signed_Date__c], m.[EngSignedDate_CCC], o.[CloseDate]) END [OriginalSignedDate]
- , CASE WHEN d.Mattindex is not null THEN
- coalesce(
- m.MattCategory
- , case
- when et.[Description] = 'New Business' then 'NEW'
- when et.[Description] = 'Follow - Up' then 'FU'
- when et.[Description] = 'Continuation' then 'CONT'
- end
- , case
- when o.[Type] = 'New Business' and COALESCE(Cloned.IsCloned_CCC,0) = 0 then 'NEW'
- when o.[Type] = 'Follow-Up' and COALESCE(Cloned.IsCloned_CCC,0) = 0 then 'FU'
- when o.[Type] = 'Continuation' and COALESCE(Cloned.IsCloned_CCC,0) = 0 then 'CONT'
- end ) ELSE
- coalesce(case
- when o.[Type] = 'New Business' and COALESCE(Cloned.IsCloned_CCC,0) = 0 then 'NEW'
- when o.[Type] = 'Follow-Up' and COALESCE(Cloned.IsCloned_CCC,0) = 0 then 'FU'
- when o.[Type] = 'Continuation' and COALESCE(Cloned.IsCloned_CCC,0) = 0 then 'CONT'
- end
- , m.MattCategory
- , case
- when et.[Description] = 'New Business' then 'NEW'
- when et.[Description] = 'Follow - Up' then 'FU'
- when et.[Description] = 'Continuation' then 'CONT'
- end) END [MattCategory]
- , m.[MattStatus]
- , coalesce(o.[BD1_TKID], case when eu.[NxUnit] = 20 then atk.[BD1_ID] end,-1) [BD1_ID]
- , coalesce(o.[BD2_TKID], case when eu.[NxUnit] = 20 then atk.[BD2_ID] end,-1) [BD2_ID]
- , coalesce(atk.[BD3_ID],-1) [BD3_ID]
- , coalesce(o.[SOE1_TKID], case when eu.[NxUnit] = 20 then atk.[SOE1_ID] end,-1) [SOE_1_ID]
- , coalesce(o.[SOE2_TKID], case when eu.[NxUnit] = 20 then atk.[SOE2_ID] end,-1) [SOE_2_ID]
- , coalesce(qc.[QC_ID],-1) [QC_ID]
- , coalesce(md.[TD_ID],-1) [TD_ID]
- , coalesce(md.[PM_ID],-1) [PM_ID]
- , CASE WHEN pg.Description in ('R&D Services', 'SALT Services') THEN 110 ELSE pg.[Code] END [PracticeGroupCode]
- , pg.[Description] [ServiceLine]
- , count(m.[OpportunityID_CCC]) over(partition by m.[OpportunityID_CCC]) [SFOppCnt]
- , o.[Amount]
- , CAST(o.[Credit] as Decimal(18,2)) [SFCredit]
- , ph.[EffStart]
- , ph.[OrigWIP]
- --, ph.[AdjWIP]
- , CASE WHEN pg.[Code] in ('110','120','130','225') AND ph.AdjWIP != 0 Then CAST(COALESCE(FeeCapPct,o.FeeCap)*(PHCredit) as Decimal(18,2)) else ph.AdjWIP end [AdjWIP]
- --, ph.[RemainingWIP]
- , CASE WHEN pg.[Code] in ('110','120','130','225') and StudyCredit is not null and StudyCredit > 0
- then CAST(ph.[RemainingWIP]*(PHCredit/StudyCredit) as Decimal(18,2)) else ph.RemainingWIP end [RemainingWIP]
- , ph.[VAERFN]
- , ph.[PHCredit]
- , ph.[CurrentTaxYearPct]
- , ph.[FutureTaxYearPct]
- , ph.[FutureTaxYearTodayCnt]
- , ph.[FutureTaxYearCnt]
- , ph.[CurrentTaxYearCnt]
- , coalesce(ph.[VAERFNDeliveredCnt],0) [VAERFNDeliveredCnt]
- , coalesce(al.[SignedByGECnt],0) [SignedByGECnt]
- --, coalesce(case when coalesce(ph.[VAERFNDeliveredCnt],0) = 0 and pg.[Code] = 130 and datediff(dd,cast(coalesce(o.[Engagement_Letter_Signed_Date__c], m.[EngSignedDate_CCC], o.[CloseDate]) as date), cast(getdate() as date)) > 60 and coalesce(al.[SignedByGECnt], 0) = 0 then 1 end, 0) [179DPast60D]
- , coalesce(case when coalesce(ph.[VAERFNDeliveredCnt],0) = 0 and pg.[Code] = 130 and datediff(dd,cast(coalesce(o.[Engagement_Letter_Signed_Date__c], m.[EngSignedDate_CCC], o.[CloseDate]) as date), cast(getdate() as date)) > 60 /* Changed to 60 from 150 per NP 7/7/22-KR*/ and coalesce(al.[SignedByGECnt], 0) = 0 then 1 end, 0) [179DWriteDownFlag]
- , coalesce(case when pg.[Code] = 130 and datediff(dd,cast(coalesce(o.[Engagement_Letter_Signed_Date__c], m.[EngSignedDate_CCC], o.[CloseDate]) as date), cast(getdate() as date)) <= 60 /* some other bs from Spencer 5/11/23-KR*/ then 1 end, 0) [179DUnder60Flag]
- , coalesce(oa.BD1_Allocation__c2,1) [BD1_Allocation]
- , coalesce(oa.BD2_Allocation__c2,0) [BD2_Allocation]
- , coalesce(oa.BD3_Allocation__c2,0) [BD3_Allocation]
- , coalesce(oa.RD1_Allocation__c2,1) [RD1_Allocation]
- , coalesce(oa.RD2_Allocation__c2,0) [RD2_Allocation]
- --, coalesce(im.[IMFee],0) [Billed_Amount]
- , row_number() over(partition by m.[Client], replace(pg.[Description],'SALT','R&D') order by m.[Number]) [Rn]
- --, sum(coalesce(im.[IMFee],0)) over(partition by m.[Client], replace(pg.[Description],'SALT','R&D')) [TotalBilledClient]
- , sum(coalesce(ph.AdjWIP,0)) over(partition by m.[Client], replace(pg.[Description],'SALT','R&D') order by m.MattIndex) [SubtotalAdjWIPClient]
- --, coalesce(ar.[Reciept],0) [Fees_Collected]
- , coalesce(CASE WHEN pg.[Code] in ('110','120','130') and StudyCredit is not null and StudyCredit > 0
- then ar.[Reciept]*(PHCredit/StudyCredit) else ar.[Reciept] end,0) [Fees_Collected]
- , coalesce(tc.[WorkHrs],0) [Hours_Worked]
- , coalesce(tc.[WorkAmt],0) [WorkAmt]
- , coalesce(mp.[Pending_Invoices],0) [Pending_Invoices]
- , eu.[NxUnit]
- , case when bg.matter is not null then 1 else 0 end [BillingGroup]
- , coalesce(ortb.[Total_Invoiced],0) [R&D_Invoiced]
- , 0 [R&D_Invoiced_Overrun]
- , coalesce(ortb.[Total_Invoiced],0) [R&D_TotalInvoiced]
- , coalesce(ortb.[Total_Invoiced],0) [ERC_Invoiced]
- , 0 [ERC_Invoiced_Overrun]
- , coalesce(ortb.[Total_Invoiced],0) [ERC_TotalInvoiced]
- --, coalesce(ortb.[Total_Invoiced],0) [Total_Invoiced]
- , coalesce(CASE WHEN pg.[Code] in ('110','120','130') and StudyCredit is not null and StudyCredit > 0
- then ortb.[Total_Invoiced]*(PHCredit/StudyCredit) else ortb.[Total_Invoiced] end,0) [Total_Invoiced]
- --, [tax_Year]
- , Case When MaxTaxYear> MinTaxYear then 'Multi' else 'Single' end [StudyYears]
- , m.IsEvergreen_CCC
- ,CASE WHEN d.Mattindex is not null THEN year(coalesce( m.[EngSignedDate_CCC],o.Engagement_Letter_Signed_Date__c, o.CloseDate)) Else year(coalesce(o.Engagement_Letter_Signed_Date__c, m.[EngSignedDate_CCC], o.CloseDate)) END [YearEngSigned]
- , Evergreen_2__c
- , COALESCE(MinTaxYear, year(
- --coalesce(o.Engagement_Letter_Signed_Date__c, m.[EngSignedDate_CCC], o.CloseDate))
- CASE WHEN o.Engagement_Letter_Signed_Date__c<=COALESCE(m.[EngSignedDate_CCC],o.Engagement_Letter_Signed_Date__c) AND o.Engagement_Letter_Signed_Date__c<=COALESCE(o.CloseDate,o.Engagement_Letter_Signed_Date__c) AND o.Engagement_Letter_Signed_Date__c is not null THEN o.Engagement_Letter_Signed_Date__c
- WHEN m.[EngSignedDate_CCC]<=COALESCE(o.CloseDate,m.[EngSignedDate_CCC]) AND m.[EngSignedDate_CCC] is not null THEN m.[EngSignedDate_CCC]
- WHEN o.CloseDate IS not null THEN o.CloseDate
- ELSE coalesce(o.Engagement_Letter_Signed_Date__c, m.[EngSignedDate_CCC], o.CloseDate)
- END )
- ) MinTaxYear --MinTaxYear
- , MaxTaxYear
- , StudyYear
- , o.Fee_Cap_Percentage__c
- ,COALESCE(FeeCapPct,o.FeeCap) FeeCap
- , CASE WHEN ph.TimeStampFromYesterday > 0 THEN 1
- WHEN m.TimeStamp > GETDATE()-1 THEN 1
- WHEN c.TimeStamp > GETDATE()-1 THEN 1
- WHEN eu.TimeStamp > GETDATE()-1 THEN 1
- WHEN atk.TimeStamp > GETDATE()-1 THEN 1
- WHEN MD.TimeStamp > GETDATE()-1 THEN 1
- WHEN TC.TimeStamp > GETDATE()-1 THEN 1
- ELSE 1 /* force updates 0*/ END [TimeStampFromYesterday]
- ,o.Id
- ,CASE WHEN pg.[Code] = 225 THEN 0 WHEN Cloned.IsCloned_CCC = 1 OR ((m.[MattCategory] = 'FU' and COALESCE(m.[IsEvergreen_CCC],0) = 1 and (COALESCE(o.[evergreen_2__c],'-1') = 'Yes' OR o.Id is null OR NULLIF(d.Mattindex,FirstFU.Mattindex) is not null)) AND FirstFU.Mattindex is null AND YEAR(m.EngSignedDate_CCC)<=2018) THEN 1 ELSE 0 END IsCloned_CCC
- ,d.Mattindex dual
- ,FirstFU.Mattindex FirstFU
- from
- [TE_3E_PROD_CLONE].[dbo].[Matter] m
- LEFT JOIN
- (SELECT MAttindex,IsCloned_CCC
- FROM
- (
- SELECT
- LEAD(m.MattIndex,1)OVER(PARTITION BY OpportunityID_CCC,Client Order by OpenDate,m.Mattindex) MattIndex
- , 1 IsCloned_CCC
- , LEAD(OpportunityID_CCC,1)OVER(PARTITION BY OpportunityID_CCC,Client Order by OpenDate,m.Mattindex) OpportunityID_CCC
- , LEAD(EngID_CCC,1)OVER(PARTITION BY OpportunityID_CCC,Client Order by OpenDate,m.Mattindex) EngID_CCC
- FROM
- TE_3E_PROD_Clone..Matter M
- LEFT JOIN (SELECT Mattindex FROM TE_3E_PROD_CLone..matter_audit WHERE IsEvergreen_CCC = 1 GROUP BY Mattindex) waseg on waseg.MAttindex = M.Mattindex
- WHERE IsEvergreen_CCC = 1 or waseg.MattIndex is not null
- ) a
- WHERE
- (IsCloned_CCC = 1 and OpportunityID_CCC != EngID_CCC and LEFT(EngID_CCC,2) != '00')
- OR (LEFT(OpportunityID_CCC,2) != '00')
- ) cloned on cloned.MAttindex = m.Mattindex
- LEFT JOIN
- #Duals d on d.Mattindex = m.MattIndex
- LEFT JOIN
- (
- SELECT MIN(MattINdex) Mattindex
- FROM
- TE_3E_PROD_Clone..Matter
- WHERE
- MattCategory = 'FU'
- AND
- OpportunityID_CCC is not null
- AND
- [IsEvergreen_CCC] = 1
- GROUP BY
- OpportunityID_CCC
- HAVING COUNT(Mattindex)>1
- ) FirstFU on FirstFU.Mattindex = m.MattIndex
- join
- [TE_3E_PROD_CLONE].[dbo].[Client] c on c.ClientIndex = m.Client
- left JOIN
- TE_3E_PROD_Clone..Site s on s.SiteIndex = c.InvoiceSite
- left JOIN
- TE_3E_PROD_Clone..address a on a.addrindex = s.address
- LEFT JOIN
- TE_3E_PROD_Clone..MajorIndustry_CCC mi on mi.Code = c.MajorIndustry_CCC
- left join
- (
- select [Entity], [NxUnit], row_number() over(partition by [Entity] order by timestamp desc) [Rn]
- , TimeStamp [TimeStamp]
- from [TE_3E_PROD_CLONE].[dbo].[EntityUnit_CCC]
- ) eu on eu.[Entity] = c.[Entity] and eu.[Rn] = 1
- left join
- [TE_3E_PROD_CLONE].[dbo].[EngType_CCC] et on et.[Code] = m.[EngType_CCC]
- left join
- (
- select
- row_number() over (partition by [MatterLkUp] order by [EffStart] desc) [RN]
- , [MatterLkUp]
- , [TimeStamp]
- , (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e where e.[3E_Source_TK_Id] = atk.[BDTkpr1] and e.[SCDIsCurrent] = 1 order by SF_Source_Id desc) [BD1_ID]
- , (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e where e.[3E_Source_TK_Id] = atk.[BDTkpr2] and e.[SCDIsCurrent] = 1 order by SF_Source_Id desc) [BD2_ID]
- , (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e where e.[3E_Source_TK_Id] = atk.[BDTkpr3] and e.[SCDIsCurrent] = 1 order by SF_Source_Id desc) [BD3_ID]
- , (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e where e.[3E_Source_TK_Id] = atk.[SOETkpr1] and e.[SCDIsCurrent] = 1 order by SF_Source_Id desc) [SOE1_ID]
- , (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e where e.[3E_Source_TK_Id] = atk.[SOETkpr2] and e.[SCDIsCurrent] = 1 order by SF_Source_Id desc) [SOE2_ID]
- from
- [TE_3E_PROD_CLONE].[dbo].[AssociatedTkprs_CCC] atk
- ) atk on atk.[MatterLkUp] = m.[MattIndex] and atk.[rn] = 1
- left join
- (
- select
- row_number() over (partition by [matterlkup] order by [NxEndDate] desc, [NxStartDate] desc, [EffStart] desc) [rn]
- , [MatterLkUp]
- , [SpvTkpr]
- , [RspTkpr]
- , (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e where e.[3E_Source_TK_Id] = [SpvTkpr] and e.[SCDIsCurrent] = 1) [TD_ID]
- , (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e where e.[3E_Source_TK_Id] = [RspTkpr] and e.[SCDIsCurrent] = 1) [PM_ID]
- , [PracticeGroup]
- , [TimeStamp]
- from
- [TE_3E_PROD_CLONE].[dbo].[MattDate] md
- ) MD on MD.[MatterLkUp] = M.[MattIndex] and md.[rn] = 1
- left join
- [TE_3E_PROD_CLONE].[dbo].[PracticeGroup] pg on pg.[Code] = md.[PracticeGroup]
- left join
- (
- select tc.[Matter], sum(tc.[WorkHrs]) [WorkHrs], sum(tc.[WorkAmt]) [WorkAmt], Max(TimeStamp) [TimeStamp]
- from [TE_3E_PROD_CLONE].[dbo].[Timecard] tc
- where tc.[IsActive] = 1
- group by tc.[Matter]
- ) tc on tc.Matter = m.MattIndex
- left join
- (
- select
- [MattIndex]
- , [PGDetHdr_CCCID]
- , [AdjWIP]
- , [RemainingWIP]
- , [OrigWIP]
- , [EngSignedDate_CCC]
- , [EffStart]
- , [MaxTaxYear]
- , [MinTaxYear]
- , [TaxYearGreaterThanEL]
- , /*case
- when [OpportunityID_CCC] is null and [MattCategory] = 'FU' and [IsEvergreen_CCC] = 1 and [TaxYearGreaterThanEL] = 1
- then cast(cast([MaxTaxYear] + 1 as char(4)) + '0101' as datetime)
- else*/ [EngSignedDate_CCC]
- /*end*/ [SignedDate]
- , [Credit] [PHCredit]
- , [StudyCredit]
- , [VAERFN]
- , [VAERFNDeliveredCnt]
- , [TaxYearCnt]
- , [FutureTaxYearCnt]
- , [CurrentTaxYearCnt]
- --, case when [FutureTaxYearCnt] = 0 then 0 else [TaxYearCnt] / [FutureTaxYearCnt] end [FutureTaxYearPct]
- --, case when [CurrentTaxYearCnt] = 0 then 0 else [TaxYearCnt] / [CurrentTaxYearCnt] end [CurrentTaxYearPct]
- , case when [TaxYearCnt] = 0 then 0 else cast([FutureTaxYearCnt] as float) / cast([TaxYearCnt] as float) end [FutureTaxYearPct]
- , case when [TaxYearCnt] = 0 then 0 else cast([CurrentTaxYearCnt] as float) / cast([TaxYearCnt] as float) end [CurrentTaxYearPct]
- , [FutureTaxYearTodayCnt]
- , [TimeStampFromYesterday]
- , [StudyYear]
- ,Id
- ,FeeCapPct
- from
- (
- select
- [MattIndex]
- , [EngSignedDate_CCC]
- , [MattCategory]
- , [IsEvergreen_CCC]
- , [OpportunityID_CCC]
- , [PGDetHdr_CCCID]
- , [AdjWIP]
- , [RemainingWIP]
- , [OrigWIP]
- , [EffStart]
- , [ELSigned]
- , max([Year]) [MaxTaxYear]
- , min([Year]) [MinTaxYear]
- , sum([TaxYearGreaterThanEL]) [TaxYearGreaterThanEL]
- , sum([Credit]) [Credit]
- , sum([VAERFN]) [VAERFN]
- , sum([VAERFNDeliveredCnt]) [VAERFNDeliveredCnt]
- , sum([TaxYearCnt]) [TaxYearCnt]
- , sum([FutureTaxYearCnt]) [FutureTaxYearCnt]
- , sum([CurrentTaxYearCnt]) [CurrentTaxYearCnt]
- , sum([FutureTaxYearTodayCnt]) [FutureTaxYearTodayCnt]
- , sum([TimeStampFromYesterday]) [TimeStampFromYesterday]
- , [StudyCredit]
- --, CASE WHEN [PracticeGroup] in ('110','120','130') and (pc.[YEAR] IS NULL OR pc.[YEAR] < Year([ELSigned])) Then 'PreviousYear'
- -- WHEN [PracticeGroup] in ('110','120','130') and pc.[YEAR] = Year([ELSigned]) Then 'CurrentYear'
- -- WHEN [PracticeGroup] in ('110','120','130') and pc.[YEAR] > Year([ELSigned]) Then 'FutureYear'
- -- Else NULL END 'StudyYear'
- ,CASE WHEN [PracticeGroup] in ('110','120','130')
- THEN CASE WHEN pc.Year>YEAR(DATEADD(M,-pc.Month_CCC,pc.EngSignedDate_CCC)) THEN pc.Year -- 'FutureYear'
- --WHEN pc.Year=YEAR(DATEADD(M,-pc.Month_CCC,pc.EngSignedDate_CCC)) THEN 'CurrentYear'
- ELSE 0 END ELSE NULL END [StudyYear]
- ,MAX(pc.Id) Id
- ,FeeCapPct
- from
- (
- select
- m.MattIndex
- , m.[EngSignedDate_CCC]
- , m.[MattCategory]
- , m.Month_CCC
- , m.[IsEvergreen_CCC]
- , m.[OpportunityID_CCC]
- , ph.[MatterLkUp]
- , ph.[PGDetHdr_CCCID]
- , ph.[AdjWIP]
- , ph.[RemainingWIP]
- , ph.[OrigWIP]
- , ph.[EffStart]
- , coalesce(o.[Engagement_Letter_Signed_Date__c], m.[EngSignedDate_CCC], o.[CloseDate]) [ELSigned]
- , COALESCE(pc.[Year],CASE WHEN YEAR(m.[EngSignedDate_CCC])<YEAR(m.OpenDate) THEN YEAR(DATEADD(M,-6,ph.[EffStart])) ELSE YEAR(ph.[EffStart]) END, year(
- --coalesce(o.Engagement_Letter_Signed_Date__c, m.[EngSignedDate_CCC], o.CloseDate))
- CASE WHEN o.Engagement_Letter_Signed_Date__c<=COALESCE(m.[EngSignedDate_CCC],o.Engagement_Letter_Signed_Date__c) AND o.Engagement_Letter_Signed_Date__c<=COALESCE(o.CloseDate,o.Engagement_Letter_Signed_Date__c) AND o.Engagement_Letter_Signed_Date__c is not null THEN o.Engagement_Letter_Signed_Date__c
- WHEN m.[EngSignedDate_CCC]<=COALESCE(o.CloseDate,m.[EngSignedDate_CCC]) AND m.[EngSignedDate_CCC] is not null THEN m.[EngSignedDate_CCC]
- WHEN o.CloseDate IS not null THEN o.CloseDate
- ELSE coalesce(o.Engagement_Letter_Signed_Date__c, m.[EngSignedDate_CCC], o.CloseDate)
- END )) [Year]
- , case when (sum(case when pc.[Year] >= CASE WHEN m.mattcategory = 'FU' THEN YEAR(m.[EngSignedDate_CCC])+1 ELSE year(coalesce(o.[Engagement_Letter_Signed_Date__c], m.[EngSignedDate_CCC], o.[CloseDate])) END then 1 else 0 end)) >= 1 then 1 else 0 end [TaxYearGreaterThanEL]
- , sum(coalesce(pc.[TotalCredit], pc.[FinalCredit], pc.[EngineerReview], pc.[ValueAssessment], pc.[OrigCredit])) [Credit]
- , sum(coalesce(pcf.[TotalCredit], pcf.[FinalCredit], pcf.[EngineerReview], pcf.[ValueAssessment], pcf.[OrigCredit])) [StudyCredit]
- , sum(coalesce(pc.[FinalCredit], pc.[EngineerReview], pc.[ValueAssessment])) [VAERFN]
- , coalesce(sum(case when pc.[ValueAssessment] is not null or pc.[EngineerReview] is not null or pc.[FinalCredit] is not null then 1 end),0) [VAERFNDeliveredCnt]
- , coalesce(sum(case when pc.[Year] is not null then 1 end),0) [TaxYearCnt]
- , coalesce(sum(case when md.[PracticeGroup] = 225 then 0 when pc.[Year] >= CASE WHEN COALESCE(m.mattcategory,'New') = 'FU' AND m.EngType_CCC != 100 THEN YEAR(coalesce(m.[EngSignedDate_CCC],o.Engagement_Letter_Signed_Date__c))+1 ELSE year(coalesce(o.[Engagement_Letter_Signed_Date__c], m.[EngSignedDate_CCC], o.[CloseDate])) END then 1 end),0) [FutureTaxYearCnt]
- , coalesce(sum(case when md.[PracticeGroup] = 225 then 1 when pc.[Year] < CASE WHEN COALESCE(m.mattcategory,'New') = 'FU' AND m.EngType_CCC != 100 THEN YEAR(coalesce(m.[EngSignedDate_CCC],o.Engagement_Letter_Signed_Date__c))+1 ELSE year(coalesce(o.[Engagement_Letter_Signed_Date__c], m.[EngSignedDate_CCC], o.[CloseDate])) END then 1 end),0) [CurrentTaxYearCnt]
- , coalesce(sum(case when md.[PracticeGroup] = 225 then 0 when pc.[Year] >= CASE WHEN COALESCE(m.mattcategory,'New') = 'FU' AND m.EngType_CCC != 100 THEN YEAR(GETDATE())+1 ELSE year(GETDATE()) END then 1 end),0) [FutureTaxYearTodayCnt]
- , md.PracticeGroup
- , coalesce(sum(case when m.TimeStamp > GETDATE()-1 THEN 1
- when ph.TimeStamp > GETDATE()-1 THEN 1
- when md.TimeStamp > GETDATE()-1 THEN 1
- when pc.TimeStamp > GETDATE()-1 THEN 1
- ELSE 0 END),0) [TimeStampFromYesterday]
- ,o.Id
- ,FeeCapPct
- from
- [TE_3E_PROD_CLONE].[dbo].[Matter] m
- --left JOin [FP&App].bdm.BDMasterSource bd on bd.Number = m.Number COLLATE SQL_Latin1_General_CP1_CI_AS
- left join
- (
- select
- row_number() over (partition by [matterlkup] order by [NxEndDate] desc, [NxStartDate] , [EffStart] desc) [Rn]
- , [PGDetHdr_CCCID]
- , [MatterLkUp]
- , [AdjWIP]
- , [RemainingWIP]
- , [OrigWIP]
- , [EffStart]
- , [TimeStamp]
- , FeeCapPct/100 FeeCapPct
- from
- [TE_3E_PROD_CLONE].[dbo].[PGDetHdr_CCC]
- ) ph on ph.[MatterLkUp] = m.[MattIndex] and ph.[Rn] = 1
- left join
- (
- select
- row_number() over(partition by md.MatterLkUp order by md.effstart desc, md.nxStartDate , md.nxEndDate desc) [Rn]
- , md.MatterLkUp
- , md.[PracticeGroup]
- , TimeStamp
- from
- TE_3E_PROD_Clone.dbo.MattDate md
- ) md on md.MatterLkUp = m.MattIndex and md.[Rn] = 1
- left join
- (
- select
- pc1.[PGDetHdr]
- , [Year]
- , sum(pc1.[OrigCredit])+SUM(COALESCE(adj.[OrigCredit],0)) [OrigCredit]
- , sum(pc1.[ValueAssessment])+SUM(COALESCE(adj.[ValueAssessment],0)) [ValueAssessment]
- , sum(pc1.[EngineerReview])+SUM(COALESCE(adj.[EngineerReview],0)) [EngineerReview]
- , sum(pc1.[FinalCredit])+SUM(COALESCE(adj.[FinalCredit],0)) [FinalCredit]
- , sum(pc1.[Total])+SUM(COALESCE(adj.[Total],0)) [TotalCredit]
- , MAX(timestamp) [TimeStamp]
- from
- [TE_3E_PROD_CLONE].[dbo].[PGDetChild_CCC] pc1
- LEFT JOIN
- (SELECT [PGDetHdr]
- ,SUM(CASE WHEN year is null THEN [OrigCredit] ELSE 0 END)/NULLIF(COUNT(CASE WHEN year is not null THEN [OrigCredit] END),0)[OrigCredit]
- ,SUM(CASE WHEN year is null THEN [ValueAssessment] ELSE 0 END)/NULLIF(COUNT(CASE WHEN year is not null THEN [ValueAssessment] END),0)[ValueAssessment]
- ,SUM(CASE WHEN year is null THEN [EngineerReview] ELSE 0 END)/NULLIF(COUNT(CASE WHEN year is not null THEN [EngineerReview] END),0)[EngineerReview]
- ,SUM(CASE WHEN year is null THEN [FinalCredit] ELSE 0 END)/NULLIF(COUNT(CASE WHEN year is not null THEN [FinalCredit] END),0)[FinalCredit]
- ,SUM(CASE WHEN year is null THEN [Total] ELSE 0 END)/NULLIF(COUNT(CASE WHEN year is not null THEN [Total] END),0)[Total]
- FROM
- [TE_3E_PROD_CLONE].[dbo].[PGDetChild_CCC]
- GROUP BY [PGDetHdr]) adj on adj.PGDetHdr = pc1.PGDetHdr
- where COALESCE(pc1.IsGeneralWork,0) = 0 and pc1.year is not null
- group by
- pc1.[PGDetHdr]
- , [Year]
- ) pc on pc.[PGDetHdr] = ph.[PGDetHdr_CCCID]
- left join
- (
- select
- [PGDetHdr]
- , sum([OrigCredit]) [OrigCredit]
- , sum([ValueAssessment]) [ValueAssessment]
- , sum([EngineerReview]) [EngineerReview]
- , sum([FinalCredit]) [FinalCredit]
- , sum([Total]) [TotalCredit]
- , MAX(timestamp) [TimeStamp]
- from
- [TE_3E_PROD_CLONE].[dbo].[PGDetChild_CCC] where COALESCE(IsGeneralWork,0) = 0--where [Year] is not null
- group by
- [PGDetHdr]
- ) pcf on pcf.[PGDetHdr] = ph.[PGDetHdr_CCCID]
- left join
- [SalesforceClone].[dbo].[Opportunity] o on o.[ID] = m.[OpportunityID_CCC] collate SQL_Latin1_General_CP1_CI_AS
- --where LEFT(m.Number,6) = '313717'
- group by
- m.MattIndex
- , m.[EngSignedDate_CCC]
- , m.[MattCategory]
- , m.Month_CCC
- , m.[IsEvergreen_CCC]
- , m.[OpportunityID_CCC]
- , ph.[MatterLkUp]
- , ph.[PGDetHdr_CCCID]
- , ph.[AdjWIP]
- , ph.[RemainingWIP]
- , ph.[OrigWIP]
- , ph.[EffStart]
- , coalesce(o.[Engagement_Letter_Signed_Date__c], m.[EngSignedDate_CCC], o.[CloseDate])
- , COALESCE(pc.[Year],CASE WHEN YEAR(m.[EngSignedDate_CCC])<YEAR(m.OpenDate) THEN YEAR(DATEADD(M,-6,ph.[EffStart])) ELSE YEAR(ph.[EffStart]) END, year(
- --coalesce(o.Engagement_Letter_Signed_Date__c, m.[EngSignedDate_CCC], o.CloseDate))
- CASE WHEN o.Engagement_Letter_Signed_Date__c<=COALESCE(m.[EngSignedDate_CCC],o.Engagement_Letter_Signed_Date__c) AND o.Engagement_Letter_Signed_Date__c<=COALESCE(o.CloseDate,o.Engagement_Letter_Signed_Date__c) AND o.Engagement_Letter_Signed_Date__c is not null THEN o.Engagement_Letter_Signed_Date__c
- WHEN m.[EngSignedDate_CCC]<=COALESCE(o.CloseDate,m.[EngSignedDate_CCC]) AND m.[EngSignedDate_CCC] is not null THEN m.[EngSignedDate_CCC]
- WHEN o.CloseDate IS not null THEN o.CloseDate
- ELSE coalesce(o.Engagement_Letter_Signed_Date__c, m.[EngSignedDate_CCC], o.CloseDate)
- END )) --pc.[Year]
- , md.PracticeGroup
- ,o.id
- ,FeeCapPct
- ) pc
- group by
- MattIndex
- , [EngSignedDate_CCC]
- , [MattCategory]
- , [IsEvergreen_CCC]
- , [OpportunityID_CCC]
- , [PGDetHdr_CCCID]
- , [AdjWIP]
- , [RemainingWIP]
- , [OrigWIP]
- , [EffStart]
- , [ELSigned]
- , [StudyCredit]
- --, CASE WHEN [PracticeGroup] in ('110','120','130') and (pc.[YEAR] IS NULL OR pc.[YEAR] < Year([ELSigned])) Then 'PreviousYear'
- -- WHEN [PracticeGroup] in ('110','120','130') and pc.[YEAR] = Year([ELSigned]) Then 'CurrentYear'
- -- WHEN [PracticeGroup] in ('110','120','130') and pc.[YEAR] > Year([ELSigned]) Then 'FutureYear'
- -- Else NULL END
- ,CASE WHEN [PracticeGroup] in ('110','120','130')
- THEN CASE WHEN pc.Year>YEAR(DATEADD(M,-pc.Month_CCC,pc.EngSignedDate_CCC)) THEN pc.Year --'FutureYear'
- --WHEN pc.Year=YEAR(DATEADD(M,-pc.Month_CCC,pc.EngSignedDate_CCC)) THEN 'CurrentYear'
- ELSE 0 END ELSE NULL END
- ,FeeCapPct
- ) a
- ) ph on ph.[MattIndex] = M.[MattIndex]
- left join
- (
- select
- ptm.[fileID]
- , f.[fileAccCode]
- , feqc.[feeExtID]
- , ptm.[projectrole]
- , ptm.[isPrimary]
- , (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e where e.[3E_Source_TK_Id] = feqc.[feeExtID] and e.[SCDIsCurrent] = 1) [QC_ID]
- , row_number() over (partition by ptm.[fileID] order by ptm.[isPrimary] desc) [Rn]
- from
- [MS_LIVE_Clone].[dbo].[udFiProjectTeam] ptm
- left join
- [MS_LIVE_Clone].[config].[dbFile] f on ptm.[fileID] = f.[fileID]
- left join
- [MS_LIVE_Clone].[dbo].[dbFeeEarner] FEQC on FEQC.[feeusrID] = ptm.[employee]
- where
- ptm.[projectRole] = 'QC'
- and f.[fileAccCode] is not null
- ) qc on qc.[fileAccCode] = m.[MattIndex] and qc.[rn] = 1
- left join
- (
- select
- [Opportunity__c]
- , case when [BD1_Allocation__c] > 1 then [BD1_Allocation__c] / 100 else [BD1_Allocation__c] end [BD1_Allocation__c2]
- , case when [BD2_Allocation__c] > 1 then [BD2_Allocation__c] / 100 else [BD2_Allocation__c] end [BD2_Allocation__c2]
- , case when [BD3_Allocation__c] > 1 then [BD3_Allocation__c] / 100 else [BD3_Allocation__c] end [BD3_Allocation__c2]
- , case when [RD1_Allocation__c] > 1 then [RD1_Allocation__c] / 100 else [RD1_Allocation__c] end [RD1_Allocation__c2]
- , case when [RD2_Allocation__c] > 1 then [RD2_Allocation__c] / 100 else [RD2_Allocation__c] end [RD2_Allocation__c2]
- , row_number() over(partition by [Opportunity__C] order by lastmodifiedDate desc) [Rn]
- from
- [SalesforceClone].[dbo].[Opportunity_Analytics__c]
- ) OA on OA.[Opportunity__c] = M.[OpportunityID_CCC] collate SQL_Latin1_General_CP1_CI_AS and oa.Rn = 1
- left join
- (
- select
- o.[Id]
- , o.[Engagement_Letter_Signed_Date__c]
- , o.[CloseDate]
- , o.[Amount]
- , o.[Type]
- , o.[Fee_Cap_Percentage__c]
- ,(CASE
- WHEN o.[Fee_Cap_Percentage__c] is not null then o.[Fee_Cap_Percentage__c]
- WHEN o.[Fee_Cap_Percentage_Gross__c] is not null then o.[Fee_Cap_Percentage_Gross__c]
- ELSE o.[Fee_Cap_Percentage_Input__c]
- END) / 100 [FeeCap]
- , case
- when o.[Amount] is null or o.[Fee_Cap_Percentage__c] is null then null
- when o.[Amount] = 0 or o.[Fee_Cap_Percentage__c] = 0 then 0
- else o.[Amount] / (o.[Fee_Cap_Percentage__c] / 100)
- end [Credit]
- , (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e
- left join [MS_LIVE_Clone].[dbo].dbFeeEarner msfe on msfe.feeExtID = e.[3E_Source_TK_Id]
- left join [MS_LIVE_Clone].[dbo].dbUser msu on msu.usrID = msfe.feeusrID
- left join [SalesforceClone].[dbo].[User] u on u.email = msu.usrEmail
- where u.id = o.OwnerId and e.[SCDIsCurrent] = 1
- order by e.SF_Source_id desc) [BD1_TKID]
- , (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e
- left join [MS_LIVE_Clone].[dbo].dbFeeEarner msfe on msfe.feeExtID = e.[3E_Source_TK_Id]
- left join [MS_LIVE_Clone].[dbo].dbUser msu on msu.usrID = msfe.feeusrID
- left join [SalesforceClone].[dbo].[User] u on u.email = msu.usrEmail
- where u.id = o.Primary_Director_Name__c and e.[SCDIsCurrent] = 1
- order by e.SF_Source_id desc) [BD2_TKID]
- , (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e
- left join [MS_LIVE_Clone].[dbo].dbFeeEarner msfe on msfe.feeExtID = e.[3E_Source_TK_Id]
- left join [MS_LIVE_Clone].[dbo].dbUser msu on msu.usrID = msfe.feeusrID
- left join [SalesforceClone].[dbo].[User] u on u.email = msu.usrEmail
- where u.id = o.Primary_Relationship_Director__c and e.[SCDIsCurrent] = 1
- order by e.SF_Source_id desc) [SOE1_TKID]
- , (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e
- left join [MS_LIVE_Clone].[dbo].[dbFeeEarner] msfe on msfe.[feeExtID] = e.[3E_Source_TK_Id]
- left join [MS_LIVE_Clone].[dbo].[dbUser] msu on msu.[usrID] = msfe.[feeusrID]
- left join [SalesforceClone].[dbo].[User] u on u.[email] = msu.[usrEmail]
- where u.[id] = o.[X2nd_Relationship_Director__c] and e.[SCDIsCurrent] = 1
- order by e.[SF_Source_id] desc) [SOE2_TKID]
- ,o.Evergreen_2__c
- from
- [SalesforceClone].[dbo].[Opportunity] o
- where
- coalesce(o.ag_Company__c,'') != 'ForrestBrown'
- ) o on o.[ID] = m.[OpportunityID_CCC] collate SQL_Latin1_General_CP1_CI_AS
- left join
- (
- --select
- -- Matter
- --, sum([BillAmt]) [Total_Invoiced]
- --from
- --[TE_3E_PROD_Clone].[dbo].[TimeBill] TB
- --JOIN
- --[TE_3E_PROD_Clone].[dbo].[Timecard] TC on tc.TimeIndex = TB.TimeCard and TC.IsActive = 1 and LoadSource != 'Recon'
- --group by
- -- Matter
- SELECT Number,BilledSplit Total_Invoiced,[MinYear]
- FROM
- [FP&A].BDM.BDMasterMatterBilledCollected
- ) ortb on ortb.Number = m.Number COLLATE SQL_Latin1_General_CP1_CI_AS and ortb.[MinYear] = ph.MinTaxYear
- --left join
- -- (
- -- select [leadmatter], sum(orgfee) IMFee
- -- , MAX(timestamp) [TimeStamp]
- -- from [TE_3E_PROD_Clone].[dbo].[InvMaster]
- -- where [IsReversed] = 0
- -- group by [leadmatter]
- -- ) im on im.LeadMatter = m.MattIndex
- left join
- [TE_3E_PROD_Clone].dbo.[BillingGroupMatter] bg on bg.Matter = m.MattIndex
- left join
- (
- select
- [Matter]
- , coalesce(sum(case when [ARAmt] > 0 and [IsReversed] = 0 then [ARFee] end),0) [ARFee]
- , coalesce(sum(case when [IsCollection] = 1 then -[ARfee] end),0) [Reciept]
- , MAX(timestamp) [TimeStamp]
- from
- [TE_3E_PROD_Clone].dbo.[ARMaster]
- group by
- [Matter]
- ) ar on ar.Matter = m.MattIndex
- left join
- (
- select [leadmatter], coalesce(sum([TotAmt]),0) [Pending_Invoices]
- , MAX(pm.timestamp) [Timestamp]
- from [TE_3E_PROD_Clone].[dbo].[ProfMaster] pm
- join [TE_3E_PROD_Clone].[dbo].[Matter] m on m.[MattIndex] = pm.[LeadMatter]
- where [invmaster] is null and [profstatus] = 'Current'
- group by [leadmatter]
- ) MP on MP.[leadmatter] = M.[MattIndex]
- left join
- (
- select f.[fileExtLinkID], count(al.[AlStatus]) [SignedByGECnt]
- from [MS_LIVE_Clone].[dbo].[udAllocationLetter] al
- join [MS_LIVE_Clone].[config].[dbfile] f on f.fileID = al.fileID
- where al.[AlStatus] = 6
- group by f.[fileExtLinkID]
- ) al on al.[fileExtLinkID] = m.[MattIndex]
- --where LEFT(m.Number,6) = '313717'
- --coalesce(o.[Engagement_Letter_Signed_Date__c], m.[EngSignedDate_CCC], o.[CloseDate]) >= '1/1/2020'
- ) ma)ma
- ) m
- outer apply (select top 1 number from BDM.BDMasterSource f where f.number = m.number COLLATE SQL_Latin1_General_CP1_CI_AS and f.MinTaxYear = m.MinTaxYear) f
- Left JOIN Rubix.dim.Employee bd1 on bd1.EmployeeId = m.BD1_ID
- Left JOIN Rubix.dim.Employee bd2 on bd2.EmployeeId = m.BD2_ID
- Left JOIN Rubix.dim.Employee SOE1 on SOE1.EmployeeId = m.SOE_1_ID
- Left JOIN Rubix.dim.Employee SOE2 on SOE2.EmployeeId = m.SOE_2_ID
- Left JOIN Rubix.dim.Employee PM on PM.EmployeeId = m.PM_ID
- ) a
- order by
- a.[OriginalSignedDate]
- --select * from #bdmMatterInfo
- --where Number = '009810.0011'
- IF EXISTS (select count(*) from #bdmMatterInfo)
- BEGIN
- truncate table BDM.BDMasterMatterDataFrom3E
- Insert into BDM.BDMasterMatterDataFrom3E (
- [OpportunityID_CCC] ,
- [Number] ,
- [MattIndex] ,
- [AltNumber] ,
- [DisplayName] ,
- [Description] ,
- [Client] ,
- [ClientId] ,
- [CloseDate] ,
- [Currency] ,
- [IsEvergreenCCC] ,
- [ServiceLine] ,
- [State] ,
- [EngSignedDateCCC] ,
- [BD1ID] ,
- [BD2ID] ,
- [BD3ID] ,
- [SOE1ID] ,
- [SOE2ID] ,
- [QCID] ,
- [TDID] ,
- [PMID] ,
- [PBD] ,
- [SBD] ,
- [PRD] ,
- [SRD] ,
- [PM] ,
- [OriginalWIP] ,
- [Collected] ,
- [Credit] ,
- [Billed] ,
- [WorkedWIP] ,
- [PendingInvoices] ,
- [TotalWIP] ,
- [Hours_Worked] ,
- [RemainingWIP] ,
- [AdjustedWIP] ,
- [UpdatedWIP],
- [UnbilledWIP] ,
- [UnbilledWorkedWIP] ,
- [Balance] ,
- [UnworkedUnbilled] ,
- [BD1Allocation] ,
- [BD2Allocation] ,
- [BD3Allocation] ,
- [RD1Allocation] ,
- [RD2Allocation] ,
- [BD1OrgWIPAlloc] ,
- [BD2OrgWIPAlloc] ,
- [BD3OrgWIPAlloc] ,
- [RD1OrgWIPAlloc] ,
- [RD2OrgWIPAlloc] ,
- [BD1AdjWIPAlloc] ,
- [BD2AdjWIPAlloc] ,
- [BD3AdjWIPAlloc] ,
- [RD1AdjWIPAlloc] ,
- [RD2AdjWIPAlloc] ,
- [BD1FeesBilled] ,
- [BD2FeesBilled] ,
- [BD3FeesBilled] ,
- [RD1FeesBilled] ,
- [RD2FeesBilled] ,
- [BD1FeesCollected] ,
- [BD2FeesCollected] ,
- [BD3FeesCollected] ,
- [RD1FeesCollected] ,
- [RD2FeesCollected] ,
- [OriginalSignedDate] ,
- [VAERFNDeliveredCnt] ,
- [StudyYears] ,
- [MajorIndustry] ,
- [Code] ,
- [MattStatus] ,
- [MattCategory] ,
- [EngTypeCCC] ,
- [EngStatusCCC],
- [MinYear],
- [MaxYear],
- [1TimeAdj],
- [StudyYear],
- [RecordForUpdate],
- IsCloned_CCC)
- (SELECT DISTINCT [OpportunityID_CCC] ,
- [Number] ,
- [MattIndex] ,
- [AltNumber] ,
- [DisplayName] ,
- [Description] ,
- [Client] ,
- [ClientId] ,
- [CloseDate] ,
- [Currency] ,
- [IsEvergreenCCC] ,
- [ServiceLine] ,
- [State] ,
- [EngSignedDateCCC] ,
- [BD1ID] ,
- [BD2ID] ,
- [BD3ID] ,
- [SOE1ID] ,
- [SOE2ID] ,
- [QCID] ,
- [TDID] ,
- [PMID] ,
- [PBD] ,
- [SBD] ,
- [PRD] ,
- [SRD] ,
- [PM] ,
- [OriginalWIP] ,
- [Collected] ,
- [Credit] ,
- [Billed] ,
- [WorkedWIP] ,
- [PendingInvoices] ,
- [TotalWIP] ,
- [HoursWorked] ,
- [RemainingWIP] ,
- [AdjustedWIP] ,
- [UpdatedWIP],
- [UnbilledWIP] ,
- [UnbilledWorkedWIP] ,
- [Balance] ,
- [UnworkedUnbilled] ,
- [BD1Allocation] ,
- [BD2Allocation] ,
- [BD3Allocation] ,
- [RD1Allocation] ,
- [RD2Allocation] ,
- [BD1OrgWIPAlloc] ,
- [BD2OrgWIPAlloc] ,
- [BD3OrgWIPAlloc] ,
- [RD1OrgWIPAlloc] ,
- [RD2OrgWIPAlloc] ,
- [BD1AdjWIPAlloc] ,
- [BD2AdjWIPAlloc] ,
- [BD3AdjWIPAlloc] ,
- [RD1AdjWIPAlloc] ,
- [RD2AdjWIPAlloc] ,
- [BD1FeesBilled] ,
- [BD2FeesBilled] ,
- [BD3FeesBilled] ,
- [RD1FeesBilled] ,
- [RD2FeesBilled] ,
- [BD1FeesCollected] ,
- [BD2FeesCollected] ,
- [BD3FeesCollected] ,
- [RD1FeesCollected] ,
- [RD2FeesCollected] ,
- [OriginalSignedDate] ,
- [VAERFNDeliveredCnt] ,
- [StudyYears] ,
- [MajorIndustry] ,
- [Code] ,
- [MattStatus] ,
- [MattCategory] ,
- [EngTypeCCC] ,
- [EngStatusCCC],
- [MinTaxYear],
- [MaxTaxYear],
- [1TimeAdj],
- [StudyYear],
- [RecordForUpdate],
- IsCloned_CCC
- from #bdmMatterInfo)
- END
- END
- GO
- --Step 4
- USE [FP&A]
- GO
- /****** Object: StoredProcedure [BDM].[GETBDMasterSource] Script Date: 2/6/2025 10:25:49 AM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- CREATE PROCEDURE [BDM].[GETBDMasterSource]
- AS BEGIN
- --SET NOCOUNT ON
- -- Getting the latest logId from Log table
- Declare @LogId int, @LogSql nvarchar(100)
- SET @LogSql = 'SELECT TOP 1 @LogId = Id from [bdm].[BDMasterSource_Log] order by StartTime desc'
- EXEC sp_executesql @LogSql, N'@LogId int OUTPUT', @LogId = @LogId OUTPUT
- if(@LogId is null)
- begin
- SET @LogId = 0
- end
- SET @LogId = @LogId + 1;
- exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'ETL process starts'
- --Getting the Opportunities from Salesforce which are Closed
- if object_id('tempdb.dbo.#bdmoppstg','U') is not null
- drop table #bdmoppstg;
- select
- o.[Id]
- , o.[Name]
- , o.[StageName]
- , o.[CloseDate]
- , o.[Project_Name__c]
- , o.[Amount]
- , o.[Type]
- , o.[Service_Type__c]
- , case
- when o.[Service_Type__c] in ('R&D','179D') and o.[StageName] in ('Closed - Study in Process') then 1
- else 0
- end [Splitflag]
- , cast(o.[Engagement_Letter_Signed_Date__c] as date) [ELSignedDate]
- , o.[Years_Under_Study_Federal__c]
- , o.[Years_Under_Study_State__c]
- , o.[States__c]
- , o.[Fiscal_Year_End_2__c]
- into #bdmoppstg
- from
- [SalesforceClone].[dbo].[Opportunity] o
- where id <> '0064000000FtxLnAAJ'
- and (([Final_Intake_Created_By__c] is not null and [Final_Intake_Created_By__c] not like '%Bhavesh Zaveri%') or Stagename like 'Closed%')
- --o.[StageName] like 'Closed%' and id <> '0064000000FtxLnAAJ'
- --and (o.Years_Under_Study_Federal__c like '%?%' OR o.Years_Under_Study_State__c like '%?%')
- --and o.CloseDate >= '01/01/2020'
- --Evaluating Federal or State year to get the Year for Opportunity
- if object_id('tempdb.dbo.#bdmoppyearsstg','U') is not null
- drop table #bdmoppyearsstg;
- select
- o.[Id]
- , a.data [Year]
- into #bdmoppyearsstg
- from
- #bdmoppstg o
- cross apply
- [SalesforceClone].[dbo].[fStrtoTable]
- (
- case
- when o.[Years_Under_Study_Federal__c] is null then o.[Years_Under_Study_State__c]
- when o.[Years_Under_Study_State__c] is null then o.[Years_Under_Study_Federal__c]
- else concat(o.[Years_Under_Study_Federal__c],';',o.[Years_Under_Study_State__c])
- end
- , ';') a
- where
- [Splitflag] = 1
- group by
- o.[Id]
- , a.data
- --Getting Federal Year only
- if object_id('tempdb.dbo.#bdmoppFEDYears','U') is not null
- drop table #bdmoppFEDYears;
- select
- o.[Id]
- , a.Data [FEDYear]
- into #bdmoppFEDYears
- from
- #bdmoppstg o
- cross apply
- [SalesforceClone].[dbo].[fStrtoTable]([Years_Under_Study_Federal__c], ';') a
- where
- [Splitflag] = 1
- --Getting State year only
- if object_id('tempdb.dbo.#bdmoppStateYears','U') is not null
- drop table #bdmoppStateYears;
- select
- o.[Id]
- , a.[Data] [StateYear]
- into #bdmoppStateYears
- from
- #bdmoppstg o
- cross apply
- [SalesforceClone].[dbo].[fStrtoTable]([Years_Under_Study_State__c], ';') a
- where
- [Splitflag] = 1
- ;
- --Getting final year based on Federal year or State year.
- if object_id('tempdb.dbo.#bdmoppyears','U') is not null
- drop table #bdmoppyears;
- select
- o.[Id]
- , o.[Name]
- , o.[StageName]
- , o.[CloseDate]
- , o.[Project_Name__c]
- , o.[Amount]
- , opp.[Year]
- , ofy.[FEDYear]
- , osy.[StateYear]
- , o.[Service_Type__c]
- , o.[Type]
- , o.[Splitflag]
- , o.[ELSignedDate]
- , o.[Years_Under_Study_Federal__c]
- , o.[Years_Under_Study_State__c]
- , o.[States__c]
- --, case
- -- when opp.[Year] < year(o.[ELSignedDate]) then 1
- -- else row_number() over(partition by o.[Id], case when opp.[Year] >= year(o.[ELSignedDate]) then 2 else 1 end order by opp.[Year]) + 1
- -- end [OppRn]
- --, case
- -- when opp.[Year] < year(o.[ELSignedDate]) -1 then 1
- -- when opp.[Year] = year(o.[ELSignedDate]) -1 and DatePart(Month, o.ELSignedDate) > COALESCE(LEFT(o.Fiscal_Year_End_2__c,CHARINDEX('/',o.Fiscal_Year_End_2__c)-1),12) then 1
- -- when opp.[Year] = year(o.[ELSignedDate]) -1 and DatePart(Month, o.ELSignedDate) <= COALESCE(LEFT(o.Fiscal_Year_End_2__c,CHARINDEX('/',o.Fiscal_Year_End_2__c)-1),12) then 2
- -- else row_number() over(partition by o.[Id]
- -- , case when opp.[Year] >= year(o.[ELSignedDate]) then 2
- -- when opp.[Year] >= year(o.[ELSignedDate]) then 3 else 1 end order by opp.[Year]) + 2
- -- end [OppRn]
- , case when o.Fiscal_Year_End_2__c is null
- THEN CASE WHEN opp.Year - CASE WHEN Type = 'Follow-Up' THEN 1 ELSE 0 END >= Year(o.ELSignedDate) Then SUBSTRING(opp.Year, 2, 3) else 1 END
- when CAST (COALESCE(LEFT(o.Fiscal_Year_End_2__c,CHARINDEX('/',o.Fiscal_Year_End_2__c)-1),12) as INT) = 12
- THEN
- CASE WHEN opp.Year - CASE WHEN Type = 'Follow-Up' THEN 1 ELSE 0 END > Year(DateAdd(M, -CAST(COALESCE(LEFT(o.Fiscal_Year_End_2__c,CHARINDEX('/',o.Fiscal_Year_End_2__c)-1),12 ) AS INT),o.ELSignedDate) ) Then SUBSTRING(opp.Year, 2, 3)
- else 1 END
- ELSE case when opp.Year - CASE WHEN Type = 'Follow-Up' THEN 1 ELSE 0 END >= Year(DateAdd(M, -CAST(LEFT(o.Fiscal_Year_End_2__c,CHARINDEX('/',o.Fiscal_Year_End_2__c)-1) AS INT),o.ELSignedDate) ) Then SUBSTRING(opp.Year, 2, 3)
- --when opp.Year = Year(DateAdd(M, -COALESCE(LEFT(o.Fiscal_Year_End_2__c,CHARINDEX('/',o.Fiscal_Year_End_2__c)-1),12),o.ELSignedDate) ) Then SUBSTRING(opp.Year, 2, 3)
- else 1 END END [OppRn]
- , row_number() over(partition by o.[Id] order by opp.[Year]) [OppYearRn]
- into #bdmoppyears
- from
- #bdmoppstg o
- left join
- #bdmoppyearsstg opp on opp.[Id] = o.[Id]
- left join
- #bdmoppFEDYears ofy on ofy.[Id] = o.[Id] and ofy.[FEDYear] = opp.[Year]
- left join
- #bdmoppStateYears osy on osy.[Id] = o.[Id] and osy.[StateYear] = opp.[Year]
- ;
- --Finalizing data
- if object_id('tempdb.dbo.#bdmoppfinalstg','U') is not null
- drop table #bdmoppfinalstg;
- select
- o.[Id]
- , o.[Name]
- , o.[StageName]
- , o.[CloseDate]
- , o.[Project_Name__c]
- , o.[Amount]
- , o.[Service_Type__c]
- , o.[Type]
- , o.[Splitflag]
- , o.[ELSignedDate]
- , o.[Years_Under_Study_Federal__c]
- , o.[Years_Under_Study_State__c]
- , o.[States__c]
- , o.[OppRn]
- , substring
- (
- (
- select ';' + ob.[FEDYear] [text()]
- from #bdmoppyears ob
- where ob.[Id] = o.[Id] and ob.[OppRn] = o.[OppRn]
- order by ob.[Id], ob.[OppRn]
- for xml path ('')
- ), 2, 1000
- ) [FEDYear]
- , substring
- (
- (
- select ';' + ob.[StateYear] [text()]
- from #bdmoppyears ob
- where ob.[Id] = o.[Id] and ob.[OppRn] = o.[OppRn]
- order by ob.[Id], ob.[OppRn]
- for xml path ('')
- ), 2, 1000
- ) [StateYear]
- into #bdmoppfinalstg
- from
- #bdmoppyears o
- group by
- o.[Id]
- , o.[Name]
- , o.[StageName]
- , o.[CloseDate]
- , o.[Project_Name__c]
- , o.[Amount]
- , o.[Service_Type__c]
- , o.[Type]
- , o.[Splitflag]
- , o.[ELSignedDate]
- , o.[Years_Under_Study_Federal__c]
- , o.[Years_Under_Study_State__c]
- , o.[States__c]
- , o.[OppRn]
- --Finalize Opportunity data
- if object_id('tempdb.dbo.#bdmoppfinal','U') is not null
- drop table #bdmoppfinal;
- select
- [Id]
- , [Name]
- , [StageName]
- , [CloseDate]
- , [Project_Name__c]
- , [Amount]
- , [Service_Type__c]
- , [Type]
- , [Splitflag]
- , [ELSignedDate]
- , [Years_Under_Study_Federal__c]
- , [Years_Under_Study_State__c]
- , [States__c]
- , [OppRn]
- , NULLIF(coalesce(case when [FEDYear] = '' AND COUNT(Id)OVER(Partition By Id) = 1 then null else [FEDYear] end, [Years_Under_Study_Federal__c]),'') [FEDYear]
- , NULLIF(coalesce(case when [StateYear] = '' AND COUNT(Id)OVER(Partition By Id) = 1 then null else [StateYear] end, [Years_Under_Study_State__c]),'') [StateYear]
- into #bdmoppfinal
- from
- #bdmoppfinalstg
- if object_id('tempdb.dbo.#bdmopp','U') is not null
- drop table #bdmopp;
- select
- [Id]
- , case
- when Rubix.dbo.ProjectName([FEDYear],[StateYear],[States__c]) = '' then replace([Service_Type__c],'Employee Retention Credit','ERC')
- when Service_Type__c = '179D' then concat(Rubix.dbo.ProjectName([FEDYear],null,null),' ', [Service_Type__c])
- else concat(Rubix.dbo.ProjectName([FEDYear],[StateYear],[States__c]),' ', replace([Service_Type__c],'Employee Retention Credit','ERC'))
- end [RevProjectName]
- --, Service_Type__c as [RevProjectName]
- , case
- when opp.[Splitflag] = 0 then opp.[Amount]
- when opp.[OppRn] = 1 then opp.[Amount]
- else 0
- end [RevAmount]
- , opp.FEDYear
- , opp.StateYear
- into #bdmopp
- from
- #bdmoppfinal opp
- ;
- --Getting Non CPA Referral Source Info
- if object_id('tempdb.dbo.#bdmoncrsstg','U') is not null
- drop table #bdmoncrsstg;
- select
- [Opportunity__c]
- , [Referral_Information__c]
- , age1.Name [OpRefSourceEmployee1]
- , age2.Name [OpRefSourceEmployee2]
- , age3.Name [OpRefSourceEmployee3]
- into #bdmoncrsstg
- from
- [SalesforceClone].[dbo].[Opportunity_Non_CPA_Referral_Source__c] oncrs
- LEFT JOIN [SalesforceClone].[dbo].[AG_Employee__c] age1 on age1.id = oncrs.ag_Employee_1__c
- LEFT JOIN [SalesforceClone].[dbo].[AG_Employee__c] age2 on age2.id = oncrs.ag_Employee_2__c
- LEFT JOIN [SalesforceClone].[dbo].[AG_Employee__c] age3 on age3.id = oncrs.ag_Employee_3__c
- where
- oncrs.IsDeleted = 0
- group by
- [Opportunity__c]
- , [Referral_Information__c]
- , age1.Name
- , age2.Name
- , age3.Name
- ;
- if object_id('tempdb.dbo.#bdmoncrs','U') is not null
- drop table #bdmoncrs;
- select
- [Opportunity__c]
- , trim(replace(substring
- (
- (
- select
- '; ' + oncrsb.[OpRefSourceEmployee1] [text()]
- from
- #bdmoncrsstg oncrsb
- where
- oncrsb.[Opportunity__c] = oncrs.[Opportunity__c] and oncrsb.OpRefSourceEmployee1 IS NOT NULL
- order by
- oncrsb.[Opportunity__c]
- for xml path ('')
- ), 2, 1000
- ),'&','&')) [OpRefSourceEmployee1]
- ,trim(replace(substring
- (
- (
- select
- '; ' + oncrsb.[OpRefSourceEmployee2] [text()]
- from
- #bdmoncrsstg oncrsb
- where
- oncrsb.[Opportunity__c] = oncrs.[Opportunity__c] and oncrsb.OpRefSourceEmployee2 IS NOT NULL
- order by
- oncrsb.[Opportunity__c]
- for xml path ('')
- ), 2, 1000
- ),'&','&')) [OpRefSourceEmployee2]
- ,trim(replace(substring
- (
- (
- select
- '; ' + oncrsb.[OpRefSourceEmployee3] [text()]
- from
- #bdmoncrsstg oncrsb
- where
- oncrsb.[Opportunity__c] = oncrs.[Opportunity__c] and oncrsb.OpRefSourceEmployee3 IS NOT NULL
- order by
- oncrsb.[Opportunity__c]
- for xml path ('')
- ), 2, 1000
- ),'&','&')) [OpRefSourceEmployee3]
- , trim(replace(substring
- (
- (
- select
- '; ' + oncrsb.[Referral_Information__c] [text()]
- from
- #bdmoncrsstg oncrsb
- where
- oncrsb.[Opportunity__c] = oncrs.[Opportunity__c]
- order by
- oncrsb.[Opportunity__c]
- for xml path ('')
- ), 2, 1000
- ),'&','&')) [Referral_Information__c]
- into #bdmoncrs
- from
- #bdmoncrsstg oncrs
- group by
- [Opportunity__c]
- ;
- if object_id('tempdb.dbo.#OldbdMasterOpportunity','U') is not null
- drop table #OldbdMasterOpportunity;
- select distinct OpportunityID_CCC_3E into #OldbdMasterOpportunity from [FP&A].dbo.BD_Master
- --Getting Opportunity data
- if object_id('tempdb..#bdmoppResults') is not null
- drop table #bdmoppResults;
- select Date, Region, Company, WIP, Fee, PBD, PBdPerc, SBD, SBDPerc, CPA, CPAID, CPAPerc, Description, SOE,[OtherRefSource]
- , [CPAAlliance], [State], [CPAContact], [Industry], [SIC], [YearEnd], [FeeType_Remove], [FeeCap],
- [FUSoe]
- , [SF_Case_Intake_ID]
- , [SF_Account_ID]
- , [SF_Parent_Account_ID]
- , [SF_Opportunity_ID]
- , [RunDt]
- , [CPA_Referral_Firm_Account_Ref__c]
- , [Amending_CPA_s_Firm_Account_Ref__c]
- , [NAICS_Code__c]
- , [IndustryIntake]
- , [Percentage]
- , [ADDeg]
- , [System_Integrators_Group__C]
- , [SF_CHILD_NAME]
- , [SF_CHILD_ID]
- , [Immediate_Parent__c] --PAR.Name [Immediate_Parent__c]
- , [Immediate_Parent_ID__c] --PAR.ID [Immediate_Parent_ID__c]
- , [Parent_Account_Alliance__c]
- , [Associations]
- , [Type]
- , [Evergreen]
- , [Relationship_Director_1]
- , [Relationship_Director_2]
- , [BD_Assist] [BDAssist]
- , [BD_Assist_Other]
- , [Number_of_Employees]
- , [Final_Intake_Created_By__c]
- , [Fee_Cap_Percentage_Type]
- , [SL]
- , [PBDAllocationPerc]
- , [SBDAllocationPerc]
- , [SOE1AllocationPerc]
- , [SOE2AllocationPerc]
- , [Contingent_Converted]
- , FEDYear
- , StateYear
- , [ServiceType]
- , [HistoricalAlliance]
- , [CPANewExistingNewAgain]
- , [CPAOrignalSignedDate]
- , [AnnualRevenue]
- , [OpRefSourceRavingFan]
- , [OpRefSourceCPA]
- , [OpRefSourceConference]
- , [OpRefSourceNonConference]
- , [OpRefSourceDirect]
- , [OpRefSourceEA]
- , [OpRefSourceWebinar]
- , [OpRefSourceWebsite]
- , [OpRefSourceReferralSource]
- , [OpRefSourceEmployee1]
- , [OpRefSourceEmployee2]
- , [OpRefSourceEmployee3]
- , [EgmtLetterSignedDate]
- , CloseDate
- , [RecordForUpdate]
- , CASE WHEN b.OpportunityID_CCC_3E IS NULL THEN 1 ELSE 0 END [RecordNotInOldBDMaster]
- into #bdmoppResults from (
- select distinct
- coalesce(case
- when charindex('@',o.[Final_Intake_Created_By__c]) = 0 then null
- when ow.[LocaleSidKey] = 'en_GB' then
- cast(convert(datetime,RIGHT(o.[Final_Intake_Created_By__c],charindex('@',reverse(o.[Final_Intake_Created_By__c]))-2),103) as date)
- else cast(RIGHT(o.[Final_Intake_Created_By__c],charindex('@',reverse(o.[Final_Intake_Created_By__c]))-2) as date)
- end,o.[Final_Intake_Created_Date__c]) [Date]
- , o.[State_by_Region_Mapping__c] [Region]
- , a.[Name] [Company]
- , coalesce(opp.[RevAmount], o.[Amount]) [WIP]
- , o.[Fee_Type__c] [Fee]
- , ow.[Name] [PBD]
- , null [PBDPerc]
- , coalesce(SBD.[Name],'N/A') [SBD]
- , null [SBDPerc]
- , CASE WHEN CPAAccount.Name IS NOT NULL then CPAAccount.Name
- WHEN PAR.Name IS NOT NULL THEN PAR.NAME
- WHEN AAR.NAME IS NOT NULL THEN AAR.NAME
- WHEN CAR.Name IS NOT NULL THEN CAR.Name
- ELSE 'Direct' END [CPA]
- , CASE WHEN a.CPA_Account__c IS NOT NULL then a.CPA_Account__c
- WHEN a.ParentID iS NOT NULL THEN a.ParentId
- WHEN o.Amending_CPA_Firm_ID__c IS NOT NULL THEN o.Amending_CPA_Firm_ID__c
- WHEN CAR.ID IS NOT NULL THEN CAR.ID
- ELSE 'Direct' END [CPAID]
- , cast(case when coalesce(case when cir.[Referral_Information__c] = '' then 'Direct' else cir.[Referral_Information__c] end, 'Direct') = 'Direct' then 0 end as decimal(18,2)) [CPAPerc]
- , concat(coalesce(opp.[RevProjectName], replace(o.[Project_Name__c],' Employee Retention Credit','ERC'))
- , case when o.[Service_Type__c] != 'Employee Retention Credit' and o.[Type] = 'Follow-Up' then ' FU' end
- , case when o.[Service_Type__c] != 'Employee Retention Credit' and o.[Type] = 'Continuation' then ' Add-On' end
- , case when o.[Service_Type__c] != 'Employee Retention Credit' and o.Evergreen_2__c = 'Yes' then ' EG' end
- ) [Description]
- , soe.[Name] [SOE]
- , coalesce(case when cir.[Referral_Information__c] = '' then 'Direct' else cir.[Referral_Information__c] end, 'Direct') [OtherRefSource]
- , o.[Amending_CPA_Alliance__c] [CPAAlliance]
- , case when len(a.[BillingState]) = 2 then a.[BillingState] else null end [State]
- , CPAContact.[Name] [CPAContact]
- , n.Name [Industry]--n.Major_Industry__c [Industry]
- , n.NAICS_Code__c [SIC] --a.[SIC]
- , o.[Fiscal_Year_End_2__c] [YearEnd]
- , null [FeeType_Remove]
- , try_convert(decimal(5,4),
- (CASE
- WHEN o.[Fee_Cap_Percentage__c] is not null then o.[Fee_Cap_Percentage__c]
- WHEN o.[Fee_Cap_Percentage_Gross__c] is not null then o.[Fee_Cap_Percentage_Gross__c]
- ELSE o.[Fee_Cap_Percentage_Input__c]
- END) / 100) [FeeCap]
- , o.[Follow_Up_Source_of_Engagement_FU_STUDY__c] [FUSoe]
- , o.[Id] [SF_Case_Intake_ID]
- , a.[Id] [SF_Account_ID]
- , a.ParentId [SF_Parent_Account_ID]
- , o.[Id] [SF_Opportunity_ID]
- , getdate() [RunDt]
- , CAR.[Account_Ref__c] [CPA_Referral_Firm_Account_Ref__c]
- , AAR.[Account_Ref__c] [Amending_CPA_s_Firm_Account_Ref__c]
- , N.[NAICS_Code__c]
- , N.Major_Industry__c [IndustryIntake]
- , (CASE
- WHEN o.[Fee_Cap_Percentage__c] is not null then o.[Fee_Cap_Percentage__c]
- WHEN o.[Fee_Cap_Percentage_Gross__c] is not null then o.[Fee_Cap_Percentage_Gross__c]
- ELSE o.[Fee_Cap_Percentage_Input__c]
- END) / 100 [Percentage]
- , CASE WHEN coalesce(o.Evergreen_2__c,'No') = 'No' THEN 0 ELSE 1 END [ADDeg]
- , A.[System_Integrators_Group__C]
- , CASE WHEN CPAAccount.Name IS NOT NULL then CPAAccount.Name
- WHEN PAR.Name IS NOT NULL THEN PAR.NAME
- WHEN AAR.NAME IS NOT NULL THEN AAR.NAME
- WHEN CAR.Name IS NOT NULL THEN CAR.Name
- ELSE NULL END [SF_CHILD_NAME]
- , CASE WHEN a.CPA_Account__c IS NOT NULL then a.CPA_Account__c
- WHEN a.ParentID iS NOT NULL THEN a.ParentId
- WHEN o.Amending_CPA_Firm_ID__c IS NOT NULL THEN o.Amending_CPA_Firm_ID__c
- WHEN CAR.ID IS NOT NULL THEN CAR.ID
- ELSE NULL END [SF_CHILD_ID]
- , coalesce(cpa4.[Name], cpa3.[Name], cpa2.[Name], parentAcc.[Name], 'Direct') [Immediate_Parent__c] --PAR.Name [Immediate_Parent__c]
- , coalesce(cpa4.[Id], cpa3.[Id], cpa2.[Id], parentAcc.[Id]) [Immediate_Parent_ID__c] --PAR.ID [Immediate_Parent_ID__c]
- , A.[Parent_Account_Alliance__c]
- , A.[affiliations__c] [Associations]
- , replace(replace(o.[Type],'New Business','New'),'Follow-Up','FU') [Type]
- , coalesce(o.Evergreen_2__c,'No') [Evergreen]
- , rd1.[Name] [Relationship_Director_1]
- , rd2.[Name] [Relationship_Director_2]
- , bda.[Name] [BD_Assist]
- , bdao.[Name] [BD_Assist_Other]
- , o.Number_of_Employees__c [Number_of_Employees]
- , case when charindex('@',o.[Final_Intake_Created_By__c]) > 0 then left(o.[Final_Intake_Created_By__c],charindex('@',o.[Final_Intake_Created_By__c])-2) else o.[Final_Intake_Created_By__c] end [Final_Intake_Created_By__c]
- , o.[Fee_Cap_Percentage_Type__c] [Fee_Cap_Percentage_Type]
- , replace(o.[Service_Type__c],'Employee Retention Credit','ERC') [SL]
- , oa.BD1_Allocation__c / 100 [PBDAllocationPerc]
- , oa.BD2_Allocation__c / 100 [SBDAllocationPerc]
- , oa.RD1_Allocation__c / 100 [SOE1AllocationPerc]
- , oa.RD2_Allocation__c / 100 [SOE2AllocationPerc]
- , o.[Contingent_Converted__c] [Contingent_Converted]
- , opp.FEDYear
- , opp.StateYear
- --, row_number() over(partition by o.id, opp.FEDYear, opp.StateYear order by
- -- coalesce(case
- -- when charindex('@',o.[Final_Intake_Created_By__c]) = 0 then null
- -- when ow.[LocaleSidKey] = 'en_GB' then
- -- cast(convert(datetime,RIGHT(o.[Final_Intake_Created_By__c],charindex('@',reverse(o.[Final_Intake_Created_By__c]))-2),103) as date)
- -- else cast(RIGHT(o.[Final_Intake_Created_By__c],charindex('@',reverse(o.[Final_Intake_Created_By__c]))-2) as date)
- -- end,o.[Final_Intake_Created_Date__c])) Rn
- , CASE
- WHEN o.[Service_Type__c] = '179D' THEN 130
- WHEN o.[Service_Type__c] ='DPD' THEN 140
- WHEN o.[Service_Type__c] ='HCI' THEN 170
- WHEN o.[Service_Type__c] ='IC-DISC' THEN 160
- WHEN o.[Service_Type__c] ='ITC' THEN 180
- WHEN o.[Service_Type__c] ='LDTC' THEN 180
- WHEN o.[Service_Type__c] ='MDET' THEN 180
- WHEN o.[Service_Type__c] ='QTDP' THEN 180
- WHEN o.[Service_Type__c] ='R&D' THEN 110
- WHEN o.[Service_Type__c] ='SALT' THEN 110
- WHEN o.[Service_Type__c] ='SUT' THEN 120
- WHEN o.[Service_Type__c] ='TCS' THEN 150
- WHEN o.[Service_Type__c] ='Cybersecurity' Then 175
- WHEN o.[Service_Type__c] ='SRED' THEN 230
- WHEN o.[Service_Type__c] ='SR&ED' THEN 230
- WHEN o.[Service_Type__c] ='Employee Retention Credit' THEN 225
- WHEN o.[Service_Type__c] ='ERC Services' THEN 225
- WHEN o.[Service_Type__c] ='Tax Services' THEN 200
- WHEN o.[Service_Type__c] ='Business Advisory' THEN 235
- WHEN o.[Service_Type__c] ='Business Services' THEN 240
- WHEN o.[Service_Type__c] ='External Audit' THEN 250
- WHEN o.[Service_Type__c] ='ERC' THEN 225
- ELSE NULL --150
- END [ServiceType]
- , oa.Alliance_Historical__c [HistoricalAlliance]
- , oa.CPA_Status_YTD__c [CPANewExistingNewAgain]
- , oa.CPA_First_Assigned_Date__c [CPAOrignalSignedDate]
- , a.AnnualRevenue [AnnualRevenue]
- , ref.[OpRefSourceRavingFan]
- , ref.[OpRefSourceCPA]
- , ref.[OpRefSourceConference]
- , ref.[OpRefSourceNonConference]
- , ref.[OpRefSourceDirect]
- , ref.[OpRefSourceEA]
- , ref.[OpRefSourceWebinar]
- , ref.[OpRefSourceWebsite]
- , ref.[OpRefSourceReferralSource]
- , ref.[OpRefSourceEmployee1]
- , ref.[OpRefSourceEmployee2]
- , ref.[OpRefSourceEmployee3]
- , o.Engagement_Letter_Signed_Date__c [EgmtLetterSignedDate]
- , o.CloseDate
- , CASE WHEN s.OpportunityIDCCC is NOT NULL and o.LastModifiedDate > GETDATE()-1 THEN 1
- WHEN s.OpportunityIDCCC is NOT NULL and A.Last_Modified_Date__c > GETDATE()-1 THEN 1
- WHEN s.OpportunityIDCCC is NOT NULL and CPAContact.LastModifiedDate > GETDATE()-1 THEN 1
- WHEN s.OpportunityIDCCC is NOT NULL and N.LastModifiedDate > GETDATE() -1 THEN 1
- WHEN s.OpportunityIDCCC is NOT NULL and CAR.LastModifiedDate > GETDATE() -1 THEN 1
- WHEN s.OpportunityIDCCC is NOT NULL and AAR.LastModifiedDate > GETDATE() -1 THEN 1
- WHEN s.OpportunityIDCCC is NOT NULL and PAR.LastModifiedDate > GETDATE() -1 THEN 1
- WHEN s.OpportunityIDCCC is NOT NULL and RD1.LastModifiedDate > GETDATE() -1 THEN 1
- WHEN s.OpportunityIDCCC is NOT NULL and RD2.LastModifiedDate > GETDATE() -1 THEN 1
- WHEN s.OpportunityIDCCC is NOT NULL and OA.LastModifiedDate > GETDATE() -1 THEN 1
- WHEN s.OpportunityIDCCC is NOT NULL and CPAAccount.LastModifiedDate > GETDATE() -1 THEN 1
- WHEN ref.RecordForUpdate =1 THEN 1
- ELSE 0 END [RecordForUpdate]
- --into #bdmoppResults
- from
- [SalesforceClone].[dbo].[Opportunity] o --on bd.OpportunityID_CCC_3E = o.id
- left join
- bdm.BDMasterOppReferralInfo ref on ref.Opportunity__c = o.id
- left join
- #bdmopp opp on opp.[Id] = o.[Id]
- left join
- [SalesforceClone].[dbo].[Account] A on O.[AccountId] = A.[Id]
- left join
- [SalesforceClone].[dbo].[User] ow on ow.[Id] = O.[OwnerId]
- left join
- [SalesforceClone].[dbo].[User] SBD on SBD.Id = O.[Primary_Director_Name__c]
- left join
- [SalesforceClone].[dbo].[User] soe on soe.[Id] = O.[Source_of_Engagement__c]
- left join
- [SalesforceClone].[dbo].[Contact] CPAContact on CPAContact.Id = O.Amending_CPA_Contact__c
- left join
- [SalesforceClone].[dbo].[NAICS_List__c] N on A.[NAICS_Lookup__c] = N.[Id]
- left join
- #bdmoncrs CIR on cir.[Opportunity__c] = O.[id]
- left join
- [SalesforceClone].[dbo].[Account] CAR on CAR.[Id] = O.[Referring_CPA_Firm_ID__C]
- left join
- [SalesforceClone].[dbo].[Account] AAR on AAR.[Id] = O.[Amending_CPA_Firm_ID__c]
- left join
- [SalesforceClone].[dbo].[Account] PAR on PAR.[Id] = A.[ParentId]
- left join
- [SalesforceClone].[dbo].[User] rd1 on rd1.Id = o.Primary_Relationship_Director__c
- left join
- [SalesforceClone].[dbo].[User] rd2 on rd2.Id = o.X2nd_Relationship_Director__c
- left join
- [SalesforceClone].[dbo].[AG_Employee__c] bda on bda.Id = o.BD_Assist__c
- left join
- [SalesforceClone].[dbo].[AG_Employee__c] bdao on bdao.Id = o.BD_Assist_Other_1__c
- left join
- [SalesforceClone].[dbo].[Opportunity_Analytics__c] oa on oa.Opportunity__c = o.id
- left join
- [SalesforceClone].[dbo].[Account] CPAAccount on CPAAccount.id = a.CPA_Account__c
- left join
- [SalesForceClone].dbo.Account parentAcc on parentAcc.id = COALESCE(a.CPA_Account__c,o.Amending_CPA_Firm_ID__c, [Referring_CPA_Firm_ID__C])
- left join
- SalesForceClone.dbo.Account cpa2 on cpa2.[Id] = parentAcc.[ParentId]
- left join
- SalesForceClone.dbo.Account cpa3 on cpa3.[Id] = cpa2.[ParentId]
- left join
- SalesForceClone.dbo.Account cpa4 on cpa4.id = cpa3.ParentId
- outer apply
- (select top 1 OpportunityIDCCC from BDM.BDMasterSource s where s.OpportunityIDCCC = o.id ) s
- where --o.CloseDate > '01/01/2020' and
- (([Final_Intake_Created_By__c] is not null and [Final_Intake_Created_By__c] not like '%Bhavesh Zaveri%') or Stagename like 'Closed%')
- UNION
- select distinct
- cast(C.[CreatedDate] as date) [Date]
- , C.[State_by_Region_Mapping__c] [Region]
- , C.[Account_Name__c] [Company]
- , C.[Book_to_WIP__c] [WIP]
- , C.[Fee_Type__c] [Fee]
- , U.[Name] [PBD]
- , NULL [PBDPerc]
- , U1.[Name] [SBD]
- , NULL [SBDPerc]
- , C.[Amending_CPA_s_Firm__c] [CPA]
- , NULL [CPAID]
- , NULL [CPAPerc]
- , replace(C.[Project_Name__c],'Fed','FED') [Description]
- , U2.[Name] [SOE]
- , ciro.[Referral_Information__c] [OtherRefSource]
- , C.[Alliance__c] [CPAAlliance]
- , case
- when len(C.[Client_Billing_State__c]) = 2
- then C.[Client_Billing_state__c]
- else NULL
- end [State]
- , Con.[Name] [CPAContact]
- , C.[Client_s_Industry__c] [Industry]
- , C.[SIC_Code__c] [SIC]
- , C.[Year_End__c] [YearEnd]
- , NULL [FeeType_Remove]
- , try_convert(decimal(5,4), C.[Fee_CAP__c]) [FeeCap] -- C.[Fee_CAP__c] [FeeCap]
- , C.[Follow_Up_Source_of_Engagement_FU_STUDY__c] [FUSoe]
- , C.[Id] [SF_Case_Intake_ID]
- , C.[Account_ID__c] [SF_Account_ID]
- , NULL AS [SF_Parent_Account_ID]
- , C.Opportunity_ID__c [SF_Opportunity_ID]
- , getdate() [RunDt]
- , C.[CPA_Referral_Firm_Account_Ref__c]
- , C.[Amending_CPA_s_Firm_Account_Ref__c]
- , C.[NAICS_Code__c]
- , Null as IndustryIntake
- , 0 as Percencetage
- , 0 [ADDeg]
- , A.[System_Integrators_Group__C]
- , NULL [SF_CHILD_NAME]
- , NULL [SF_CHILD_ID]
- , PAR.[Name] [Immediate_Parent__c]
- , PAR.ID [Immediate_Parent_ID__c]
- , A.[Parent_Account_Alliance__c]
- , A.[affiliations__c] [Associations]
- , null [Type]
- , null [Evergreen]
- , null [Relationship_Director_1]
- , null [Relationship_Director_2]
- , null [BD_Assist]
- , null [BD_Assist_Other]
- , null [Number_of_Employees]
- , null [Final_Intake_Created_By__c]
- , null [Fee_Cap_Percentage_Type]
- , null [SL]
- , null [PBDAllocationPerc]
- , null [SBDAllocationPerc]
- , null [SOE1AllocationPerc]
- , null [SOE2AllocationPerc]
- , null [Contingent_Converted]
- , null as [FedYear]
- , null as [StateYear]
- , null as [ServiceType]
- , NULL as [HistoricalAlliance]
- , NULL as [CPANewExistingNewAgain]
- , NULL as [CPAOrignalSignedDate]
- , Null as [AnnualRevenue]
- , NUll [OpRefSourceRavingFan]
- , NUll [OpRefSourceCPA]
- , NUll [OpRefSourceConference]
- ,NUll [OpRefSourceNonConference]
- ,NUll [OpRefSourceDirect]
- ,NUll [OpRefSourceEA]
- , NUll [OpRefSourceWebinar]
- , NUll [OpRefSourceWebsite]
- , NUll [OpRefSourceReferralSource]
- ,NUll [OpRefSourceEmployee1]
- ,NUll [OpRefSourceEmployee2]
- ,NUll [OpRefSourceEmployee3]
- , NULL [EgmtLetterSignedDate]
- , NULL CloseDate
- , 0 [RecordForUpdate]
- from
- [SalesforceClone].[dbo].[Case] c
- left outer join
- [SalesforceClone].[dbo].[User] u on c.[Primary_BD_Director__c] = u.[Id]
- left outer join
- [SalesforceClone].[dbo].[Case_Intake_Referral_Source__c] cir on cir.[Case_Intake_Referral_Source__c] = c.[Id]
- left outer join
- [SalesforceClone].[dbo].[User] U1 on c.[x2nd_BD_Director_If_any__c] = U1.[Id]
- left outer join
- [SalesforceClone].[dbo].[User] U2 on c.[Source_of_Engagement__c] = U2.[Id]
- left outer join
- [SalesforceClone].[dbo].[Contact] con on C.[CPA_Amending_Prepping_Returns__c] = con.[Id]
- left join
- [SalesforceClone].[dbo].[Account] a on a.[Id] = c.[AccountId]
- left join
- [SalesforceClone].[dbo].[Account] par on par.Id = a.ParentId
- left outer join
- [SalesforceClone].[dbo].[Opportunity_Non_CPA_Referral_Source__c] ciro on ciro.[Opportunity__c] = c.[Opportunity_ID__c]
- where
- c.[RecordType_Name__c] in ('New Client Intake R&D, QETC and DPD','New Client Intake-179D')
- and c.[CreatedDate] >= '2015-05-20'
- and c.Opportunity_ID__c not in (select distinct id from SalesForceClone..Opportunity where ([Final_Intake_Created_By__c] is not null and [Final_Intake_Created_By__c] not like '%Bhavesh Zaveri%') or Stagename like 'Closed%')
- --and o.[CloseDate]>= '01/01/2020'
- )a
- LEFT JOin #OldbdMasterOpportunity b on b.OpportunityID_CCC_3E = a.SF_Opportunity_ID
- --Logging in Log table
- exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'Data retrived from Salesforce for Opportunity'
- if object_id('tempdb..#bdmResults') is not null
- drop table #bdmResults;
- --Pulling data from 3E based on Opportunity Id, Service Line and Year of Study
- select distinct
- m.MattIndex, m.Number, m.AltNumber, m.DisplayName
- , b.Description [Description_SF]
- , m.Description [Description_3E]
- , COALESCE(b.Description, m.Description) [Description]
- , b.Company [Client_SF]
- , m.Client [Client_3E]
- , COALESCE(b.Company,m.Client) [Client]
- , m.ClientId
- , CASE WHEN m.MattStatus IN ('KO','CANCELDUP','Cancel_NOEL','TERM','TERM_EG','TERM_ERCLIVE') THEN 'Suspended'
- WHEN m.MattStatus IN ('COMP_ERCLIVE','COMP','CLOSING','CLOSING_ERCLIVE') THEN 'Completed'
- WHEN m.MattStatus IN ('HOLDAR','HOLDUTL','HOLDREP','HOLDFYR','LINKED','PEND','HOLDAUD','PENDEG','INPROC'
- ,'HOLDRESELL','HOLDFYE','HOLDCLI','EGREADYTOASSIGN','NO_EL','HOLDBD','HOLDFF','HOLDAYE','PENDCOMP','HOLDARREP'
- ,'HOLDAMR', 'HOLDARREP', 'HOLDERC', 'HOLDIRS', 'HOLDREF', 'HOLDUR')
- THEN 'In-Process'
- ELSE m.MattStatus END [MattStatus]
- , m.Currency
- , m.MattCategory
- , COALESCE(m.IsEvergreenCCC,0) IsEvergreenCCC
- , b.Type [EngTypeCCC_SF]
- , m.EngTypeCCC [EngTypeCCC_3E]
- , COALESCE(CASE WHEN m.IsCloned_CCC = 1 THEN m.EngTypeCCC WHEN b.Type = 'Continuation' THEN 'New' ELSE ISNULL(b.Type,NULL) END, m.EngTypeCCC) [EngTypeCCC]
- , m.EngStatusCCC
- , b.[EgmtLetterSignedDate] [EngSignedDateCCC_SF]
- , m.EngSignedDateCCC [EngSignedDateCCC_3E]
- , COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC) [EngSignedDateCCC]
- , b.SL [ServiceLine_SF]
- , m.ServiceLine [ServiceLine_3E]
- , COALESCE(b.SL,m.ServiceLine) ServiceLine
- , b.State [State_SF]
- , m.State [State_3E]
- , COALESCE(b.State, m.State) [State]
- , b.WIP [OriginalWIP_SF]
- , m.OriginalWIP [OriginalWIP_3E]
- , CASE WHEN (COALESCE(m.[1TimeAdj],0) = 1 OR m.IsCloned_CCC = 1 OR (COALESCE(CASE WHEN m.IsCloned_CCC = 1 THEN m.EngTypeCCC WHEN b.Type = 'Continuation' THEN 'New' ELSE ISNULL(b.Type,NULL) END, m.EngTypeCCC) = 'FU' and NULLIF(m.MinYear,9999) > YEAR(COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC,b.Date)))) and COALESCE(b.WIP,0) = 0
- THEN m.OriginalWIP
- WHEN COUNT(m.Mattindex)OVER(Partition BY m.[1TimeAdj],b.SF_Opportunity_ID)>1 THEN m.OriginalWIP
- ELSE COALESCE(NULLIF(b.WIP,0), m.OriginalWIP) END [OriginalWIP]
- , /*Case when m.[MattStatus] in ('COMP','CLOSING','CLOSING_ERCLIVE') then bc.BilledSplit else*/ m.AdjustedWIP /*end*/ AdjustedWIP
- , b.[IndustryIntake] [MajorIndustry_SF]
- , m.MajorIndustry [MajorIndustry_3E]
- , COALESCE(b.[IndustryIntake], m.MajorIndustry) MajorIndustry
- , COALESCE(m.MinYear,YEAR(m.EngSignedDateCCC),YEAR(b.Date), '9999') [MinTaxYear]
- , m.MaxYear [MaxTaxYear]
- , m.Code
- , StudyYears
- , m.UpdatedWIP
- , CASE WHEN m.OriginalWIP <> m.UpdatedWIP THEN UpdatedWIP ELSE OriginalWIP END [ComboWIP]
- , COALESCE(bc.BilledSplit,0) [Billed]
- , ISNULL(bc.CollectedSplit,0) [Collected]
- , ISNULL(bc.BilledSplit - bc.CollectedSplit,0) [AccountReceivable]
- , COALESCE(m.PBD, b.PBD) PBD
- , CASE WHEN ISNULL(COALESCE(m.SBD, b.SBD), 'Unknown') = 'Unknown' THEN 'N/A' ELSE COALESCE(m.SBD, b.SBD) END SBD
- , COALESCE(m.PRD, b.Relationship_Director_1) PRD
- , CASE WHEN ISNULL(COALESCE(m.SRD, b.Relationship_Director_2), 'Unknown') = 'Unknown' THEN 'N/A'
- ELSE COALESCE(m.SRD, b.Relationship_Director_2) END SRD
- , NULL as [PM] --m.PM
- , m.Credit [EstimatedCredits]
- , m.WorkedWIP
- , m.PendingInvoices
- , m.TotalWIP
- , m.RemainingWIP [RemainingWIPbasedonhoursworked]
- , m.UnbilledWIP
- , m.UnbilledWorkedWIP
- , m.Balance
- , COALESCE(m.BD1Allocation,b.PBDAllocationPerc) [PBDAllocationPercent]
- , COALESCE(m.BD2Allocation,b.SBDAllocationPerc) [SBDAllocationPercent]
- , COALESCE(m.RD1Allocation,b.SOE1AllocationPerc) [PRDAllocationPercent]
- , COALESCE(m.RD2Allocation,b.SOE2AllocationPerc) [SRDAllocationPercent]
- , case when COALESCE(CASE WHEN b.Type = 'Continuation' THEN 'New' ELSE ISNULL(b.Type,NULL) END, m.EngTypeCCC) in ('New','New Business') then pbd.NewStudyCommission/100 else pbd.FuStudyCommission/100 end [PBDComPercent]
- , case when COALESCE(CASE WHEN b.Type = 'Continuation' THEN 'New' ELSE ISNULL(b.Type,NULL) END, m.EngTypeCCC) in ('New','New Business') then prd.NewStudyCommission/100 else prd.FuStudyCommission/100 end [PRDComPercent]
- , case when COALESCE(CASE WHEN b.Type = 'Continuation' THEN 'New' ELSE ISNULL(b.Type,NULL) END, m.EngTypeCCC) in ('New','New Business') then sbd.NewStudyCommission/100 else sbd.FuStudyCommission/100 end [SBDComPercent]
- , case when COALESCE(CASE WHEN b.Type = 'Continuation' THEN 'New' ELSE ISNULL(b.Type,NULL) END, m.EngTypeCCC) in ('New','New Business') then srd.NewStudyCommission/100 else srd.FuStudyCommission/100 end [SRDComPercent]
- , m.BD1AdjWIPAlloc [PBDWIPAllocation]
- , m.BD2AdjWIPAlloc [SBDWIPAllocation]
- , m.RD1AdjWIPAlloc [SOE1WIPAllocation]
- , m.RD2AdjWIPAlloc [SOE2WIPAllocation]
- , m.BD1FeesBilled [PBDBilledAllocation]
- , m.BD2FeesBilled [SBDBilledAllocation]
- , m.RD1FeesBilled [SOE1BilledAllocation]
- , m.RD2FeesBilled [SOE2BilledAllocation]
- , m.BD1FeesCollected [PBDCollections]
- , m.BD2FeesCollected [SBDCollections]
- , m.RD1FeesCollected [SOE1Collections]
- , m.RD2FeesCollected [SOE2Collections]
- , COALESCE(m.[1TimeAdj],0) [OneTimeAdj]
- , b.SF_Opportunity_ID [OpportunityIDCCC]
- --, b.PBD, b.SBD, b.SOE [PRD], b.Relationship_Director_2 [SRD],
- --ISNULL(b.[PBDAllocationPerc],0) [PBDPercent], ISNULL(b.SBDAllocationPerc,0) [SBDPercent]
- --, ISNULL(b.SOE1AllocationPerc,0) [PRDPercent], ISNULL(b.SOE2AllocationPerc,0) [SRDPercent],
- ,b.CPA, b.CPAPerc [CPAPercent], b.OtherRefSource [ReferralSource], b.CPAAlliance [CPAAlliance],
- 0 as [Manufacturing], 0 as [Architecture], 0 as [Construction] , 0 as [Engineering], 0 as [SystemIntegrator],
- b.[SF_Account_ID] as [SFAccountId]
- , b.[Immediate_Parent__c] [SFParentAccount] --b.SF_Parent_Account_ID [SFParentAccount]
- , b.SF_CHILD_ID [SFChildId]
- , b.SF_CHILD_NAME [SFChildAccount],
- b.CPAID as CPAID, NULL as [EAReferral], NULL as [EATeam], NULL as [EAIndustry], NULL as [EAParentName], NULL as [EAYearAttended], NULL as [EAEventDate],
- NULL as [WebinarIPA], NULL as [EASpeaker], ISNULL(b.FeeCap,0) FeeCap, b.Fee [FeeType],b.Number_of_Employees [NumberOfEmployees], ISNULL(b.WIP,0) WIP, b.Industry , ISNULL(b.SIC,0) SIC
- , b.HistoricalAlliance
- , b.[REGION]
- , b.CPAContact
- , NULL as CPANewExisting --b.CPANewExistingNewAgain
- , NULL as [CPAOrignalSignedDate] --b.CPAOrignalSignedDate [CPAOrignalSignedDate]
- ,-1 as RefNo
- , b.[AnnualRevenue]
- , b.[OpRefSourceRavingFan]
- , b.[OpRefSourceCPA]
- , b.[OpRefSourceConference]
- , b.[OpRefSourceNonConference]
- , b.[OpRefSourceDirect]
- , b.[OpRefSourceEA]
- , b.[OpRefSourceWebsite]
- , b.[OpRefSourceWebinar]
- , b.[OpRefSourceReferralSource]
- , b.[OpRefSourceEmployee1]
- , b.[OpRefSourceEmployee2]
- , b.[OpRefSourceEmployee3]
- , b.[IndustryIntake] [IndustryIntake]
- , b.Percentage [Percentage]
- , b.ADDeg [AddEG]
- , b.Associations [Associations]
- , NULL As [ReferralCategory] --b.OtherRefSource [ReferralCategory]
- , b.YearEnd
- ,b.Fee_Cap_Percentage_Type [FeeCapPercentageType]
- , CASE WHEN DATEDIFF(day, b.CloseDate, GETDATE() ) <= 365 and COALESCE(b.CPA, 'Direct') <> 'Direct' THEN 'New'
- WHEN DATEDIFF(day, b.CloseDate, GETDATE()) >= 365
- and DATEDIFF(day, b.CloseDate, GETDATE()) <= 1460 and COALESCE(b.CPA, 'Direct') <> 'Direct'
- THEN 'Existing'
- WHEN DATEDIFF(day, b.CloseDate, GETDATE()) > 1460 and COALESCE(b.CPA, 'Direct') <> 'Direct'
- THEN 'New'
- ELSE 'Direct' END [CPANewExistingNewAgain]
- , CASE WHEN (m.[1TimeAdj] = 1 OR m.IsCloned_CCC = 1 OR (COALESCE(CASE WHEN m.IsCloned_CCC = 1 THEN m.EngTypeCCC WHEN b.Type = 'Continuation' THEN 'New' ELSE ISNULL(b.Type,NULL) END, m.EngTypeCCC) = 'FU' and NULLIF(m.MinYear,9999) > YEAR(COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC,b.Date)))) AND m.Code in (110,120,130)
- THEN TRY_CAST(NULLIF(CONCAT('01/01/',
- COALESCE(CASE WHEN m.IsCloned_CCC = 1 AND YEAR(m2.OpenDate) >= YEar(m.EngSignedDateCCC) AND m.MinYear is null THEN YEAR(DATEADD(M,-6,m2.OpenDate))+1 END
- , NULLIF(m.MinYear,9999)+1
- , YEAR(COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC,b.Date))+1)),'01/01/') as datetime)
- ELSE CAST(COALESCE(b.[EgmtLetterSignedDate], m.EngSignedDateCCC,b.Date) as varchar(50)) END [OriginalDate]--[CloseDate]
- , COALESCE(b.Date, m.EngSignedDateCCC) [CloseDate]--[OriginalDate]
- , CASE WHEN COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC) IS NOT NULL THEN YEAR(COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC)) ELSE 0 END [Year]
- , CASE WHEN COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC) IS NOT NULL THEN DATEPART(Quarter, COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC)) ELSE 0 END [Quarter]
- , CASE WHEN COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC) IS NOT NULL THEN DATEPART(Month, COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC)) ELSE 0 END [Month]
- , CASE WHEN COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC) IS NOT NULL THEN DATEPART(Week, COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC)) ELSE 0 END [Week]
- , CASE WHEN b.Type = 'Continuation' THEN 1 ELSE 0 END [FO]
- , b.BDAssist
- , b.RecordNotInOldBDMaster
- , CASE WHEN b.RecordForUpdate =1 OR m.RecordForUpdate = 1 OR COALESCE(bc.BilledSplit,bc.CollectedSplit) is not null THEN 1 ELSE 0 END [RecordForUpdate]
- ,m.IsCloned_CCC
- into #bdmResults
- from #bdmoppResults b
- FULL OUTER JOIN Bdm.BDMasterMatterDataFrom3E m
- on m.[OpportunityID_CCC] = b.SF_Opportunity_ID COLLATE SQL_Latin1_General_CP1_CI_AS
- and m.Code = ISNULL(b.ServiceType , m.code)
- and ((CHARINDEX(CAST(m.MinYear AS varchar), b.fedyear) >0 OR CHARINDEX(CAST(m.MinYear AS varchar), b.StateYear)>0)
- OR (b.FEDYear is null and b.StateYear is null)
- )
- LEFT JOIN BDM.BDMasterMatterBilledCollected bc on bc.Number = m.Number and bc.MinYear = m.MinYear
- LEFT JOIN BDM.BDMasterCommissionPerc pbd on pbd.Employee = COALESCE(m.PBD, b.PBD) and pbd.[Role] = 'PBD'
- LEFT JOIN BDM.BDMasterCommissionPerc prd on prd.Employee = COALESCE(m.PRD, b.Relationship_Director_1) and prd.[Role] = 'PRD'
- LEFT JOIN BDM.BDMasterCommissionPerc sbd on sbd.Employee = COALESCE(m.SBD, b.SBD) and sbd.[Role] = 'SBD'
- LEFT JOIN BDM.BDMasterCommissionPerc srd on srd.Employee = COALESCE(m.SRD, b.Relationship_Director_2) and srd.[Role] = 'SRD'
- LEFT JOIN TE_3E_PROD_Clone..Matter m2 on m2.mattindex = m.Mattindex
- where NOT COALESCE(m.ClientId, -1) IN (17296,17300,23683,27697,25188,29888/*,10478,17630 these aren't actually test clients...*/) --Test CLient in Salesforce
- --and m.Number IN ('012825.0006')
- exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'Data retrived from 3E based on Opportunity'
- --Final data ready for Insert/Update in Source Table. Checking if it's a new data or existing data based on Number or Opportunity ID
- if object_id('tempdb..#bdmFinalResults') is not null
- drop table #bdmFinalResults;
- select b.* , CASE WHEN COALESCE(s.Number, s.[OpportunityIDCCC]) IS NULL THEN 'I' ELSE NULL END [RecordActionFlag]
- into #bdmFinalResults
- from
- #bdmResults b
- LEFT JOIN bdm.BDMasterSource s
- on COALESCE(b.Number, b.[OpportunityIDCCC])= COALESCE(s.Number, s.OpportunityIdCCC) --COLLATE SQL_Latin1_General_CP1_CI_AS--and b.ServiceLine = s.ServiceLine and b.OpportunityID_CCC = s.OpportunityID_CCC
- and b.MinTaxYear = s.MinTaxYear
- --Insert data in BDMasterSource table based on RecordActionFlag
- Declare @InsertResultCount varchar(100)
- Set @InsertResultCount = (select try_convert(varchar(10),count(*)) + ' to be inserted' from #bdmFinalResults where RecordActionFlag = 'I')
- exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = @InsertResultCount
- --Insert Data in Source Table
- INSERT INTO [bdm].[BDMasterSource]
- ([MattIndex]
- ,[Number]
- ,[AltNumber]
- ,[DisplayName]
- ,[Description]
- ,[ClientID]
- ,[Client]
- ,[MattStatus]
- ,[CloseDate]
- ,[Currency]
- ,[MattCategory]
- ,[IsEvergreenCCC]
- ,[EngTypeCCC]
- ,[EngStatusCCC]
- ,[EngSignedDateCCC]
- ,[OpportunityIDCCC]
- ,[ServiceLine]
- ,[State]
- ,[OriginalWIP]
- ,[AdjustedWIP]
- ,[MajorIndustry]
- ,[PBD]
- ,[SBD]
- ,[PRD]
- ,[SRD]
- ,[PBDAllocationPercent]
- ,[SBDAllocationPercent]
- ,[PRDAllocationPercent]
- ,[SRDAllocationPercent]
- ,[CPA]
- ,[CPAPercent]
- ,[ReferralSource]
- ,[CPAAlliance]
- ,[Manufacturing]
- ,[Architecture]
- ,[Construction]
- ,[Engineering]
- ,[SystemIntegrator]
- ,[SFAccountID]
- ,[SFParentAccount]
- ,[SFChildID]
- ,[SFChildAccount]
- ,[CPAID]
- ,[EAReferral]
- ,[EATeam]
- ,[EAIndustry]
- ,[EAParentName]
- ,[EAYearAttended]
- ,[EAEventDate]
- ,[WebinarIPA]
- ,[EASpeaker]
- ,[FeeCap]
- ,[FeeType]
- ,[NumberOfEmployees]
- ,[WIP]
- ,[Industry]
- ,[SIC]
- , [LastUpdatedDate]
- , [HistoricalAlliance]
- , [REGION]
- , [Year]
- , [Quarter]
- , [Month]
- , [Week]
- , [CPAContact]
- , [CPANewExistingNewAgain]
- , [CPAOrignalSignedDate]
- , [StudyYears]
- , RefNo
- , UpdatedWIP
- , ComboWIP
- , Billed
- , Collected
- , AccountReceivable
- , [EstimatedCredits]
- , [AnnualRevenue]
- , [WorkedWIP]
- , [PendingInvoices]
- , [RemainingWIPbasedonhoursworked]
- , [UnbilledWIP]
- , [UnbilledWorkedWIP]
- , [Balance]
- , [PBDWIPAllocation]
- , [SBDWIPAllocation]
- , [SOE1WIPAllocation]
- , [SOE2WIPAllocation]
- , [PBDBilledAllocation]
- , [SBDBilledAllocation]
- , [SOE1BilledAllocation]
- , [SOE2BilledAllocation]
- , [PBDCollections]
- , [SBDCollections]
- , [SOE1Collections]
- , [SOE2Collections]
- , [OneTimeAdj]
- , [OpRefSourceRavingFan]
- , [OpRefSourceCPA]
- , [OpRefSourceConference]
- , [OpRefSourceNonConference]
- , [OpRefSourceDirect]
- , [OpRefSourceEA]
- , [OpRefSourceEmployee1]
- , [OpRefSourceEmployee2]
- , [OpRefSourceEmployee3]
- , [OpRefSourceWebsite]
- , [OpRefSourceWebinar]
- , [OpRefSourceReferralSource]
- , [PM]
- , [IndustryIntake]
- , [Percentage]
- , [AddEG]
- , [Associations]
- , [ReferralCategory]
- , [YearEnd]
- , [FeeCapPercentageType]
- ,[Description_SF]
- ,[Description_3E]
- ,[Client_SF]
- ,[Client_3E]
- ,[EngTypeCCC_SF]
- ,[EngTypeCCC_3E]
- ,[EngSignedDateCCC_SF]
- ,[EngSignedDateCCC_3E]
- ,[ServiceLine_SF]
- ,[ServiceLine_3E]
- ,[State_SF]
- ,[State_3E]
- ,[OriginalWIP_SF]
- ,[OriginalWIP_3E]
- ,[MajorIndustry_SF]
- ,[MajorIndustry_3E]
- ,[CPANewExisting]
- --,[BDMasterOppId]
- ,[OriginalDate]
- ,[FO]
- ,[BDAssist]
- ,[PBDComPercent]
- ,[PRDComPercent]
- ,[SBDComPercent]
- ,[SRDComPercent]
- ,[MinTaxYear]
- , [RecordNotInOldBDMaster]
- ,[Source]
- ,IsCloned_CCC
- ,MaxTaxYear
- )
- (select [MattIndex]
- ,[Number]
- ,[AltNumber]
- ,[DisplayName]
- ,[Description]
- ,[ClientID]
- ,[Client]
- ,[MattStatus]
- ,[CloseDate]
- ,[Currency]
- ,[MattCategory]
- ,[IsEvergreenCCC]
- ,[EngTypeCCC]
- ,[EngStatusCCC]
- ,[EngSignedDateCCC]
- ,[OpportunityIDCCC]
- ,[ServiceLine]
- ,[State]
- ,[OriginalWIP]
- ,[AdjustedWIP]
- ,[MajorIndustry]
- ,[PBD]
- ,[SBD]
- ,[PRD]
- ,[SRD]
- ,[PBDAllocationPercent]
- ,[SBDAllocationPercent]
- ,[PRDAllocationPercent]
- ,[SRDAllocationPercent]
- ,[CPA]
- ,[CPAPercent]
- ,[ReferralSource]
- ,[CPAAlliance]
- ,[Manufacturing]
- ,[Architecture]
- ,[Construction]
- ,[Engineering]
- ,[SystemIntegrator]
- ,[SFAccountID]
- ,[SFParentAccount]
- ,[SFChildID]
- ,[SFChildAccount]
- ,[CPAID]
- ,[EAReferral]
- ,[EATeam]
- ,[EAIndustry]
- ,[EAParentName]
- ,[EAYearattended]
- ,[EAEventDate]
- ,[WebinarIPA]
- ,[EASpeaker]
- ,try_convert(decimal(5,4),[FeeCap])
- ,[FeeType]
- ,[NumberOfEmployees]
- ,[WIP]
- ,[Industry]
- ,[SIC]
- , convert(datetime, convert(char(35),GETDATE(), 120))
- ,[HistoricalAlliance]
- ,[REGION]
- , [Year]
- , [Quarter]
- , [Month]
- , [Week]
- , [CPAContact]
- , [CPANewExistingNewAgain]
- , [CPAOrignalSignedDate]
- , [StudyYears]
- , [RefNo]
- , [UpdatedWIP]
- , [ComboWIP]
- , [Billed]
- , [Collected]
- , [AccountReceivable]
- , [EstimatedCredits]
- , [AnnualRevenue]
- , [WorkedWIP]
- , [PendingInvoices]
- , [RemainingWIPbasedonhoursworked]
- , [UnbilledWIP]
- , [UnbilledWorkedWIP]
- , [Balance]
- , [PBDWIPAllocation]
- , [SBDWIPAllocation]
- , [SOE1WIPAllocation]
- , [SOE2WIPAllocation]
- , [PBDBilledAllocation]
- , [SBDBilledAllocation]
- , [SOE1BilledAllocation]
- , [SOE2BilledAllocation]
- , [PBDCollections]
- , [SBDCollections]
- , [SOE1Collections]
- , [SOE2Collections]
- , [OneTimeAdj]
- , [OpRefSourceRavingFan]
- , [OpRefSourceCPA]
- , [OpRefSourceConference]
- , [OpRefSourceNonConference]
- , [OpRefSourceDirect]
- , [OpRefSourceEA]
- , [OpRefSourceEmployee1]
- , [OpRefSourceEmployee2]
- , [OpRefSourceEmployee3]
- , [OpRefSourceWebsite]
- , [OpRefSourceWebinar]
- , [OpRefSourceReferralSource]
- , [PM]
- , [IndustryIntake]
- , [Percentage]
- , [AddEG]
- , [Associations]
- , [ReferralCategory]
- , [YearEnd]
- , [FeeCapPercentageType]
- ,[Description_SF]
- ,[Description_3E]
- ,[Client_SF]
- ,[Client_3E]
- ,[EngTypeCCC_SF]
- ,[EngTypeCCC_3E]
- ,[EngSignedDateCCC_SF]
- ,[EngSignedDateCCC_3E]
- ,[ServiceLine_SF]
- ,[ServiceLine_3E]
- ,[State_SF]
- ,[State_3E]
- ,[OriginalWIP_SF]
- ,[OriginalWIP_3E]
- ,[MajorIndustry_SF]
- ,[MajorIndustry_3E]
- ,[CPANewExisting]
- --,'-1' --[BDMasterOppId]
- ,[OriginalDate]
- ,[FO]
- ,[BDAssist]
- ,[PBDComPercent]
- ,[PRDComPercent]
- ,[SBDComPercent]
- ,[SRDComPercent]
- ,[MinTaxYear]
- ,[RecordNotInOldBDMaster]
- ,'SF'
- ,IsCloned_CCC
- ,MaxTaxYear
- from #bdmFinalResults where RecordActionFlag = 'I'
- )
- --Logging record insert
- exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'Records Inserted'
- --Getting the data for Update
- --if object_id('tempdb..#bdmMatterToUpdate','U') is not null
- --drop table #bdmMatterToUpdate;
- --if object_id('tempdb..#bdmFinalResultsStr','U') is not null
- --drop table #bdmFinalResultsStr;
- -- --Converting Final Results to varchar
- --select Number, OpportunityIDCCC , AltNumber, DisplayName , Description
- --,try_convert(nvarchar(1000), ClientID) ClientID
- --,try_convert(nvarchar(1000), Client) Client
- --, MattStatus
- --,try_convert(nvarchar(1000), CloseDate) CloseDate
- --, Currency, MattCategory
- --,try_convert(nvarchar(1000), IsEvergreenCCC) IsEvergreenCCC
- --, EngTypeCCC, EngStatusCCC
- --,try_convert(nvarchar(1000), EngSignedDateCCC) EngSignedDateCCC
- --, ServiceLine, State
- --,try_convert(nvarchar(1000), OriginalWIP) OriginalWIP
- --,try_convert(nvarchar(1000), AdjustedWIP) AdjustedWIP
- --,try_convert(nvarchar(1000), UpdatedWIP) UpdatedWIP
- --,try_convert(nvarchar(1000), ComboWIP) ComboWIP
- --,try_convert(nvarchar(1000), Billed) Billed
- --,try_convert(nvarchar(1000), Collected) Collected
- --,try_convert(nvarchar(1000), AccountReceivable) AccountReceivable
- --,try_convert(nvarchar(1000), AnnualRevenue) AnnualRevenue
- --, MajorIndustry, PBD, SBD, PRD, SRD
- --,try_convert(nvarchar(1000), PBDPercent) PBDPercent
- --,try_convert(nvarchar(1000), SBDPercent) SBDPercent
- --,try_convert(nvarchar(1000), PRDPercent) PRDPercent
- --,try_convert(nvarchar(1000), SRDPercent) SRDPercent
- --, CPA
- --,try_convert(nvarchar(1000), CPAPercent) CPAPercent
- --, ReferralSource, CPAAlliance
- --,try_convert(nvarchar(1000), Manufacturing) Manufacturing
- --,try_convert(nvarchar(1000), Architecture) Architecture
- --,try_convert(nvarchar(1000), Construction) Construction
- --,try_convert(nvarchar(1000), Engineering) Engineering
- --,try_convert(nvarchar(1000), SystemIntegrator) SystemIntegrator
- --, SFAccountID, SFParentAccount, SFChildID, SFChildAccount
- --, CPAID
- --, EAReferral, EATeam, EAIndustry, EAParentName, EAYearAttended, EAEventDate, WebinarIPA, EASpeaker
- --,try_convert(nvarchar(1000), FeeCap) FeeCap
- --, FeeType
- --,try_convert(nvarchar(1000), NumberOfEmployees) NumberOfEmployees
- --,try_convert(nvarchar(1000), WIP) WIP
- --, Industry
- --,try_convert(nvarchar(1000), SIC) SIC
- --, HistoricalAlliance
- --, REGION
- --,RecordActionFlag
- --,try_convert(nvarchar(1000), [Year]) [Year]
- --,try_convert(nvarchar(1000), [Quarter]) [Quarter]
- --,try_convert(nvarchar(1000), [Month]) [Month]
- --,try_convert(nvarchar(1000), [Week]) [Week]
- --, CPAContact
- --, CPANewExistingNewAgain
- --, try_convert(nvarchar(1000),CPAOrignalSignedDate) [CPAOrignalSignedDate]
- --, StudyYears
- --, [OpRefSourceRavingFan]
- --, [OpRefSourceCPA]
- --, [OpRefSourceConference]
- --, [OpRefSourceNonConference]
- --, [OpRefSourceDirect]
- --, [OpRefSourceEA]
- --, [OpRefSourceEmployee1]
- --, [OpRefSourceEmployee2]
- --, [OpRefSourceEmployee3]
- --, [OpRefSourceWebsite]
- --, [OpRefSourceWebinar]
- --, [OpRefSourceReferralSource]
- --, try_convert(nvarchar(1), [OneTimeAdj]) [OneTimeAdj]
- --, [PM]
- --, [IndustryIntake]
- --, [Percentage]
- --, [AddEG]
- --, [Associations]
- --, [ReferralCategory]
- --into #bdmFinalResultsStr
- --from #bdmFinalResults where RecordActionFlag is null
- --if object_id('tempdb..#BDMasterSourceStr','U') is not null
- --drop table #BDMasterSourceStr;
- -- --Converting Final Results to varchar
- --select Number, OpportunityIDCCC , AltNumber, DisplayName , Description
- --,try_convert(nvarchar(1000), ClientID) ClientID
- --,try_convert(nvarchar(1000), Client) Client
- --, MattStatus
- --,try_convert(nvarchar(1000), CloseDate) CloseDate
- --, Currency, MattCategory
- --,try_convert(nvarchar(1000), IsEvergreenCCC) IsEvergreenCCC
- --, EngTypeCCC, EngStatusCCC
- --,try_convert(nvarchar(1000), EngSignedDateCCC) EngSignedDateCCC
- --, ServiceLine, State
- --,try_convert(nvarchar(1000), OriginalWIP) OriginalWIP
- --,try_convert(nvarchar(1000), AdjustedWIP) AdjustedWIP
- --,try_convert(nvarchar(1000), UpdatedWIP) UpdatedWIP
- --,try_convert(nvarchar(1000), ComboWIP) ComboWIP
- --,try_convert(nvarchar(1000), Billed) Billed
- --,try_convert(nvarchar(1000), Collected) Collected
- --,try_convert(nvarchar(1000), AccountReceivable) AccountReceivable
- --,try_convert(nvarchar(1000), AnnualRevenue) AnnualRevenue
- --, MajorIndustry, PBD, SBD, PRD, SRD
- --,try_convert(nvarchar(1000), PBDPercent) PBDPercent
- --,try_convert(nvarchar(1000), SBDPercent) SBDPercent
- --,try_convert(nvarchar(1000), PRDPercent) PRDPercent
- --,try_convert(nvarchar(1000), SRDPercent) SRDPercent
- --, CPA
- --,try_convert(nvarchar(1000), CPAPercent) CPAPercent
- --, ReferralSource, CPAAlliance
- --,try_convert(nvarchar(1000), Manufacturing) Manufacturing
- --,try_convert(nvarchar(1000), Architecture) Architecture
- --,try_convert(nvarchar(1000), Construction) Construction
- --,try_convert(nvarchar(1000), Engineering) Engineering
- --,try_convert(nvarchar(1000), SystemIntegrator) SystemIntegrator
- --, SFAccountID, SFParentAccount, SFChildID, SFChildAccount
- --, CPAID
- --, EAReferral, EATeam, EAIndustry, EAParentName, EAYearAttended, EAEventDate, WebinarIPA, EASpeaker
- --,try_convert(nvarchar(1000), FeeCap) FeeCap
- --, FeeType
- --,try_convert(nvarchar(1000), NumberOfEmployees) NumberOfEmployees
- --,try_convert(nvarchar(1000), WIP) WIP
- --, Industry
- --,try_convert(nvarchar(1000), SIC) SIC
- --, HistoricalAlliance
- --, REGION
- --,try_convert(nvarchar(1000), [Year]) [Year]
- --,try_convert(nvarchar(1000), [Quarter]) [Quarter]
- --,try_convert(nvarchar(1000), [Month]) [Month]
- --,try_convert(nvarchar(1000), [Week]) [Week]
- --, CPAContact
- --, CPANewExistingNewAgain
- --, try_convert(nvarchar(1000),CPAOrignalSignedDate) [CPAOrignalSignedDate]
- --, StudyYears
- --, [OpRefSourceRavingFan]
- --, [OpRefSourceCPA]
- --, [OpRefSourceConference]
- --, [OpRefSourceNonConference]
- --, [OpRefSourceDirect]
- --, [OpRefSourceEA]
- --, [OpRefSourceEmployee1]
- --, [OpRefSourceEmployee2]
- --, [OpRefSourceEmployee3]
- --, [OpRefSourceWebsite]
- --, [OpRefSourceWebinar]
- --, [OpRefSourceReferralSource]
- --, try_convert(nvarchar(1), [OneTimeAdj]) [OneTimeAdj]
- --, [PM]
- --, [IndustryIntake]
- --, [Percentage]
- --, [AddEG]
- --, [Associations]
- --, [ReferralCategory]
- --into #BDMasterSourceStr
- --from BDM.BDMasterSource
- ----Update record exist in BD Master Source Table
- --;WITH TEMPSOURCE AS (
- -- select Number, OpportunityIDCCC, /*[1TimeAdj],*/ colName, value FROM #bdmFinalResultsStr
- -- CROSS APPLY (VALUES (AltNumber, 'AltNumber'), (DisplayName, 'DisplayName'), (Description, 'Description'),(ClientID, 'ClientID'),(Client, 'Client'),(MattStatus, 'MattStatus'),(CloseDate, 'CloseDate'),
- -- (Currency, 'Currency'),(MattCategory, 'MattCategory'),(IsEvergreenCCC, 'IsEvergreenCCC'),(EngTypeCCC, 'EngTypeCCC'),(EngStatusCCC, 'EngStatusCCC'),(EngSignedDateCCC, 'EngSignedDateCCC'),
- -- (OpportunityIDCCC, 'OpportunityIDCCC'),(ServiceLine,'ServiceLine'),(State,'State'),(OriginalWIP,'OriginalWIP'),(AdjustedWIP, 'AdjustedWIP'),(MajorIndustry, 'MajorIndustry'),(PBD,'PBD'),
- -- (SBD,'SBD'),(PRD,'PRD'),(SRD,'SRD'),(PBDPercent,'PBDPercent'),(SBDPercent,'SBDPercent'),(PRDPercent,'PRDPercent'),(SRDPercent,'SRDPercent'),(CPA,'CPA'),(CPAPercent,'CPAPercent'),
- -- (ReferralSource,'ReferralSource'),(CPAAlliance,'CPAAlliance'),(Manufacturing,'Manufacturing'),(Architecture,'Architecture'),(Construction,'Construction'),(Engineering,'Engineering'),
- -- (SystemIntegrator,'SystemIntegrator'),(SFAccountID,'SFAccountID'),(SFParentAccount,'SFParentAccount'),(SFChildID,'SFChildD'),(SFChildAccount,'SFChildAccount'),(CPAID,'CPAID'),(EAReferral,'EAReferral'),
- -- (EATeam,'EATeam'),(EAIndustry,'EAIndustry'),(EAParentName,'EAParentName'),(EAYearAttended,'EAYearAttended'),(EAEventDate,'EAEventDate'),(WebinarIPA,'WebinarIPA'),(EASpeaker,'EASpeaker')
- -- ,(FeeCap,'FeeCap'),(FeeType,'FeeType'),(NumberOfEmployees,'NumberOfEmployees'),(WIP,'WIP'), (Industry,'Industry'), (SIC,'SIC')
- -- ,(HistoricalAlliance,'HistoricalAlliance'),(Region,'Region'), (CPAContact, 'CPAContact'), (CPANewExistingNewAgain,'CPANewExistingNewAgain')
- -- ,(CPAOrignalSignedDate,'CPAOrignalSignedDate'), (StudyYears, 'StudyYears'),(UpdatedWIP, 'UpdatedWIP'),(ComboWIP, 'ComboWIP'),(Billed, 'Billed'),(Collected, 'Collected')
- -- , (AnnualRevenue,'AnnualRevenue')
- -- , (OpRefSourceRavingFan, 'OpRefSourceRavingFan'),(OpRefSourceCPA,'OpRefSourceCPA'),(OpRefSourceConference,'OpRefSourceConference'),(OpRefSourceNonConference,'OpRefSourceNonConference')
- -- ,(OpRefSourceDirect,'OpRefSourceDirect'),(OpRefSourceEA,'OpRefSourceEA'),(OpRefSourceEmployee1,'OpRefSourceEmployee1'),(OpRefSourceEmployee2,'OpRefSourceEmployee2'),(OpRefSourceEmployee3,'OpRefSourceEmployee3')
- -- ,(OpRefSourceWebsite,'OpRefSourceWebsite'),(OpRefSourceWebinar,'OpRefSourceWebinar'),(OpRefSourceReferralSource,'OpRefSourceReferralSource')
- -- ,(OneTimeAdj,'OneTimeAdj'),(PM,'PM'), (IndustryIntake,'IndustryIntake'), (Percentage, 'Percentage'),(AddEG,'AddEG'), (Associations,'Associations'),(ReferralCategory,'ReferralCategory'))
- -- cs (value, colName) WHERE RecordActionFlag IS NULL)
- --,BDMSOURCE AS (
- -- select Number, OpportunityIDCCC,/*[1TimeAdj],*/ colName, value FROM #BDMasterSourceStr
- -- CROSS APPLY ( VALUES (AltNumber, 'AltNumber'), (DisplayName, 'DisplayName'), (Description, 'Description'),(ClientID, 'ClientID'),(Client, 'Client'),(MattStatus, 'MattStatus'),(CloseDate, 'CloseDate'),
- -- (Currency, 'Currency'),(MattCategory, 'MattCategory'),(IsEvergreenCCC, 'IsEvergreenCCC'),(EngTypeCCC, 'EngTypeCCC'),(EngStatusCCC, 'EngStatusCCC'),(EngSignedDateCCC, 'EngSignedDateCCC'),
- -- (OpportunityIDCCC, 'OpportunityIDCCC'),(ServiceLine,'ServiceLine'),(State,'State'),(OriginalWIP,'OriginalWIP'),(AdjustedWIP, 'AdjustedWIP'),(MajorIndustry, 'MajorIndustry'),(PBD,'PBD'),
- -- (SBD,'SBD'),(PRD,'PRD'),(SRD,'SRD'),(PBDPercent,'PBDPercent'),(SBDPercent,'SBDPercent'),(PRDPercent,'PRDPercent'),(SRDPercent,'SRDPercent'),(CPA,'CPA'),(CPAPercent,'CPAPercent'),
- -- (ReferralSource,'ReferralSource'),(CPAAlliance,'CPAAlliance'),(Manufacturing,'Manufacturing'),(Architecture,'Architecture'),(Construction,'Construction'),(Engineering,'Engineering'),
- -- (SystemIntegrator,'SystemIntegrator'),(SFAccountID,'SFAccountID'),(SFParentAccount,'SFParentAccount'),(SFChildID,'SFChildD'),(SFChildAccount,'SFChildAccount'),(CPAID,'CPAID'),(EAReferral,'EAReferral'),
- -- (EATeam,'EATeam'),(EAIndustry,'EAIndustry'),(EAParentName,'EAParentName'),(EAYearAttended,'EAYearAttended'),(EAEventDate,'EAEventDate'),(WebinarIPA,'WebinarIPA'),(EASpeaker,'EASpeaker')
- -- ,(FeeCap,'FeeCap'),(FeeType,'FeeType'),(NumberOfEmployees,'NumberOfEmployees'),(WIP,'WIP'), (Industry,'Industry'), (SIC,'SIC')
- -- ,(HistoricalAlliance,'HistoricalAlliance'),(Region,'Region'), (CPAContact, 'CPAContact'),(CPANewExistingNewAgain,'CPANewExistingNewAgain')
- -- ,(CPAOrignalSignedDate,'CPAOrignalSignedDate'), (StudyYears, 'StudyYears'),(UpdatedWIP, 'UpdatedWIP'), (ComboWIP, 'ComboWIP'),(Billed, 'Billed'),(Collected, 'Collected')
- -- , (AnnualRevenue, 'AnnualRevenue')
- -- , (OpRefSourceRavingFan, 'OpRefSourceRavingFan'),(OpRefSourceCPA,'OpRefSourceCPA'),(OpRefSourceConference,'OpRefSourceConference'),(OpRefSourceNonConference,'OpRefSourceNonConference')
- -- ,(OpRefSourceDirect,'OpRefSourceDirect'),(OpRefSourceEA,'OpRefSourceEA'),(OpRefSourceEmployee1,'OpRefSourceEmployee1'),(OpRefSourceEmployee2,'OpRefSourceEmployee2'),(OpRefSourceEmployee3,'OpRefSourceEmployee3')
- -- ,(OpRefSourceWebsite,'OpRefSourceWebsite'),(OpRefSourceWebinar,'OpRefSourceWebinar'),(OpRefSourceReferralSource,'OpRefSourceReferralSource')
- -- ,(OneTimeAdj,'OneTimeAdj'),(PM,'PM'), (IndustryIntake,'IndustryIntake'), (Percentage, 'Percentage'),(AddEG,'AddEG'), (Associations,'Associations'),(ReferralCategory,'ReferralCategory'))
- -- cs (value, colName))
- --SELECT DISTINCT Number, OpportunityIDCCC--, [1TimeAdj]
- --into #bdmMatterToUpdate
- --from (
- -- SELECT ts.Number, ts.OpportunityIDCCC/*, ts.[1TimeAdj]*/, ts.colName, ts.value as TempValue, bd.value AS BDMValue
- -- FROM TEMPSOURCE ts
- -- INNER JOIN BDMSource bd
- -- on COALESCE(ts.Number,ts.opportunityIdccc) = COALESCE(bd.Number,bd.opportunityidccc) /*and ts.opportunityIdccc = bd.opportunityidccc*/
- -- --and ts.[1TimeAdj] = bd.[1TimeAdj]
- -- and ts.colName = bd.colName and ISnull(ts.value,'') <> Isnull(bd.value, ''))a
- --Update #bdmFinalResults set RecordActionFlag = 'U'
- --FROM #bdmFinalResults b
- --JOIN #bdmMatterToUpdate u
- --on COALESCE(b.Number,b.OpportunityIDCCC) = COALESCE(u.Number,u.OpportunityIDCCC) --and b.OpportunityIDCCC = u.OpportunityIDCCC
- ----and b.[1TimeAdj] = u.[1TimeAdj]
- --WHERE b.RecordActionFlag IS NULL
- Update #bdmFinalResults set RecordActionFlag = 'U'
- where RecordActionFlag IS NULL and RecordForUpdate = 1
- --Update record in BDMasterSource table
- Declare @UpdateResultCount varchar(100);
- SET @UpdateResultCount = (SELECT try_convert(varchar(10),count(*)) + ' to be updated' from #bdmFinalResults where RecordActionFlag = 'U')
- exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = @UpdateResultCount
- /*
- DECLARE @Number nvarchar(64), @AltNumber nvarchar(64), @DisplayName nvarchar(255), @Description nvarchar(255), @ClientID nvarchar(255),@Client nvarchar(128),@MattStatus nvarchar(64) ,
- @CloseDate dateTime ,@Currency nvarchar(8) ,@MattCategory nvarchar(16)
- , @IsEvergreenCCC tinyint,@EngTypeCCC nvarchar(64) ,@EngStatusCCC nvarchar(64) ,@EngSignedDateCCC dateTime ,@OpportunityIDCCC nvarchar(64)
- ,@ServiceLine nvarchar(64),@State nvarchar(64),@OriginalWIP decimal(16, 2),@AdjustedWIP decimal(16, 2)
- ,@MajorIndustry nvarchar(500), @PBD nvarchar(121) ,@SBD nvarchar(121),@PRD nvarchar(121),@SRD nvarchar(121)
- ,@PBDAllocationPercent float ,@SBDAllocationPercent float,@PRDAllocationPercent float,@SRDAllocationPercent float, @CPA nvarchar(255) ,@CPAPercent float ,@ReferralSource nvarchar(1500)
- ,@CPAAlliance nvarchar(121),@Manufacturing bit,@Architecture bit,@Construction bit ,@Engineering bit ,@SystemIntegrator bit
- , @SFAccountID nvarchar(18) ,@SFParentAccount nvarchar(1500), @SFChildID nvarchar(18), @SFChildAccount nvarchar(1500)
- , @CPAID nvarchar(18),@EAReferral varchar(1500), @EATeam varchar(1500) ,@EAIndustry varchar(1500),@EAParentName varchar(1500) ,@EAYearAttended varchar(1500)
- ,@EAEventDate varchar(1500) ,@WebinarIPA varchar(1500),@EASpeaker varchar(1500)
- ,@FeeCap decimal(5,4),@FeeType nvarchar(200),@NumberOfEmployees int,@WIP decimal(16,2), @Industry nvarchar(1000), @SIC varchar(1500)
- ,@HistoricalAlliance varchar(1500), @Region varchar(1500), @Year int, @Quarter int, @Month int, @Week int
- ,@CPAContact varchar(1500), @CPANewExistingNewAgain varchar(200), @CPAOrignalSignedDate DateTime, @StudyYears varchar(10)
- ,@OpRefSourceEmployee1 varchar(500),@OpRefSourceEmployee2 varchar(500),@OpRefSourceEmployee3 varchar(500)
- ,@RefNo int, @UpdatedWIP decimal(20,2), @ComboWIP decimal(20,2), @Billed decimal(20,2), @Collected decimal(20,2), @AccountReceivable decimal(20,2)
- , @EstimatedCredits decimal(20,2), @AnnualRevenue decimal(20,2)
- ,@WorkedWIP decimal(20,2),@PendingInvoices decimal(20,2), @RemainingWIPbasedonhoursworked decimal(20,2), @UnbilledWIP decimal(20,2)
- ,@UnbilledWorkedWIP decimal(20,2), @Balance decimal(20,2), @PBDWIPAllocation decimal(20,2), @SBDWIPAllocation decimal(20,2)
- ,@SOE1WIPAllocation decimal(20,2), @SOE2WIPAllocation decimal(20,2), @PBDBilledAllocation decimal(20,2), @SBDBilledAllocation decimal(20,2)
- , @SOE1BilledAllocation decimal(20,2), @SOE2BilledAllocation decimal(20,2) , @PBDCollections decimal(20,2), @SBDCollections decimal(20,2)
- , @SOE1Collections decimal(20,2), @SOE2Collections decimal(20,2)
- , @OpRefSourceRavingFan varchar(1500), @OpRefSourceCPA varchar(1500), @OpRefSourceConference varchar(1500), @OpRefSourceNonConference varchar(1500)
- , @OpRefSourceDirect varchar(1500), @OpRefSourceEA varchar(1500), @OpRefSourceWebsite varchar(1500), @OpRefSourceWebinar varchar(1500), @OpRefSourceReferralSource varchar(1500),
- @OneTimeAdj varchar(1), @PM varchar(1500), @IndustryIntake varchar(1500), @Percentage varchar(1500), @AddEG int, @Associations varchar(1500), @ReferralCategory varchar(1500)
- , @YearEnd varchar(255) , @FeeCapPercentageType varchar(255) , @Description_SF nvarchar(255), @Description_3E nvarchar(255), @Client_SF nvarchar(255), @Client_3E nvarchar(255), @EngTypeCCC_SF nvarchar(64)
- ,@EngTypeCCC_3E nvarchar(64), @EngSignedDateCCC_SF DateTime, @EngSignedDateCCC_3E DateTime, @ServiceLine_SF nvarchar(64), @ServiceLine_3E nvarchar(64)
- ,@State_SF nvarchar(16), @State_3E nvarchar(16), @OriginalWIP_SF decimal(16,2), @OriginalWIP_3E decimal(16,2), @MajorIndustry_SF nvarchar(500), @MajorIndustry_3E nvarchar(500)
- ,@CPANewExisting varchar(1500), @OriginalDate datetime, @FO varchar(1500), @BDAssist nvarchar(1500), @MinTaxYear int
- ,@PBDComPercent decimal(18,4) ,@SBDComPercent decimal(18,4),@PRDComPercent decimal(18,4),@SRDComPercent decimal(18,4);
- DECLARE @ChangeId int , @FieldName varchar(100), @OrigValue varchar(1500), @ChangeValue varchar(1500), @Flag nvarchar(1500), @ModifiedDate dateTime;
- DECLARE @SQL nvarchar(1000);
- DECLARE @SOURCEVALUE nvarchar(1500);
- DECLARE UpdateSource CURSOR FOR
- SELECT
- [Number], [AltNumber], [DisplayName] , [Description] , [ClientID] , [Client] , [MattStatus] , [CloseDate] , [Currency] ,
- [MattCategory] , [IsEvergreenCCC] , [EngTypeCCC] , [EngStatusCCC] , [EngSignedDateCCC] , [OpportunityIDCCC] ,
- [ServiceLine] , [State] , [OriginalWIP] , [AdjustedWIP] , [MajorIndustry] , [PBD] , [SBD] , [PRD] ,
- [SRD] , [PBDAllocationPercent] , [SBDAllocationPercent] , [PRDAllocationPercent] , [SRDAllocationPercent] , [CPA] , [CPAPercent] ,
- [ReferralSource] , [CPAAlliance] , [Manufacturing] , [Architecture] , [Construction] , [Engineering] , [SystemIntegrator] , [SFAccountID] , [SFParentAccount] , [SFChildID] , [SFChildAccount] , [CPAID] ,
- [EAReferral] , [EATeam] , [EAIndustry] , [EAParentName] , [EAYearattended] , [EAEventDate] ,
- [WebinarIPA] , [EASpeaker], [FeeCap], [FeeType] ,[NumberOfEmployees], [WIP], [Industry], [SIC]
- , [HistoricalAlliance], [REGION], [Year],[Quarter], [Month], [Week], [CPAContact],[CPANewExistingNewAgain]
- , [CPAOrignalSignedDate], [StudyYears], [OpRefSourceEmployee1], [OpRefSourceEmployee2], [OpRefSourceEmployee3]
- , [RefNo],[UpdatedWIP], [ComboWIP], [Billed],[Collected],[AccountReceivable], [EstimatedCredits], [AnnualRevenue]
- , [WorkedWIP], [PendingInvoices], [RemainingWIPbasedonhoursworked], [UnbilledWIP]
- ,[UnbilledWorkedWIP], [Balance], [PBDWIPAllocation], [SBDWIPAllocation]
- ,[SOE1WIPAllocation], [SOE2WIPAllocation], [PBDBilledAllocation] , [SBDBilledAllocation]
- , [SOE1BilledAllocation], [SOE2BilledAllocation] , [PBDCollections], [SBDCollections]
- , [SOE1Collections], [SOE2Collections]
- , [OpRefSourceRavingFan], [OpRefSourceCPA], [OpRefSourceConference], [OpRefSourceNonConference]
- , [OpRefSourceDirect], [OpRefSourceEA], [OpRefSourceWebsite], [OpRefSourceWebinar], [OpRefSourceReferralSource]
- ,[OneTimeAdj], [PM], [IndustryIntake], [Percentage], [AddEG], [Associations], [ReferralCategory], [YearEnd],[FeeCapPercentageType]
- ,[Description_SF] ,[Description_3E] ,[Client_SF] ,[Client_3E] ,[EngTypeCCC_SF] ,[EngTypeCCC_3E] ,[EngSignedDateCCC_SF]
- ,[EngSignedDateCCC_3E] ,[ServiceLine_SF] ,[ServiceLine_3E] ,[State_SF] ,[State_3E] ,[OriginalWIP_SF] ,[OriginalWIP_3E]
- ,[MajorIndustry_SF] ,[MajorIndustry_3E], [CPANewExisting], [OriginalDate],[FO], [BDAssist],[MinTaxYear],[PBDComPercent],[SBDComPercent],[PRDComPercent],[SRDComPercent]
- FROM #bdmFinalResults where RecordActionFlag = 'U'
- OPEN UpdateSource
- FETCH NEXT FROM UpdateSource INTO
- @Number, @AltNumber , @DisplayName , @Description , @ClientID ,@Client ,@MattStatus ,
- @CloseDate ,@Currency ,@MattCategory , @IsEvergreenCCC ,@EngTypeCCC ,@EngStatusCCC ,@EngSignedDateCCC ,@OpportunityIDCCC
- ,@ServiceLine ,@State ,@OriginalWIP ,@AdjustedWIP ,@MajorIndustry , @PBD ,@SBD ,@PRD ,@SRD
- ,@PBDAllocationPercent ,@SBDAllocationPercent ,@PRDAllocationPercent ,@SRDAllocationPercent , @CPA ,@CPAPercent ,@ReferralSource
- ,@CPAAlliance ,@Manufacturing ,@Architecture ,@Construction ,@Engineering ,@SystemIntegrator
- , @SFAccountID ,@SFParentAccount , @SFChildID , @SFChildAccount , @CPAID ,@EAReferral , @EATeam ,@EAIndustry ,@EAParentName ,
- @EAYearAttended ,@EAEventDate ,@WebinarIPA ,@EASpeaker , @FeeCap, @FeeType ,@NumberOfEmployees, @WIP, @Industry, @SIC
- , @HistoricalAlliance, @Region, @Year, @Quarter, @Month, @Week, @CPAContact, @CPANewExistingNewAgain,@CPAOrignalSignedDate, @StudyYears
- , @OpRefSourceEmployee1, @OpRefSourceEmployee2, @OpRefSourceEmployee3
- , @RefNo, @UpdatedWIP, @ComboWIP, @Billed, @Collected, @AccountReceivable
- , @EstimatedCredits, @AnnualRevenue
- , @WorkedWIP ,@PendingInvoices , @RemainingWIPbasedonhoursworked , @UnbilledWIP
- ,@UnbilledWorkedWIP , @Balance , @PBDWIPAllocation , @SBDWIPAllocation
- ,@SOE1WIPAllocation , @SOE2WIPAllocation , @PBDBilledAllocation , @SBDBilledAllocation
- , @SOE1BilledAllocation , @SOE2BilledAllocation , @PBDCollections , @SBDCollections
- , @SOE1Collections , @SOE2Collections
- , @OpRefSourceRavingFan , @OpRefSourceCPA , @OpRefSourceConference , @OpRefSourceNonConference
- , @OpRefSourceDirect , @OpRefSourceEA ,@OpRefSourceWebsite, @OpRefSourceWebinar, @OpRefSourceReferralSource, @OneTimeAdj, @PM
- , @IndustryIntake , @Percentage , @AddEG , @Associations , @ReferralCategory, @YearEnd, @FeeCapPercentageType
- , @Description_SF, @Description_3E , @Client_SF, @Client_3E, @EngTypeCCC_SF,
- @EngTypeCCC_3E, @EngSignedDateCCC_SF, @EngSignedDateCCC_3E, @ServiceLine_SF, @ServiceLine_3E
- ,@State_SF , @State_3E , @OriginalWIP_SF , @OriginalWIP_3E , @MajorIndustry_SF , @MajorIndustry_3E , @CPANewExisting, @OriginalDate
- ,@FO, @BDAssist, @MinTaxYear, @PBDComPercent, @SBDComPercent, @PRDComPercent, @SRDComPercent
- WHILE @@FETCH_STATUS = 0
- BEGIN
- BEGIN TRY
- exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'Updating results in Source table'
- Update [bdm].[BDMasterSource] set
- [AltNumber] = @AltNumber, [DisplayName] = @DisplayName , [Description] = @Description , [ClientID] = @ClientID
- , [Client] = @Client , [MattStatus] = @MattStatus , [CloseDate] = @CloseDate , [Currency] = @Currency , [MattCategory] =@MattCategory
- , [IsEvergreenCCC] = @IsEvergreenCCC , [EngTypeCCC] = @EngTypeCCC , [EngStatusCCC] = @EngStatusCCC , [EngSignedDateCCC] = @EngSignedDateCCC
- , [OpportunityIDCCC] = @OpportunityIDCCC, [ServiceLine] = @ServiceLine , [State] = @State, [OriginalWIP] = @OriginalWIP, [AdjustedWIP] = @AdjustedWIP
- , [MajorIndustry] = @MajorIndustry, [PBD] = @PBD , [SBD] = @SBD , [PRD] = @PRD, [SRD] = @SRD , [PBDAllocationPercent] = @PBDAllocationPercent
- , [SBDAllocationPercent] = @SBDAllocationPercent , [PRDAllocationPercent] = @PRDAllocationPercent, [SRDAllocationPercent] = @SRDAllocationPercent, [CPA] = @CPA , [CPAPercent] = @CPAPercent
- , [ReferralSource] =@ReferralSource , [CPAAlliance] = @CPAAlliance , [Manufacturing] = @Manufacturing , [Architecture] = @Architecture
- , [Construction] = @Construction , [Engineering] = @Engineering , [SystemIntegrator] = @SystemIntegrator , [SFAccountID] = @SFAccountID
- , [SFParentAccount] = @SFParentAccount , [SFChildID] = @SFChildID , [SFChildAccount] = @SFChildAccount, [CPAID] = @CPAID
- , [EAReferral] = @EAReferral, [EATeam] = @EATeam , [EAIndustry] = @EAIndustry , [EAParentName] = @EAParentName,
- [EAYearAttended] = @EAYearAttended , [EAEventDate] = @EAEventDate , [WebinarIPA] = @WebinarIPA
- , [EASpeaker] = @EASpeaker, [FeeCap] = @FeeCap, [FeeType] = @FeeType , [NumberOfEmployees] = @NumberOfEmployees
- , [WIP] = @WIP, [Industry] = @Industry, [SIC] = @SIC , LastUpdatedDate = convert(datetime, convert(char(35),GETDATE(), 120)) --GETDATE()
- , [HistoricalAlliance] = @HistoricalAlliance, [REGION] = @Region, [Year] = @Year, [Quarter]= @Quarter, [Month] = @Month, [Week] = @Week
- , [CPAContact] = @CPAContact, [CPANewExistingNewAgain] = @CPANewExistingNewAgain, [CPAOrignalSignedDate] = @CPAOrignalSignedDate
- , [StudyYears] = @StudyYears, [OpRefSourceEmployee1] = @OpRefSourceEmployee1 , [OpRefSourceEmployee2] = @OpRefSourceEmployee2, [OpRefSourceEmployee3] = @OpRefSourceEmployee3
- , [RefNo] = @RefNo,[UpdatedWIP] =@UpdatedWIP, [ComboWIP] = @ComboWIP, [Billed] = @Billed, [Collected] = @Collected, [AccountReceivable] = @AccountReceivable
- , [EstimatedCredits] = @EstimatedCredits, [AnnualRevenue] = @AnnualRevenue
- , [WorkedWIP] = @WorkedWIP , [PendingInvoices] = @PendingInvoices , [RemainingWIPbasedonhoursworked] = @RemainingWIPbasedonhoursworked , [UnbilledWIP] = @UnbilledWIP
- ,[UnbilledWorkedWIP] = @UnbilledWorkedWIP , [Balance] = @Balance , [PBDWIPAllocation] = @PBDWIPAllocation , [SBDWIPAllocation] = @SBDWIPAllocation
- ,[SOE1WIPAllocation] = @SOE1WIPAllocation , [SOE2WIPAllocation] = @SOE2WIPAllocation , [PBDBilledAllocation] = @PBDBilledAllocation , [SBDBilledAllocation] = @SBDBilledAllocation
- , [SOE1BilledAllocation] = @SOE1BilledAllocation , [SOE2BilledAllocation] = @SOE2BilledAllocation , [PBDCollections] = @PBDCollections , [SBDCollections] = @SBDCollections
- , [SOE1Collections] = @SOE1Collections , [SOE2Collections] = @SOE2Collections
- , [OneTimeAdj] = @OneTimeAdj, [PM] = @PM, [OpRefSourceWebsite] = @OpRefSourceWebsite, [OpRefSourceWebinar] = @OpRefSourceWebinar, [OpRefSourceReferralSource] = @OpRefSourceReferralSource
- , [IndustryIntake] = @IndustryIntake, [Percentage] = @Percentage, [AddEG] = @AddEG, [Associations] = @Associations, [ReferralCategory] = @ReferralCategory
- , [YearEnd] = @YearEnd, [FeeCapPercentageType] = @FeeCapPercentageType
- ,[Description_SF] = @Description_SF,[Description_3E] = @Description_3E ,[Client_SF] = @Client_SF ,[Client_3E] = @Client_3E
- ,[EngTypeCCC_SF] = @EngTypeCCC_SF ,[EngTypeCCC_3E] = @EngTypeCCC_3E,[EngSignedDateCCC_SF] = @EngSignedDateCCC_SF
- ,[EngSignedDateCCC_3E] = @EngSignedDateCCC_3E ,[ServiceLine_SF] = @ServiceLine_SF ,[ServiceLine_3E] = @ServiceLine_3E
- ,[State_SF] = @State_SF ,[State_3E] = @State_3E ,[OriginalWIP_SF] = @OriginalWIP_SF ,[OriginalWIP_3E] = @OriginalWIP_3E
- ,[MajorIndustry_SF] = @MajorIndustry_SF ,[MajorIndustry_3E] = @MajorIndustry_3E, [CPANewExisting] = @CPANewExisting
- ,[OriginalDate] = @OriginalDate, [FO] = @FO, [BDAssist] = @BDAssist, [PBDComPercent] = @PBDComPercent, [SBDComPercent] = @SBDComPercent, [PRDComPercent] = @PRDComPercent, [SRDComPercent] = @SRDComPercent
- where COALESCE(Number,OpportunityIDCCC) = COALESCE(@Number,@OpportunityIDCCC) --and OpportunityIDCCC = @OpportunityIDCCC --and [1TImeAdj] = @1TimeAdj
- and MinTaxYear = @MinTaxYear
- DECLARE INNER_CURSOR CURSOR FOR SELECT ChangeId, FieldName, OrigValue, ChangeValue, Flag, ModifiedDate
- from (SELECT ChangeId, FieldName, OrigValue, ChangeValue, Flag, ModifiedDate,
- ROW_NUMBER() OVER(PARTITION BY MatterNumber, OpportunityID, FieldName order by ModifiedDate DESC) rn
- from [bdm].BDMasterChange where COALESCE(MatterNumber,OpportunityID) = COALESCE(@Number,@OpportunityIDCCC) /*and OpportunityID = @OpportunityIDCCC*/)rec where rn = 1 and flag in ('Edit From App', 'Match')
- OPEN INNER_CURSOR
- FETCH NEXT FROM INNER_CURSOR INTO @ChangeId, @FieldName, @OrigValue, @ChangeValue, @Flag, @ModifiedDate
- WHILE @@FETCH_STATUS = 0
- BEGIN
- SET @SQL = 'SELECT TOP 1 @SourceValue=' + REPLACE(@FieldName,'SFChildD','SFChildID') + ' from [bdm].[BDMasterSource] where COALESCE(Number,OpportunityIDCCC) = COALESCE(''' + @Number + ''' , ''' + @OpportunityIDCCC + ''')'
- PRINT @SQL;
- EXEC sp_executesql @SQL, N'@FieldName nvarchar(1500), @SourceValue nvarchar(1500) OUTPUT', @FieldName = @FieldName, @SourceValue = @SourceValue OUTPUT
- --Compare if value are matching and set flag to
- IF( @Flag = 'Edit From App' and @SourceValue = @ChangeValue)
- BEGIN
- --Update query and set flag to 'Match'
- UPDATE [bdm].BDMasterChange set Flag = 'Match', MatchFlagSetDate = GETDATE() where ChangeId = @ChangeId --MatterNumber = @Number
- --and OpportunityID = @OpportunityID_CCC and Flag = 'Edit From App' and FieldName = @FieldName and ModifiedDate = @ModifiedDate
- END
- ELSE IF (@Flag = 'Match' and @SourceValue <> @ChangeValue)
- BEGIN
- --Update query and set flag to 'Source'
- UPDATE [bdm].BDMasterChange set Flag = 'Source' where ChangeId = @ChangeId -- MatterNumber = @Number
- --and OpportunityID = @OpportunityID_CCC and Flag = 'Match' and FieldName = @FieldName and ModifiedDate = @ModifiedDate
- END
- FETCH NEXT FROM INNER_CURSOR INTO @ChangeId, @FieldName, @OrigValue, @ChangeValue, @Flag, @ModifiedDate
- END
- CLOSE INNER_CURSOR
- DEALLOCATE INNER_CURSOR
- END TRY
- BEGIN CATCH
- exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'ERROR', @Details = 'Error Processing Records. Please check.'
- END CATCH
- FETCH NEXT FROM UpdateSource INTO
- @Number, @AltNumber , @DisplayName , @Description , @ClientID ,@Client ,@MattStatus ,
- @CloseDate ,@Currency ,@MattCategory , @IsEvergreenCCC ,@EngTypeCCC ,@EngStatusCCC ,@EngSignedDateCCC ,@OpportunityIDCCC
- ,@ServiceLine ,@State ,@OriginalWIP ,@AdjustedWIP ,@MajorIndustry , @PBD ,@SBD ,@PRD ,@SRD
- ,@PBDAllocationPercent ,@SBDAllocationPercent ,@PRDAllocationPercent ,@SRDAllocationPercent , @CPA ,@CPAPercent ,@ReferralSource
- ,@CPAAlliance ,@Manufacturing ,@Architecture ,@Construction ,@Engineering ,@SystemIntegrator
- , @SFAccountID ,@SFParentAccount , @SFChildID , @SFChildAccount , @CPAID ,@EAReferral , @EATeam ,@EAIndustry ,@EAParentName ,
- @EAYearAttended ,@EAEventDate ,@WebinarIPA ,@EASpeaker, @FeeCap, @FeeType ,@NumberOfEmployees, @WIP, @Industry , @SIC
- , @HistoricalAlliance, @Region, @Year, @Quarter, @Month, @Week, @CPAContact, @CPANewExistingNewAgain, @CPAOrignalSignedDate
- , @StudyYears, @OpRefSourceEmployee1,@OpRefSourceEmployee2,@OpRefSourceEmployee3
- , @RefNo, @UpdatedWIP, @ComboWIP, @Billed, @Collected, @AccountReceivable
- , @EstimatedCredits, @AnnualRevenue
- , @WorkedWIP ,@PendingInvoices , @RemainingWIPbasedonhoursworked , @UnbilledWIP
- ,@UnbilledWorkedWIP , @Balance , @PBDWIPAllocation , @SBDWIPAllocation
- ,@SOE1WIPAllocation , @SOE2WIPAllocation , @PBDBilledAllocation , @SBDBilledAllocation
- , @SOE1BilledAllocation , @SOE2BilledAllocation , @PBDCollections , @SBDCollections
- , @SOE1Collections , @SOE2Collections
- , @OpRefSourceRavingFan , @OpRefSourceCPA , @OpRefSourceConference , @OpRefSourceNonConference
- , @OpRefSourceDirect , @OpRefSourceEA ,@OpRefSourceWebsite, @OpRefSourceWebinar, @OpRefSourceReferralSource, @OneTimeAdj, @PM
- , @IndustryIntake , @Percentage , @AddEG , @Associations , @ReferralCategory, @YearEnd, @FeeCapPercentageType
- , @Description_SF, @Description_3E , @Client_SF, @Client_3E, @EngTypeCCC_SF,
- @EngTypeCCC_3E, @EngSignedDateCCC_SF, @EngSignedDateCCC_3E, @ServiceLine_SF, @ServiceLine_3E
- ,@State_SF , @State_3E , @OriginalWIP_SF , @OriginalWIP_3E , @MajorIndustry_SF , @MajorIndustry_3E, @CPANewExisting
- ,@OriginalDate, @FO, @BDAssist, @MinTaxYear, @PBDComPercent, @SBDComPercent, @PRDComPercent, @SRDComPercent
- END
- CLOSE UpdateSource
- DEALLOCATE UpdateSource
- */
- -----CURSOR Replacement------
- Update BMS set
- [AltNumber] = BFR.AltNumber, [DisplayName] = BFR.DisplayName , [Description] = BFR.Description , [ClientID] = BFR.ClientID
- , [Client] = BFR.Client , [MattStatus] = BFR.MattStatus , [CloseDate] = BFR.CloseDate , [Currency] = BFR.Currency , [MattCategory] =BFR.MattCategory
- , [IsEvergreenCCC] = BFR.IsEvergreenCCC , [EngTypeCCC] = BFR.EngTypeCCC , [EngStatusCCC] = BFR.EngStatusCCC , [EngSignedDateCCC] = BFR.EngSignedDateCCC
- , [OpportunityIDCCC] = BFR.OpportunityIDCCC, [ServiceLine] = BFR.ServiceLine , [State] = BFR.State, [OriginalWIP] = BFR.OriginalWIP, [AdjustedWIP] = BFR.AdjustedWIP
- , [MajorIndustry] = BFR.MajorIndustry, [PBD] = BFR.PBD , [SBD] = BFR.SBD , [PRD] = BFR.PRD, [SRD] = BFR.SRD , [PBDAllocationPercent] = BFR.PBDAllocationPercent
- , [SBDAllocationPercent] = BFR.SBDAllocationPercent , [PRDAllocationPercent] = BFR.PRDAllocationPercent, [SRDAllocationPercent] = BFR.SRDAllocationPercent, [CPA] = BFR.CPA , [CPAPercent] = BFR.CPAPercent
- , [ReferralSource] =BFR.ReferralSource , [CPAAlliance] = BFR.CPAAlliance , [Manufacturing] = BFR.Manufacturing , [Architecture] = BFR.Architecture
- , [Construction] = BFR.Construction , [Engineering] = BFR.Engineering , [SystemIntegrator] = BFR.SystemIntegrator , [SFAccountID] = BFR.SFAccountID
- , [SFParentAccount] = BFR.SFParentAccount , [SFChildID] = BFR.SFChildID , [SFChildAccount] = BFR.SFChildAccount, [CPAID] = BFR.CPAID
- , [EAReferral] = BFR.EAReferral, [EATeam] = BFR.EATeam , [EAIndustry] = BFR.EAIndustry , [EAParentName] = BFR.EAParentName,
- [EAYearAttended] = BFR.EAYearAttended , [EAEventDate] = BFR.EAEventDate , [WebinarIPA] = BFR.WebinarIPA
- , [EASpeaker] = BFR.EASpeaker, [FeeCap] = BFR.FeeCap, [FeeType] = BFR.FeeType , [NumberOfEmployees] = BFR.NumberOfEmployees
- , [WIP] = BFR.WIP, [Industry] = BFR.Industry, [SIC] = BFR.SIC , LastUpdatedDate = convert(datetime, convert(char(35),GETDATE(), 120)) --GETDATE()
- , [HistoricalAlliance] = BFR.HistoricalAlliance, [REGION] = BFR.Region, [Year] = BFR.Year, [Quarter]= BFR.Quarter, [Month] = BFR.Month, [Week] = BFR.Week
- , [CPAContact] = BFR.CPAContact, [CPANewExistingNewAgain] = BFR.CPANewExistingNewAgain, [CPAOrignalSignedDate] = BFR.CPAOrignalSignedDate
- , [StudyYears] = BFR.StudyYears, [OpRefSourceEmployee1] = BFR.OpRefSourceEmployee1 , [OpRefSourceEmployee2] = BFR.OpRefSourceEmployee2, [OpRefSourceEmployee3] = BFR.OpRefSourceEmployee3
- , [RefNo] = BFR.RefNo,[UpdatedWIP] =BFR.UpdatedWIP, [ComboWIP] = BFR.ComboWIP, [Billed] = BFR.Billed, [Collected] = BFR.Collected, [AccountReceivable] = BFR.AccountReceivable
- , [EstimatedCredits] = BFR.EstimatedCredits, [AnnualRevenue] = BFR.AnnualRevenue
- , [WorkedWIP] = BFR.WorkedWIP , [PendingInvoices] = BFR.PendingInvoices , [RemainingWIPbasedonhoursworked] = BFR.RemainingWIPbasedonhoursworked , [UnbilledWIP] = BFR.UnbilledWIP
- ,[UnbilledWorkedWIP] = BFR.UnbilledWorkedWIP , [Balance] = BFR.Balance , [PBDWIPAllocation] = BFR.PBDWIPAllocation , [SBDWIPAllocation] = BFR.SBDWIPAllocation
- ,[SOE1WIPAllocation] = BFR.SOE1WIPAllocation , [SOE2WIPAllocation] = BFR.SOE2WIPAllocation , [PBDBilledAllocation] = BFR.PBDBilledAllocation , [SBDBilledAllocation] = BFR.SBDBilledAllocation
- , [SOE1BilledAllocation] = BFR.SOE1BilledAllocation , [SOE2BilledAllocation] = BFR.SOE2BilledAllocation , [PBDCollections] = BFR.PBDCollections , [SBDCollections] = BFR.SBDCollections
- , [SOE1Collections] = BFR.SOE1Collections , [SOE2Collections] = BFR.SOE2Collections
- , [OneTimeAdj] = BFR.OneTimeAdj, [PM] = BFR.PM, [OpRefSourceWebsite] = BFR.OpRefSourceWebsite, [OpRefSourceWebinar] = BFR.OpRefSourceWebinar, [OpRefSourceReferralSource] = BFR.OpRefSourceReferralSource
- , [IndustryIntake] = BFR.IndustryIntake, [Percentage] = BFR.Percentage, [AddEG] = BFR.AddEG, [Associations] = BFR.Associations, [ReferralCategory] = BFR.ReferralCategory
- , [YearEnd] = BFR.YearEnd, [FeeCapPercentageType] = BFR.FeeCapPercentageType
- ,[Description_SF] = BFR.Description_SF,[Description_3E] = BFR.Description_3E ,[Client_SF] = BFR.Client_SF ,[Client_3E] = BFR.Client_3E
- ,[EngTypeCCC_SF] = BFR.EngTypeCCC_SF ,[EngTypeCCC_3E] = BFR.EngTypeCCC_3E,[EngSignedDateCCC_SF] = BFR.EngSignedDateCCC_SF
- ,[EngSignedDateCCC_3E] = BFR.EngSignedDateCCC_3E ,[ServiceLine_SF] = BFR.ServiceLine_SF ,[ServiceLine_3E] = BFR.ServiceLine_3E
- ,[State_SF] = BFR.State_SF ,[State_3E] = BFR.State_3E ,[OriginalWIP_SF] = BFR.OriginalWIP_SF ,[OriginalWIP_3E] = BFR.OriginalWIP_3E
- ,[MajorIndustry_SF] = BFR.MajorIndustry_SF ,[MajorIndustry_3E] = BFR.MajorIndustry_3E, [CPANewExisting] = BFR.CPANewExisting
- ,[OriginalDate] = BFR.OriginalDate, [FO] = BFR.FO, [BDAssist] = BFR.BDAssist, [PBDComPercent] = BFR.PBDComPercent, [SBDComPercent] = BFR.SBDComPercent, [PRDComPercent] = BFR.PRDComPercent, [SRDComPercent] = BFR.SRDComPercent
- ,IsCloned_CCC = BFR.IsCloned_CCC
- ,MaxTaxYear = BFR.MaxTaxYear
- FROM
- [bdm].[BDMasterSource] BMS
- JOIN
- #bdmFinalResults BFR on BFR.RecordActionFlag = 'U'
- AND COALESCE(BMS.Number,BMS.OpportunityIDCCC) = COALESCE(BFR.Number,BFR.OpportunityIDCCC)
- and BMS.MinTaxYear = BFR.MinTaxYear
- if object_id('tempdb.dbo.#FlagChanges','U') is not null
- drop table #FlagChanges;
- SELECT ChangeId
- ,CASE WHEN Flag = 'Edit From App' and up.Value = rec.ChangeValue THEN 'Match' WHEN Flag = 'Match' and up.Value != rec.ChangeValue then 'Source' else Flag END FlagUpdate
- ,CASE WHEN Flag = 'Edit From App' and up.Value = rec.ChangeValue THEN GETDATE() WHEN Flag = 'Match' and up.Value != rec.ChangeValue then rec.MatchFlagSetDate else MatchFlagSetDate END MatchFlagSetDate
- INTO #FlagChanges
- FROM
- (
- SELECT [ID]
- ,[MattIndex]
- ,[Number]
- , [OpportunityIDCCC]
- ,CAST([AltNumber] as nvarchar(4000)) [AltNumber]
- ,CAST( [DisplayName] as nvarchar(4000)) [DisplayName]
- ,CAST( [Description] as nvarchar(4000)) [Description]
- ,CAST( [ClientID] as nvarchar(4000)) [ClientID]
- ,CAST( [Client] as nvarchar(4000)) [Client]
- ,CAST( [MattStatus] as nvarchar(4000)) [MattStatus]
- ,CAST( [CloseDate] as nvarchar(4000)) [CloseDate]
- ,CAST( [Currency] as nvarchar(4000)) [Currency]
- ,CAST( [MattCategory] as nvarchar(4000)) [MattCategory]
- ,CAST( [IsEvergreenCCC] as nvarchar(4000)) [IsEvergreenCCC]
- ,CAST( [EngTypeCCC] as nvarchar(4000)) [EngTypeCCC]
- ,CAST( [EngStatusCCC] as nvarchar(4000)) [EngStatusCCC]
- ,CAST( [EngSignedDateCCC] as nvarchar(4000)) [EngSignedDateCCC]
- ,CAST( [ServiceLine] as nvarchar(4000)) [ServiceLine]
- ,CAST( [State] as nvarchar(4000)) [State]
- ,CAST( [OriginalWIP] as nvarchar(4000)) [OriginalWIP]
- ,CAST( [AdjustedWIP] as nvarchar(4000)) [AdjustedWIP]
- ,CAST( [MajorIndustry] as nvarchar(4000)) [MajorIndustry]
- ,CAST( [PBD] as nvarchar(4000)) [PBD]
- ,CAST( [SBD] as nvarchar(4000)) [SBD]
- ,CAST( [PRD] as nvarchar(4000)) [PRD]
- ,CAST( [SRD] as nvarchar(4000)) [SRD]
- ,CAST( [CPA] as nvarchar(4000)) [CPA]
- ,CAST( [CPAPercent] as nvarchar(4000)) [CPAPercent]
- ,CAST( [ReferralSource] as nvarchar(4000)) [ReferralSource]
- ,CAST( [CPAAlliance] as nvarchar(4000)) [CPAAlliance]
- ,CAST( [Manufacturing] as nvarchar(4000)) [Manufacturing]
- ,CAST( [Architecture] as nvarchar(4000)) [Architecture]
- ,CAST( [Construction] as nvarchar(4000)) [Construction]
- ,CAST( [Engineering] as nvarchar(4000)) [Engineering]
- ,CAST( [SystemIntegrator] as nvarchar(4000)) [SystemIntegrator]
- ,CAST( [SFAccountID] as nvarchar(4000)) [SFAccountID]
- ,CAST( [SFParentAccount] as nvarchar(4000)) [SFParentAccount]
- ,CAST( [SFChildID] as nvarchar(4000)) [SFChildID]
- ,CAST( [SFChildAccount] as nvarchar(4000)) [SFChildAccount]
- ,CAST( [EAReferral] as nvarchar(4000)) [EAReferral]
- ,CAST( [EATeam] as nvarchar(4000)) [EATeam]
- ,CAST( [EAIndustry] as nvarchar(4000)) [EAIndustry]
- ,CAST( [EAParentName] as nvarchar(4000)) [EAParentName]
- ,CAST( [EAYearAttended] as nvarchar(4000)) [EAYearAttended]
- ,CAST( [EAEventDate] as nvarchar(4000)) [EAEventDate]
- ,CAST( [WebinarIPA] as nvarchar(4000)) [WebinarIPA]
- ,CAST( [EASpeaker] as nvarchar(4000)) [EASpeaker]
- ,CAST( [FeeType] as nvarchar(4000)) [FeeType]
- ,CAST( [WIP] as nvarchar(4000)) [WIP]
- ,CAST( [Industry] as nvarchar(4000)) [Industry]
- ,CAST( [NumberOfEmployees] as nvarchar(4000)) [NumberOfEmployees]
- ,CAST( [FeeCap] as nvarchar(4000)) [FeeCap]
- ,CAST( [SIC] as nvarchar(4000)) [SIC]
- ,CAST( [RefNo] as nvarchar(4000)) [RefNo]
- ,CAST( [Year] as nvarchar(4000)) [Year]
- ,CAST( [NewCount] as nvarchar(4000)) [NewCount]
- ,CAST( [UpdatedWIP] as nvarchar(4000)) [UpdatedWIP]
- ,CAST( [ComboWIP] as nvarchar(4000)) [ComboWIP]
- ,CAST( [Billed] as nvarchar(4000)) [Billed]
- ,CAST( [Collected] as nvarchar(4000)) [Collected]
- ,CAST( [AccountReceivable] as nvarchar(4000)) [AccountReceivable]
- ,CAST( [Variance] as nvarchar(4000)) [Variance]
- ,CAST( [CPAContact] as nvarchar(4000)) [CPAContact]
- ,CAST( [IndustryIntake] as nvarchar(4000)) [IndustryIntake]
- ,CAST( [TypeMG] as nvarchar(4000)) [TypeMG]
- ,CAST( [Percentage] as nvarchar(4000)) [Percentage]
- ,CAST( [EstimatedCredits] as nvarchar(4000)) [EstimatedCredits]
- ,CAST( [Other1] as nvarchar(4000)) [Other1]
- ,CAST( [O1] as nvarchar(4000)) [O1]
- ,CAST( [O2] as nvarchar(4000)) [O2]
- ,CAST( [O3] as nvarchar(4000)) [O3]
- ,CAST( [CPANewExisting] as nvarchar(4000)) [CPANewExisting]
- ,CAST( [CPACoding] as nvarchar(4000)) [CPACoding]
- ,CAST( [PBDWIPAllocation] as nvarchar(4000)) [PBDWIPAllocation]
- ,CAST( [SBDWIPAllocation] as nvarchar(4000)) [SBDWIPAllocation]
- ,CAST( [PBDBilledAllocation] as nvarchar(4000)) [PBDBilledAllocation]
- ,CAST( [SBDBilledAllocation] as nvarchar(4000)) [SBDBilledAllocation]
- ,CAST( [PBDCollections] as nvarchar(4000)) [PBDCollections]
- ,CAST( [SBDCollections] as nvarchar(4000)) [SBDCollections]
- ,CAST( [RevisedPBDWIPAllocation] as nvarchar(4000)) [RevisedPBDWIPAllocation]
- ,CAST( [RevisedSBDWIPAllocation] as nvarchar(4000)) [RevisedSBDWIPAllocation]
- ,CAST( [SOE1WIPAllocation] as nvarchar(4000)) [SOE1WIPAllocation]
- ,CAST( [SOE2WIPAllocation] as nvarchar(4000)) [SOE2WIPAllocation]
- ,CAST( [SOE1BilledAllocation] as nvarchar(4000)) [SOE1BilledAllocation]
- ,CAST( [SOE2BilledAllocation] as nvarchar(4000)) [SOE2BilledAllocation]
- ,CAST( [SOE1Collections] as nvarchar(4000)) [SOE1Collections]
- ,CAST( [SOE2Collections] as nvarchar(4000)) [SOE2Collections]
- ,CAST( [RevisedSOE1WIPAllocation] as nvarchar(4000)) [RevisedSOE1WIPAllocation]
- ,CAST( [RevisedSOE2WIPAllocation] as nvarchar(4000)) [RevisedSOE2WIPAllocation]
- ,CAST( [PBDAllocPct] as nvarchar(4000)) [PBDAllocPct]
- ,CAST( [SBDAllocPct] as nvarchar(4000)) [SBDAllocPct]
- ,CAST( [PRDPct] as nvarchar(4000)) [PRDPct]
- ,CAST( [SRDPct] as nvarchar(4000)) [SRDPct]
- ,CAST( [PBDAllocWIP] as nvarchar(4000)) [PBDAllocWIP]
- ,CAST( [SPBDAllocWIP] as nvarchar(4000)) [SPBDAllocWIP]
- ,CAST( [PRDAllocWIP] as nvarchar(4000)) [PRDAllocWIP]
- ,CAST( [SRDAllocWIP] as nvarchar(4000)) [SRDAllocWIP]
- ,CAST( [FwUpSSLSOE] as nvarchar(4000)) [FwUpSSLSOE]
- ,CAST( [FUSOEOther] as nvarchar(4000)) [FUSOEOther]
- ,CAST( [OtherSSLBD] as nvarchar(4000)) [OtherSSLBD]
- ,CAST( [179DNewvExisting] as nvarchar(4000)) [179DNewvExisting]
- ,CAST( [RemainingWIPbasedonhoursworked] as nvarchar(4000)) [RemainingWIPbasedonhoursworked]
- ,CAST( [UnbilledWIP] as nvarchar(4000)) [UnbilledWIP]
- ,CAST( [WorkedWIP] as nvarchar(4000)) [WorkedWIP]
- ,CAST( [BilledWorkedWIP] as nvarchar(4000)) [BilledWorkedWIP]
- ,CAST( [UnbilledWorkedWIP] as nvarchar(4000)) [UnbilledWorkedWIP]
- ,CAST( [PendingInvoices] as nvarchar(4000)) [PendingInvoices]
- ,CAST( [Balance] as nvarchar(4000)) [Balance]
- ,CAST( [OctoberHours] as nvarchar(4000)) [OctoberHours]
- ,CAST( [JulyWIP] as nvarchar(4000)) [JulyWIP]
- ,CAST( [PreCurrentMonthUnbilled] as nvarchar(4000)) [PreCurrentMonthUnbilled]
- ,CAST( [Comment] as nvarchar(4000)) [Comment]
- ,CAST( [Region] as nvarchar(4000)) [Region]
- ,CAST( [TrueWeek] as nvarchar(4000)) [TrueWeek]
- ,CAST( [DateCreated] as nvarchar(4000)) [DateCreated]
- ,CAST( [HistoricalAlliance] as nvarchar(4000)) [HistoricalAlliance]
- ,CAST( [AddEG] as nvarchar(4000)) [AddEG]
- ,CAST( [CPAYearSignedNewNA] as nvarchar(4000)) [CPAYearSignedNewNA]
- ,CAST( [CPANewNAExistingCount] as nvarchar(4000)) [CPANewNAExistingCount]
- ,CAST( [ReferralCategory] as nvarchar(4000)) [ReferralCategory]
- ,CAST( [FO] as nvarchar(4000)) [FO]
- ,CAST( [RegionalOffice] as nvarchar(4000)) [RegionalOffice]
- ,CAST( [Associations] as nvarchar(4000)) [Associations]
- ,CAST( [OriginalDate] as nvarchar(4000)) [OriginalDate]
- ,CAST( [WholesaleRetail] as nvarchar(4000)) [WholesaleRetail]
- ,CAST( [StudyYears] as nvarchar(4000)) [StudyYears]
- ,CAST( [ExcludeinDataMerge] as nvarchar(4000)) [ExcludeinDataMerge]
- ,CAST( [CommissionPM] as nvarchar(4000)) [CommissionPM]
- ,CAST( [PMPct] as nvarchar(4000)) [PMPct]
- ,CAST( [EGDB] as nvarchar(4000)) [EGDB]
- ,CAST( [OpRefSourceCPA] as nvarchar(4000)) [OpRefSourceCPA]
- ,CAST( [OpRefSourceConference] as nvarchar(4000)) [OpRefSourceConference]
- ,CAST( [OpRefSourceNonConference] as nvarchar(4000)) [OpRefSourceNonConference]
- ,CAST( [OpRefSourceDirect] as nvarchar(4000)) [OpRefSourceDirect]
- ,CAST( [OpRefSourceEA] as nvarchar(4000)) [OpRefSourceEA]
- ,CAST( [OpRefSourceWebinar] as nvarchar(4000)) [OpRefSourceWebinar]
- ,CAST( [OpRefSourceWebsite] as nvarchar(4000)) [OpRefSourceWebsite]
- ,CAST( [OpRefSourceReferralSource] as nvarchar(4000)) [OpRefSourceReferralSource]
- ,CAST( [PM] as nvarchar(4000)) [PM]
- ,CAST( [CR] as nvarchar(4000)) [CR]
- ,CAST( [LastUpdatedDate] as nvarchar(4000)) [LastUpdatedDate]
- ,CAST( [Quarter] as nvarchar(4000)) [Quarter]
- ,CAST( [Month] as nvarchar(4000)) [Month]
- ,CAST( [Week] as nvarchar(4000)) [Week]
- ,CAST( [CPANewExistingNewAgain] as nvarchar(4000)) [CPANewExistingNewAgain]
- ,CAST( [CPAOrignalSignedDate] as nvarchar(4000)) [CPAOrignalSignedDate]
- ,CAST( [OpRefSourceEmployee1] as nvarchar(4000)) [OpRefSourceEmployee1]
- ,CAST( [OpRefSourceEmployee2] as nvarchar(4000)) [OpRefSourceEmployee2]
- ,CAST( [OpRefSourceEmployee3] as nvarchar(4000)) [OpRefSourceEmployee3]
- ,CAST( [AnnualRevenue] as nvarchar(4000)) [AnnualRevenue]
- ,CAST( [OpRefSourceRavingFan] as nvarchar(4000)) [OpRefSourceRavingFan]
- ,CAST( [CPAID] as nvarchar(4000)) [CPAID]
- ,CAST( [YearEnd] as nvarchar(4000)) [YearEnd]
- ,CAST( [OneTimeAdj] as nvarchar(4000)) [OneTimeAdj]
- ,CAST( [Description_SF] as nvarchar(4000)) [Description_SF]
- ,CAST( [Description_3E] as nvarchar(4000)) [Description_3E]
- ,CAST( [Client_SF] as nvarchar(4000)) [Client_SF]
- ,CAST( [Client_3E] as nvarchar(4000)) [Client_3E]
- ,CAST( [EngSignedDateCCC_SF] as nvarchar(4000)) [EngSignedDateCCC_SF]
- ,CAST( [EngSignedDateCCC_3E] as nvarchar(4000)) [EngSignedDateCCC_3E]
- ,CAST( [ServiceLine_SF] as nvarchar(4000)) [ServiceLine_SF]
- ,CAST( [ServiceLine_3E] as nvarchar(4000)) [ServiceLine_3E]
- ,CAST( [State_SF] as nvarchar(4000)) [State_SF]
- ,CAST( [State_3E] as nvarchar(4000)) [State_3E]
- ,CAST( [OriginalWIP_SF] as nvarchar(4000)) [OriginalWIP_SF]
- ,CAST( [OriginalWIP_3E] as nvarchar(4000)) [OriginalWIP_3E]
- ,CAST( [MajorIndustry_SF] as nvarchar(4000)) [MajorIndustry_SF]
- ,CAST( [MajorIndustry_3E] as nvarchar(4000)) [MajorIndustry_3E]
- ,CAST( [EngTypeCCC_SF] as nvarchar(4000)) [EngTypeCCC_SF]
- ,CAST( [EngTypeCCC_3E] as nvarchar(4000)) [EngTypeCCC_3E]
- ,CAST( [PBDAllocationPercent] as nvarchar(4000)) [PBDAllocationPercent]
- ,CAST( [SBDAllocationPercent] as nvarchar(4000)) [SBDAllocationPercent]
- ,CAST( [PRDAllocationPercent] as nvarchar(4000)) [PRDAllocationPercent]
- ,CAST( [SRDAllocationPercent] as nvarchar(4000)) [SRDAllocationPercent]
- ,CAST( [FeeCapPercentageType] as nvarchar(4000)) [FeeCapPercentageType]
- ,CAST( [PBDComPercent] as nvarchar(4000)) [PBDComPercent]
- ,CAST( [SBDComPercent] as nvarchar(4000)) [SBDComPercent]
- ,CAST( [PRDComPercent] as nvarchar(4000)) [PRDComPercent]
- ,CAST( [SRDComPercent] as nvarchar(4000)) [SRDComPercent]
- ,CAST( [BDAssist] as nvarchar(4000)) [BDAssist]
- ,CAST( [MinTaxYear] as nvarchar(4000)) [MinTaxYear]
- ,CAST( [RecordNotInOldBDMaster] as nvarchar(4000)) [RecordNotInOldBDMaster]
- ,CAST( [Source] as nvarchar(4000)) [Source]
- ,CAST( [RelatedEntity] as nvarchar(4000)) [RelatedEntity]
- ,CAST( [RaveFanReferralSource] as nvarchar(4000)) [RaveFanReferralSource]
- ,CAST( [RaveFanReferralEmployee1] as nvarchar(4000)) [RaveFanReferralEmployee1]
- ,CAST( [RaveFanReferralEmployee2] as nvarchar(4000)) [RaveFanReferralEmployee2]
- ,CAST( [RaveFanReferralEmployee3] as nvarchar(4000)) [RaveFanReferralEmployee3]
- ,CAST( [RaveFanCampaign] as nvarchar(4000)) [RaveFanCampaign]
- ,CAST( [DirectReferral] as nvarchar(4000)) [DirectReferral]
- ,CAST( [CPAReferralFirm] as nvarchar(4000)) [CPAReferralFirm]
- ,CAST( [CPAReferralIPAAssociate] as nvarchar(4000)) [CPAReferralIPAAssociate]
- ,CAST( [CPAReferralCampaign] as nvarchar(4000)) [CPAReferralCampaign]
- ,CAST( [CPAReferralAccountList] as nvarchar(4000)) [CPAReferralAccountList]
- ,CAST( [EmployeeReferral] as nvarchar(4000)) [EmployeeReferral]
- ,CAST( [ReferralSourceSource] as nvarchar(4000)) [ReferralSourceSource]
- ,CAST( [ReferralSourceCampaign] as nvarchar(4000)) [ReferralSourceCampaign]
- ,CAST( [IPAReferralType] as nvarchar(4000)) [IPAReferralType]
- ,CAST( [IPAReferralSpeaker] as nvarchar(4000)) [IPAReferralSpeaker]
- ,CAST( [IPAReferralCampaign] as nvarchar(4000)) [IPAReferralCampaign]
- ,CAST( [IPAReferralAssociate] as nvarchar(4000)) [IPAReferralAssociate]
- ,CAST( [IPAReferralAccountList] as nvarchar(4000)) [IPAReferralAccountList]
- ,CAST( [EAReferralType] as nvarchar(4000)) [EAReferralType]
- ,CAST( [EAReferralSpeaker] as nvarchar(4000)) [EAReferralSpeaker]
- ,CAST( [EAReferralCampaign] as nvarchar(4000)) [EAReferralCampaign]
- ,CAST( [EAReferralLeadGenAssociate] as nvarchar(4000)) [EAReferralLeadGenAssociate]
- ,CAST( [IsCloned_CCC] as nvarchar(4000)) [IsCloned_CCC]
- FROM [BDM].[BDMasterSource])p
- UNPIVOT
- (Value FOR SourceField IN
- (
- [AltNumber]
- ,[DisplayName]
- ,[Description]
- ,[ClientID]
- ,[Client]
- ,[MattStatus]
- ,[CloseDate]
- ,[Currency]
- ,[MattCategory]
- ,[IsEvergreenCCC]
- ,[EngTypeCCC]
- ,[EngStatusCCC]
- ,[EngSignedDateCCC]
- ,[ServiceLine]
- ,[State]
- ,[OriginalWIP]
- ,[AdjustedWIP]
- ,[MajorIndustry]
- ,[PBD]
- ,[SBD]
- ,[PRD]
- ,[SRD]
- ,[CPA]
- ,[CPAPercent]
- ,[ReferralSource]
- ,[CPAAlliance]
- ,[Manufacturing]
- ,[Architecture]
- ,[Construction]
- ,[Engineering]
- ,[SystemIntegrator]
- ,[SFAccountID]
- ,[SFParentAccount]
- ,[SFChildID]
- ,[SFChildAccount]
- ,[EAReferral]
- ,[EATeam]
- ,[EAIndustry]
- ,[EAParentName]
- ,[EAYearAttended]
- ,[EAEventDate]
- ,[WebinarIPA]
- ,[EASpeaker]
- ,[FeeType]
- ,[WIP]
- ,[Industry]
- ,[NumberOfEmployees]
- ,[FeeCap]
- ,[SIC]
- ,[RefNo]
- ,[Year]
- ,[NewCount]
- ,[UpdatedWIP]
- ,[ComboWIP]
- ,[Billed]
- ,[Collected]
- ,[AccountReceivable]
- ,[Variance]
- ,[CPAContact]
- ,[IndustryIntake]
- ,[TypeMG]
- ,[Percentage]
- ,[EstimatedCredits]
- ,[Other1]
- ,[O1]
- ,[O2]
- ,[O3]
- ,[CPANewExisting]
- ,[CPACoding]
- ,[PBDWIPAllocation]
- ,[SBDWIPAllocation]
- ,[PBDBilledAllocation]
- ,[SBDBilledAllocation]
- ,[PBDCollections]
- ,[SBDCollections]
- ,[RevisedPBDWIPAllocation]
- ,[RevisedSBDWIPAllocation]
- ,[SOE1WIPAllocation]
- ,[SOE2WIPAllocation]
- ,[SOE1BilledAllocation]
- ,[SOE2BilledAllocation]
- ,[SOE1Collections]
- ,[SOE2Collections]
- ,[RevisedSOE1WIPAllocation]
- ,[RevisedSOE2WIPAllocation]
- ,[PBDAllocPct]
- ,[SBDAllocPct]
- ,[PRDPct]
- ,[SRDPct]
- ,[PBDAllocWIP]
- ,[SPBDAllocWIP]
- ,[PRDAllocWIP]
- ,[SRDAllocWIP]
- ,[FwUpSSLSOE]
- ,[FUSOEOther]
- ,[OtherSSLBD]
- ,[179DNewvExisting]
- ,[RemainingWIPbasedonhoursworked]
- ,[UnbilledWIP]
- ,[WorkedWIP]
- ,[BilledWorkedWIP]
- ,[UnbilledWorkedWIP]
- ,[PendingInvoices]
- ,[Balance]
- ,[OctoberHours]
- ,[JulyWIP]
- ,[PreCurrentMonthUnbilled]
- ,[Comment]
- ,[Region]
- ,[TrueWeek]
- ,[DateCreated]
- ,[HistoricalAlliance]
- ,[AddEG]
- ,[CPAYearSignedNewNA]
- ,[CPANewNAExistingCount]
- ,[ReferralCategory]
- ,[FO]
- ,[RegionalOffice]
- ,[Associations]
- ,[OriginalDate]
- ,[WholesaleRetail]
- ,[StudyYears]
- ,[ExcludeinDataMerge]
- ,[CommissionPM]
- ,[PMPct]
- ,[EGDB]
- ,[OpRefSourceCPA]
- ,[OpRefSourceConference]
- ,[OpRefSourceNonConference]
- ,[OpRefSourceDirect]
- ,[OpRefSourceEA]
- ,[OpRefSourceWebinar]
- ,[OpRefSourceWebsite]
- ,[OpRefSourceReferralSource]
- ,[PM]
- ,[CR]
- ,[LastUpdatedDate]
- ,[Quarter]
- ,[Month]
- ,[Week]
- ,[CPANewExistingNewAgain]
- ,[CPAOrignalSignedDate]
- ,[OpRefSourceEmployee1]
- ,[OpRefSourceEmployee2]
- ,[OpRefSourceEmployee3]
- ,[AnnualRevenue]
- ,[OpRefSourceRavingFan]
- ,[CPAID]
- ,[YearEnd]
- ,[OneTimeAdj]
- ,[Description_SF]
- ,[Description_3E]
- ,[Client_SF]
- ,[Client_3E]
- ,[EngSignedDateCCC_SF]
- ,[EngSignedDateCCC_3E]
- ,[ServiceLine_SF]
- ,[ServiceLine_3E]
- ,[State_SF]
- ,[State_3E]
- ,[OriginalWIP_SF]
- ,[OriginalWIP_3E]
- ,[MajorIndustry_SF]
- ,[MajorIndustry_3E]
- ,[EngTypeCCC_SF]
- ,[EngTypeCCC_3E]
- ,[PBDAllocationPercent]
- ,[SBDAllocationPercent]
- ,[PRDAllocationPercent]
- ,[SRDAllocationPercent]
- ,[FeeCapPercentageType]
- ,[PBDComPercent]
- ,[SBDComPercent]
- ,[PRDComPercent]
- ,[SRDComPercent]
- ,[BDAssist]
- ,[MinTaxYear]
- ,[RecordNotInOldBDMaster]
- ,[Source]
- ,[RelatedEntity]
- ,[RaveFanReferralSource]
- ,[RaveFanReferralEmployee1]
- ,[RaveFanReferralEmployee2]
- ,[RaveFanReferralEmployee3]
- ,[RaveFanCampaign]
- ,[DirectReferral]
- ,[CPAReferralFirm]
- ,[CPAReferralIPAAssociate]
- ,[CPAReferralCampaign]
- ,[CPAReferralAccountList]
- ,[EmployeeReferral]
- ,[ReferralSourceSource]
- ,[ReferralSourceCampaign]
- ,[IPAReferralType]
- ,[IPAReferralSpeaker]
- ,[IPAReferralCampaign]
- ,[IPAReferralAssociate]
- ,[IPAReferralAccountList]
- ,[EAReferralType]
- ,[EAReferralSpeaker]
- ,[EAReferralCampaign]
- ,[EAReferralLeadGenAssociate]
- ,[IsCloned_CCC]
- )
- ) as up
- JOIN
- (
- SELECT ChangeId, FieldName, OrigValue, ChangeValue, Flag, ModifiedDate,MatterNumber,OpportunityID,MatchFlagSetDate
- ,ROW_NUMBER() OVER(PARTITION BY MatterNumber, OpportunityID, FieldName order by ModifiedDate DESC) rn
- from [bdm].BDMasterChange )rec on rn = 1 and COALESCE(MatterNumber,OpportunityID) = COALESCE(up.Number,up.OpportunityIDCCC) and REPLACE(rec.FieldName,'SFChildD','SFChildID') = up.SourceField and flag in ('Edit From App', 'Match')
- UPDATE BC
- SET Flag = FC.FlagUpdate
- ,MatchFlagSetDate = FC.MatchFlagSetDate
- FROM
- [bdm].BDMasterChange BC
- JOIN
- #FlagChanges FC on FC.ChangeId = BC.ChangeId
- ----------
- exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'Checking if there is any insert from app'
- --Update AppInsert Table and set flag to 1. With this, going forward matter data will be pulled from Source table
- Update i set UseFromSource = 1, i. ModifiedBy = 'System' , i.LastUpdatedDate = convert(datetime, convert(char(35),GETDATE(), 120)) --GETDATE()
- FROM [bdm].[BDMasterAppInsert] i
- JOIN [bdm].[BDMasterSource] s on i.Number = s.Number
- where ISNULL(i.UseFromSource ,0) = 0
- --Get Mattindex gap
- UPDATE BMS SET Mattindex = M.Mattindex
- FROM
- BDM.BDMasterSource BMS
- JOIN
- TE_3E_PROD_CLone..Matter M on M.Number COLLATE SQL_Latin1_General_CP1_CI_AS = BMS.Number
- WHERE BMS.Mattindex is null
- AND BMS.NUmber is not null
- ---Matter number change correction
- UPDATE BDU SET Number = M.Number
- FROM
- BDM.BDMasterSource BDU
- JOIN
- TE_3E_PROD_Clone..Matter M on M.MattIndex = BDU.MattIndex and M.NUmber COLLATE SQL_Latin1_General_CP1_CI_AS != BDU.Number
- DELETE--Bad Original Records
- FROM
- BDM.BDMasterSource
- WHERE
- ID IN (
- SELECT BMS.Id FROM
- BDM.BDMasterSource BMS
- JOIN
- (
- SELECT
- Matterlkup
- ,MIN(Year) MinTaxYear
- FROM
- TE_3E_PROD_Clone..PGDetHdr_CCC ph
- JOIN
- TE_3E_PROD_Clone..PGDetChild_CCC pc on pc.PGDetHdr = ph.PGDetHdr_CCCID
- GROUP BY
- Matterlkup
- ) my on BMS.MattIndex = my.MatterLkUp and BMS.MinTaxYear != my.MinTaxYear
- WHERE
- Number IN (
- SELECT
- Number
- FROM
- BDM.BDMasterSource
- WHERE
- [OneTimeAdj] != 1
- GROUP BY
- Number
- HAVING COUNT(Number)>1
- ) and BMS.AdjustedWIP = 0
- )
- --NBI delay clean up
- DELETE FROM
- bdm.BDMasterSource
- WHERE ID IN (
- SELECT ID FROM (
- SELECT s.ID,s2.Number
- from
- bdm.BDMasterSource s
- LEFT JOIN #bdmResults b
- on COALESCE(b.Number, b.[OpportunityIDCCC])= COALESCE(s.Number, s.OpportunityIdCCC) --COLLATE SQL_Latin1_General_CP1_CI_AS--and b.ServiceLine = s.ServiceLine and b.OpportunityID_CCC = s.OpportunityID_CCC
- and b.MinTaxYear = s.MinTaxYear
- LEFT JOIN
- bdm.BDMasterSource s2 on s2.Client = s.Client and s.MinTaxYear between s2.MinTaxYear and s2.YEar and s.ID != s2.ID and s2.Year>2020
- WHERE
- s.Number = '314812.0005' and
- s.Number is not null
- and b.Number is null
- ) a where
- number is not null)
- DELETE
- FROM
- [FP&A].BDM.BDMasterSource
- WHERE
- MattIndex IN (
- SELECT Mattindex
- FROM
- [FP&A].BDM.BDMasterUnpublished
- GROUP BY MattIndex
- HAVING COUNT(Mattindex)>COUNT(OpportunityIDCCC) AND COUNT(OpportunityIDCCC)>0
- )
- AND OpportunityIDCCC is null
- DELETE s
- FROM
- [FP&A].BDM.BDMasterSource s
- JOIN
- [FP&A].[BDM].[BDMasterMatterDataFrom3E] s3 on s.MattIndex = s3.MattIndex and s.MinTaxYear != s3.MinYear
- JOIN
- [FP&A].[BDM].[BDMasterMatterDataFrom3E] s3c on s.ClientID = s3c.ClientId and s.MinTaxYear = s3c.MinYear and s.MattIndex != s3c.MattIndex
- WHERE
- s.number not in
- (
- '013775.0003',
- '302081.0001',
- '000283.0002',
- '301682.0001')
- exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'ETL Process Complete'
- END
- GO
- --Step 5
- USE [FP&A]
- GO
- /****** Object: StoredProcedure [BDM].[ValidateBDMasterSourceData] Script Date: 2/6/2025 10:53:43 AM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- ALTER PROCEDURE [BDM].[ValidateBDMasterSourceData]
- AS BEGIN
- SET NOCOUNT ON
- --Getting the latest Log Id from Log Table.
- Declare @LogId int, @LogSql nvarchar(100)
- SET @LogSql = 'SELECT TOP 1 @LogId = Id from [bdm].[BDMasterSource_Log] order by StartTime desc'
- EXEC sp_executesql @LogSql, N'@LogId int OUTPUT', @LogId = @LogId OUTPUT
- exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'Validation process starts'
- --Drop the temporary table to load the table again with exception data
- if object_id('tempdb.dbo.#BDMException','U') is not null
- drop table #BDMException;
- --Getting the records from source table which has exceptions and insert into temp table.
- --select * from bdm.BDMasterExceptionType
- /*We have to add exceptions in this query and give a number in incremental order with a Prefix 'E'.
- This incremental column to be add in the unpivot query*/
- SELECT ID, ID [BDMasterSourceId] ,
- --(CASE WHEN Client IS NULL THEN 1 WHEN CPA IS NULL THEN 1 WHEN PBD IS NULL THEN 1 WHEN PRD IS NULL THEN 1
- --WHEN FeeType IS NULL THEN 1
- --WHEN Description IS NULL THEN 1 /*WHEN ISNULL(WIP,0) = 0 THEN 1*/ WHEN MajorIndustry IS NULL THEN 1 WHEN SIC IS NULL THEN 1
- --WHEN ISNULL(FeeCap,0) = 0 THEN 1 WHEN State IS NULL THEN 1 WHEN ServiceLine IS NULL THEN 1 WHEN SFAccountID IS NULL THEN 1
- --WHEN OpportunityIDCCC IS NULL THEN 1 WHEN YEAR(EngSignedDateCCC) IS NULL THEN 1 WHEN ISNULL(NumberOfEmployees,0) = 0 THEN 1 ELSE 0 END) [E1],
- CASE WHEN t.ServiceLine in ('R&D','SALT','179D Services','179D','R&D Services','SALT Services')
- THEN CASE WHEN CPA IS NULL THEN 1 WHEN Client IS NULL THEN 1 WHEN PBD IS NULL THEN 1 WHEN PRD IS NULL THEN 1
- WHEN Description IS NULL THEN 1 /*WHEN ISNULL(WIP,0) = 0 THEN 1*/ WHEN SIC IS NULL THEN 1 WHEN ISNULL(FeeCap,0) = 0 THEN 1
- WHEN State IS NULL THEN 1 WHEN EngTypeCCC IS NULL THEN 1 WHEN ServiceLine IS NULL THEN 1
- ELSE 0 END ELSE 0 END [E1],
- /*CASE WHEN (NOT t.ServiceLine IN ('ERC (ERC)', 'ERC'/*,'Business Services','Tax Services','External Audit','TCS'*/)) AND ISNULL(PBD,'1') = ISNULL(PRD,'2') THEN 2 ELSE 0 END [E2],
- CASE WHEN (NOT t.ServiceLine IN ('ERC (ERC)', 'ERC'/*,'Business Services','Tax Services','External Audit','TCS'*/)) AND ISNULL(PBD,'1') = ISNULL(SBD,'2') THEN 3 ELSE 0 END [E3],
- CASE WHEN (NOT t.ServiceLine IN ('ERC (ERC)', 'ERC'/*,'Business Services','Tax Services','External Audit','TCS'*/)) AND ISNULL(PRD,'1') = ISNULL(SRD,'2') THEN 4 ELSE 0 END [E4],*/
- CASE WHEN COALESCE(t.EngTypeCCC,'FU') in ('New','New Business') AND (t.ServiceLine IN ('R&D','SALT','179D Services','179D','R&D Services','SALT Services')) AND ISNULL(PBD,'1') = ISNULL(PRD,'2') THEN 2 ELSE 0 END [E2],
- CASE WHEN (t.ServiceLine IN ('R&D','SALT','179D Services','179D','R&D Services','SALT Services')) AND ISNULL(PBD,'1') = ISNULL(SBD,'2') THEN 3 ELSE 0 END [E3],
- CASE WHEN (t.ServiceLine IN ('R&D','SALT','179D Services','179D','R&D Services','SALT Services')) AND ISNULL(PRD,'1') = ISNULL(SRD,'2') THEN 4 ELSE 0 END [E4],
- CASE WHEN COALESCE(t.EngTypeCCC,'FU') in ('New','New Business') AND (t.serviceline LIKE '%179D%' OR t.serviceline like '%R&D%' OR t.serviceline like '%SALT%') AND (SELECT count(*) from dbo.ActiveBDRDandDraw where IsActive = 1
- And Role = 'BD' and Employee = t.PBD)<1 AND (SELECT count(*) from dbo.ActiveBDRDandDraw where IsActive = 1 And Role = 'BD'
- and Employee = t.SBD) <1 THEN 5 ELSE 0 END [E5],
- CASE WHEN COALESCE(t.EngTypeCCC,'FU') in ('New','New Business') AND (t.serviceline LIKE '%179D%' OR t.serviceline like '%R&D%' OR t.serviceline like '%SALT%') AND (SELECT count(*) from dbo.ActiveBDRDandDraw where IsActive = 1
- And Role = 'RD' and Employee =t. PRD)<1 AND (SELECT count(*) from dbo.ActiveBDRDandDraw where IsActive = 1 And Role = 'RD'
- and Employee = t.SRD) <1 THEN 6 ELSE 0 END [E6]
- into #BDMException
- FROM BDM.BDMasterSource t
- where CloseDate >= '01/01/2020'
- --Truncating exception table to reload the table with latest exceptions
- truncate table bdm.BDMasterException
- --Unpivot the exception data from temporary table and insert into BDMasterException table
- INSERT INTO bdm.BDMasterException (BDMasterSourceId, ExceptionKey)
- (
- select Id , ExceptionKey
- FROM
- (
- select ID, [E1], [E2], [E3],[E4],[E5],[E6]
- from #BDMException b
- ) as cp
- UNPIVOT (
- ExceptionKey For Exception in ([E1],[E2],[E3],[E4],[E5],[E6])
- ) as tab2
- where ISNULL(ExceptionKey ,0) <> 0
- )
- --Process completed. Logging the information in log table
- IF EXISTS (select * from BDM.BDMasterSuppressException)
- BEGIN
- Declare @BDMasterSourceId int, @ExceptionKey int, @IsRecordToSupress int;
- Declare SuppressExcCursor CURSOR For
- select BDMasterSourceId, ExceptionKey from BDM.BDMasterSuppressException
- Open SuppressExcCursor
- FETCH NEXT FROM SuppressExcCursor INTO @BDMasterSourceId, @ExceptionKey
- While @@FETCH_STATUS = 0
- begin
- SET @IsRecordToSupress = 0
- if(@ExceptionKey = 1)
- begin
- --select @IsRecordToSupress = count(*) from BDM.BDMasterSrcExceptSuppress e
- --JOIN BDM.BDMasterSource s on s.id = e.id
- --where s.Client <> e.Client OR s.CPA <> e.CPA OR s.PRD <> e.PRD
- --or s.PBD <> e.PBD OR s.PRD <> e.PRD or s.FeeType <> e.FeeType
- --or s.Description <> e.Description /*or s.WIP <> e.WIP*/ or s.MajorIndustry <> e.MajorIndustry
- --or s.SIC <> e.SIC OR s.FeeCap <> e.FeeCap or s.State <> e.State
- --or s.ServiceLine <> e.ServiceLine or s.SFAccountID <> e.SFAccountID or s.OpportunityIDCCC <> e.OpportunityIDCCC
- --or s.EngSignedDateCCC <> e.EngSignedDateCCC or s.NumberOfEmployees <> e.NumberOfEmployees
- select @IsRecordToSupress = count(*) from BDM.BDMasterSrcExceptSuppress e
- JOIN BDM.BDMasterSource s on s.id = e.id
- where s.Client <> e.Client OR s.CPA <> e.CPA OR s.PRD <> e.PRD
- or s.PBD <> e.PBD
- or s.Description <> e.Description /*or s.WIP <> e.WIP */
- or s.SIC <> e.SIC OR s.FeeCap <> e.FeeCap or s.State <> e.State or s.EngTypeCCC <> e.EngTypeCCC
- or s.ServiceLine <> e.ServiceLine
- end
- else if (@ExceptionKey = 2)
- begin
- select @IsRecordToSupress = count(*) from BDM.BDMasterSrcExceptSuppress e
- JOIN BDM.BDMasterSource s on s.id = e.id
- where s.PBD <> e.PBD OR s.PRD <> e.PRD
- end
- else if (@ExceptionKey = 3)
- begin
- select @IsRecordToSupress = count(*) from BDM.BDMasterSrcExceptSuppress e
- JOIN BDM.BDMasterSource s on s.id = e.id
- where s.PBD <> e.PBD OR s.SBD <> e.SBD
- end
- else if (@ExceptionKey = 4)
- begin
- select @IsRecordToSupress = count(*) from BDM.BDMasterSrcExceptSuppress e
- JOIN BDM.BDMasterSource s on s.id = e.id
- where s.PRD <> e.PRD OR s.SRD <> e.SRD
- end
- else if (@ExceptionKey = 5)
- begin
- select @IsRecordToSupress = count(*) from BDM.BDMasterSrcExceptSuppress e
- JOIN BDM.BDMasterSource s on s.id = e.id
- where s.ServiceLine <> e.ServiceLine OR s.PBD <> e.PBD or s.SBD <> e.SBD
- end
- else if (@ExceptionKey = 6)
- begin
- select @IsRecordToSupress = count(*) from BDM.BDMasterSrcExceptSuppress e
- JOIN BDM.BDMasterSource s on s.id = e.id
- where s.ServiceLine <> e.ServiceLine OR s.PRD <> e.PRD or s.SRD <> e.SRD
- end
- if(@IsRecordToSupress > 0)
- begin
- delete from BDM.BDMasterSuppressException where BDMasterSourceId = @BDMasterSourceId and ExceptionKey = @ExceptionKey
- end
- FETCH NEXT FROM SuppressExcCursor INTO @BDMasterSourceId, @ExceptionKey
- end
- CLOSE SuppressExcCursor
- DEALLOCATE SuppressExcCursor
- END
- exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'Validation process end'
- END
- --Step 6
- USE [FP&A]
- GO
- /****** Object: StoredProcedure [BDM].[proc_UnPublishedBDMasterMatterData] Script Date: 2/6/2025 10:55:30 AM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- CREATE PROCEDURE [BDM].[proc_UnPublishedBDMasterMatterData] (@IsUnPublished bit)
- AS BEGIN
- UPDATE BDM.BDMasterChange SET ChangeValue = LEFT(ChangeValue,11)+'00:00:00'
- where FieldName Like '%Date%' and changeValue like '%T%-%'
- ;
- if object_id('tempdb.dbo.#bdmChangeData','U') is not null
- drop table #bdmChangeData;
- WITH ChangeRecords As
- (select MatterNumber, OpportunityID, BDMasterSourceId, FieldName, ChangeValue, OrigValue, ExceptionKey, ModifiedBy
- from (
- select c.MatterNumber, c.OpportunityID, c.FieldName, c.ChangeValue, c.OrigValue, c.ExceptionKey, c.ModifiedBy, c.Flag, c.MatchFlagSetDate ,c.BDMasterSourceId,
- ROW_NUMBER() OVER(PARTITION BY MatterNumber, OpportunityID, FieldName order by modifiedDate desc) rn
- from BDM.BDMasterChange c
- --JOIn BDM.BDMasterSource s on c.BDMasterSourceId = s.id
- --where s.Id = c.BDMasterSourceId--on s.Number = c.MatterNumber and s.OpportunityIDCCC = c.OpportunityID
- --where Number is not null --and number = '309143.0002'
- -- and s.id = @ID
- ) a where rn =1 and a.Flag = 'Edit From App'
- )
- select *
- into #bdmChangeData
- from
- (
- select BDMasterSourceId, FieldName, ChangeValue from ChangeRecords)
- as ChangeData
- PIVOT (
- Max(ChangeValue)
- For FieldName In
- ([Description],[Client],[MattStatus],[CloseDate],
- [IsEvergreenCCC],[EngTypeCCC],[EngSignedDateCCC],[ServiceLine],[State],[OriginalWIP],[AdjustedWIP]
- ,[MajorIndustry],[PBD],[SBD],[PRD],[SRD],[PBDAllocationPercent],[SBDAllocationPercent],[PRDAllocationPercent],[SRDAllocationPercent],[CPA],[CPAPercent]
- ,[ReferralSource],[CPAAlliance],[SFAccountID],[SFParentAccount],[SFChildID],[SFChildAccount],[EAReferral],[EATeam],[EAIndustry],[EAParentName]
- ,[EAYearAttended],[EAEventDate],[WebinarIPA],[EASpeaker],[FeeType],[Industry],[NumberOfEmployees],[FeeCap]
- ,[SIC],[Year],[Billed],[Collected],[AccountReceivable],[CPAContact],[IndustryIntake],[EstimatedCredits]
- --,[PBDWIPAllocation],[SBDWIPAllocation],[SOE1WIPAllocation],[SOE2WIPAllocation]
- ,[Region],[HistoricalAlliance],[AddEG],[OneTimeAdj],[ReferralCategory],[FO]
- ,[Associations],[CommissionPM],[PMPct],[PBDComPercent],[SBDComPercent],[PRDComPercent],[SRDComPercent]/*,[SOE1ComPercent],[SOE2ComPercent]*/,[OpRefSourceCPA],[OpRefSourceConference],[OpRefSourceNonConference]
- ,[OpRefSourceDirect],[OpRefSourceEA],[OpRefSourceWebinar],[OpRefSourceWebsite],[OpRefSourceReferralSource],[PM],[CR]
- ,[Quarter],[Month],[Week],[CPANewExistingNewAgain],[CPAOrignalSignedDate],[OpRefSourceEmployee1],[OpRefSourceEmployee2]
- ,[OpRefSourceEmployee3],[AnnualRevenue],[OpRefSourceRavingFan],[YearEnd],[FeeCapPercentageType], [UpdatedWIP],[OriginalDate],[BDAssist]
- ,[RelatedEntity],[MinTaxYear]
- ,[Source])
- ) As ChangePivot
- if object_id('tempdb.dbo.#BDMasterDataToUnPublished','U') is not null
- drop table #BDMasterDataToUnPublished;
- select * into #BDMasterDataToUnPublished
- from (
- SELECT s.ID
- ,s.[Number]
- ,s.MattIndex
- ,COALESCE(c.[Description],s.[Description]) [Description]
- ,COALESCE(c.[Client],s.[Client]) [Client]
- ,COALESCE(c.[MattStatus],s.[MattStatus]) [MattStatus]
- ,COALESCE(c.[CloseDate],s.[CloseDate]) [CloseDate]
- ,COALESCE(c.[OriginalDate],s.[OriginalDate]) [OriginalDate]
- ,COALESCE(c.[IsEvergreenCCC],s.[IsEvergreenCCC]) [IsEvergreenCCC]
- ,COALESCE(c.[EngTypeCCC],s.[EngTypeCCC]) [EngTypeCCC]
- ,COALESCE(c.[EngSignedDateCCC],s.[EngSignedDateCCC]) [EngSignedDateCCC]
- ,s.[OpportunityIDCCC]
- ,COALESCE(c.[ServiceLine],s.[ServiceLine]) [ServiceLine]
- ,COALESCE(c.[State],s.[State]) [State]
- ,COALESCE(c.[OriginalWIP],s.[OriginalWIP]) [OriginalWIP]
- ,COALESCE(c.[AdjustedWIP],s.[AdjustedWIP]) [AdjustedWIP]
- ,COALESCE(c.[UpdatedWIP],s.[UpdatedWIP]) [UpdatedWIP]
- ,COALESCE(c.[MajorIndustry],s.[MajorIndustry]) [MajorIndustry]
- ,COALESCE(c.[PBD],s.[PBD]) [PBD]
- ,COALESCE(c.[SBD],s.[SBD]) [SBD]
- ,COALESCE(c.[PRD],s.[PRD]) [PRD]
- ,COALESCE(c.[SRD],s.[SRD]) [SRD]
- ,COALESCE(c.[PBDAllocationPercent],s.[PBDAllocationPercent]) [PBDAllocationPercent]
- ,COALESCE(c.[SBDAllocationPercent],s.[SBDAllocationPercent]) [SBDAllocationPercent]
- ,COALESCE(c.[PRDAllocationPercent],s.[PRDAllocationPercent]) [PRDAllocationPercent]
- ,COALESCE(c.[SRDAllocationPercent],s.[SRDAllocationPercent]) [SRDAllocationPercent]
- ,COALESCE(c.[CPA],s.[CPA]) [CPA]
- ,COALESCE(c.[CPAPercent],s.[CPAPercent]) [CPAPercent]
- ,COALESCE(c.[ReferralSource],s.[ReferralSource]) [ReferralSource]
- ,COALESCE(c.[CPAAlliance],s.[CPAAlliance]) [CPAAlliance]
- ,COALESCE(c.[SFAccountID],s.[SFAccountID]) [SFAccountID]
- ,COALESCE(c.[SFParentAccount],s.[SFParentAccount]) [SFParentAccount]
- ,COALESCE(c.[SFChildID],s.[SFChildID]) [SFChildID]
- ,COALESCE(c.[SFChildAccount],s.[SFChildAccount]) [SFChildAccount]
- ,COALESCE(c.[EAReferral],s.[EAReferral]) [EAReferral]
- ,COALESCE(c.[EATeam],s.[EATeam]) [EATeam]
- ,COALESCE(c.[EAIndustry],s.[EAIndustry]) [EAIndustry]
- ,COALESCE(c.[EAParentName],s.[EAParentName]) [EAParentName]
- ,COALESCE(c.[EAYearAttended],s.[EAYearAttended]) [EAYearAttended]
- ,COALESCE(c.[EAEventDate],s.[EAEventDate]) [EAEventDate]
- ,COALESCE(c.[WebinarIPA],s.[WebinarIPA]) [WebinarIPA]
- ,COALESCE(c.[EASpeaker],s.[EASpeaker]) [EASpeaker]
- ,COALESCE(c.[FeeType],s.[FeeType]) [FeeType]
- ,COALESCE(c.[Industry],s.[Industry]) [Industry]
- ,COALESCE(c.[NumberOfEmployees],s.[NumberOfEmployees]) [NumberOfEmployees]
- ,COALESCE(c.[FeeCap],s.[FeeCap]) [FeeCap]
- ,COALESCE(c.[SIC],s.[SIC]) [SIC]
- ,COALESCE(c.[Year],s.[Year]) [Year]
- ,COALESCE(c.[Billed],s.[Billed]) [Billed]
- ,COALESCE(c.[Collected],s.[Collected]) [Collected]
- ,COALESCE(c.[AccountReceivable],s.[AccountReceivable]) [AccountReceivable]
- ,COALESCE(c.[CPAContact],s.[CPAContact]) [CPAContact]
- ,COALESCE(c.[IndustryIntake],s.[IndustryIntake]) [IndustryIntake]
- ,COALESCE(c.[EstimatedCredits],s.[EstimatedCredits]) [EstimatedCredits]
- --,COALESCE(c.[PBDWIPAllocation],s.[PBDWIPAllocation]) [PBDWIPAllocation]
- --,COALESCE(c.[SBDWIPAllocation],s.[SBDWIPAllocation]) [SBDWIPAllocation]
- --,COALESCE(c.[SOE1WIPAllocation],s.[SOE1WIPAllocation]) [SOE1WIPAllocation]
- --,COALESCE(c.[SOE2WIPAllocation],s.[SOE2WIPAllocation]) [SOE2WIPAllocation]
- ,COALESCE(c.[Region],s.[Region]) [Region]
- ,COALESCE(c.[HistoricalAlliance],s.[HistoricalAlliance]) [HistoricalAlliance]
- ,COALESCE(c.[AddEG],s.[AddEG]) [AddEG]
- ,COALESCE(c.[OneTimeAdj],s.[OneTimeAdj]) [OneTimeAdj]
- ,COALESCE(c.[ReferralCategory],s.[ReferralCategory]) [ReferralCategory]
- ,COALESCE(c.[FO],s.[FO]) [FO]
- ,COALESCE(c.[Associations],s.[Associations]) [Associations]
- ,COALESCE(c.[CommissionPM],s.[CommissionPM]) [CommissionPM]
- ,COALESCE(c.[PMPct],s.[PMPct]) [PMPct]
- ,COALESCE(c.[PBDComPercent],s.[PBDComPercent]) [PBDComPercent]
- ,COALESCE(c.[SBDComPercent],s.[SBDComPercent]) [SBDComPercent]
- ,COALESCE(c.[PRDComPercent],s.[PRDComPercent]) [PRDComPercent]
- ,COALESCE(c.[SRDComPercent],s.[SRDComPercent]) [SRDComPercent]
- --,COALESCE(c.[SOE1ComPercent],s.[SOE1ComPercent]) [SOE1ComPercent]
- --,COALESCE(c.[SOE2ComPercent],s.[SOE2ComPercent]) [SOE2ComPercent]
- ,COALESCE(c.[OpRefSourceCPA],s.[OpRefSourceCPA]) [OpRefSourceCPA]
- ,COALESCE(c.[OpRefSourceConference],s.[OpRefSourceConference]) [OpRefSourceConference]
- ,COALESCE(c.[OpRefSourceNonConference],s.[OpRefSourceNonConference]) [OpRefSourceNonConference]
- ,COALESCE(c.[OpRefSourceDirect],s.[OpRefSourceDirect]) [OpRefSourceDirect]
- ,COALESCE(c.[OpRefSourceEA],s.[OpRefSourceEA]) [OpRefSourceEA]
- ,COALESCE(c.[OpRefSourceWebinar],s.[OpRefSourceWebinar]) [OpRefSourceWebinar]
- ,COALESCE(c.[OpRefSourceWebsite],s.[OpRefSourceWebsite]) [OpRefSourceWebsite]
- ,COALESCE(c.[OpRefSourceReferralSource],s.[OpRefSourceReferralSource]) [OpRefSourceReferralSource]
- ,COALESCE(c.[PM],s.[PM]) [PM]
- ,COALESCE(c.[CR],s.[CR]) [CR]
- ,COALESCE(c.[Quarter],s.[Quarter]) [Quarter]
- ,COALESCE(c.[Month],s.[Month]) [Month]
- ,COALESCE(c.[Week],s.[Week]) [Week]
- ,COALESCE(c.[CPANewExistingNewAgain],s.[CPANewExistingNewAgain]) [CPANewExistingNewAgain]
- ,COALESCE(c.[CPAOrignalSignedDate],s.[CPAOrignalSignedDate]) [CPAOrignalSignedDate]
- ,COALESCE(c.[OpRefSourceEmployee1],s.[OpRefSourceEmployee1]) [OpRefSourceEmployee1]
- ,COALESCE(c.[OpRefSourceEmployee2],s.[OpRefSourceEmployee2]) [OpRefSourceEmployee2]
- ,COALESCE(c.[OpRefSourceEmployee3],s.[OpRefSourceEmployee3]) [OpRefSourceEmployee3]
- ,COALESCE(c.[AnnualRevenue],s.[AnnualRevenue]) [AnnualRevenue]
- ,COALESCE(c.[OpRefSourceRavingFan],s.[OpRefSourceRavingFan]) [OpRefSourceRavingFan]
- ,COALESCE(c.[YearEnd], s.[YearEnd]) [YearEnd]
- ,COALESCE(c.[FeeCapPercentageType],s.[FeeCapPercentageType]) [FeeCapPercentageType]
- ,COALESCE(c.[BDAssist],s.[BDAssist]) [BDAssist]
- ,COALESCE(c.[RelatedEntity],s.[RelatedEntity]) [RelatedEntity]
- ,COALESCE(c.[MinTaxYear],s.[MinTaxYear]) [MinTaxYear]
- ,COALESCE(c.[Source],s.[Source]) [Source]
- ,s.LastUpdatedDate
- ,s.IsCloned_CCC
- ,s.MaxTaxYear
- --INTO #BDMasterDataToUnPublished
- FROM [bdm].[BDMasterSource] s
- LEFT JOIN #bdmChangeData c on s.id = c.BDMasterSourceId
- --order by s.ID
- UNION
- SELECT s.ID
- ,s.[Number]
- ,s.MattIndex
- ,COALESCE(c.[Description],s.[Description]) [Description]
- ,COALESCE(c.[Client],s.[Client]) [Client]
- ,COALESCE(c.[MattStatus],s.[MattStatus]) [MattStatus]
- ,COALESCE(c.[CloseDate],s.[CloseDate]) [CloseDate]
- ,COALESCE(c.[OriginalDate],s.[OriginalDate]) [OriginalDate]
- ,COALESCE(c.[IsEvergreenCCC],s.[IsEvergreenCCC]) [IsEvergreenCCC]
- ,COALESCE(c.[EngTypeCCC],s.[EngTypeCCC]) [EngTypeCCC]
- ,COALESCE(c.[EngSignedDateCCC],s.[EngSignedDateCCC]) [EngSignedDateCCC]
- ,s.[OpportunityIDCCC]
- ,COALESCE(c.[ServiceLine],s.[ServiceLine]) [ServiceLine]
- ,COALESCE(c.[State],s.[State]) [State]
- ,COALESCE(c.[OriginalWIP],s.[OriginalWIP]) [OriginalWIP]
- ,COALESCE(c.[AdjustedWIP],s.[AdjustedWIP]) [AdjustedWIP]
- ,COALESCE(c.[UpdatedWIP],s.[UpdatedWIP]) [UpdatedWIP]
- ,COALESCE(c.[MajorIndustry],s.[MajorIndustry]) [MajorIndustry]
- ,COALESCE(c.[PBD],s.[PBD]) [PBD]
- ,COALESCE(c.[SBD],s.[SBD]) [SBD]
- ,COALESCE(c.[PRD],s.[PRD]) [PRD]
- ,COALESCE(c.[SRD],s.[SRD]) [SRD]
- ,COALESCE(c.[PBDAllocationPercent],s.[PBDAllocationPercent]) [PBDAllocationPercent]
- ,COALESCE(c.[SBDAllocationPercent],s.[SBDAllocationPercent]) [SBDAllocationPercent]
- ,COALESCE(c.[PRDAllocationPercent],s.[PRDAllocationPercent]) [PRDAllocationPercent]
- ,COALESCE(c.[SRDAllocationPercent],s.[SRDAllocationPercent]) [SRDAllocationPercent]
- ,COALESCE(c.[CPA],s.[CPA]) [CPA]
- ,COALESCE(c.[CPAPercent],s.[CPAPercent]) [CPAPercent]
- ,COALESCE(c.[ReferralSource],s.[ReferralSource]) [ReferralSource]
- ,COALESCE(c.[CPAAlliance],s.[CPAAlliance]) [CPAAlliance]
- ,COALESCE(c.[SFAccountID],s.[SFAccountID]) [SFAccountID]
- ,COALESCE(c.[SFParentAccount],s.[SFParentAccount]) [SFParentAccount]
- ,COALESCE(c.[SFChildID],s.[SFChildID]) [SFChildID]
- ,COALESCE(c.[SFChildAccount],s.[SFChildAccount]) [SFChildAccount]
- ,COALESCE(c.[EAReferral],s.[EAReferral]) [EAReferral]
- ,COALESCE(c.[EATeam],s.[EATeam]) [EATeam]
- ,COALESCE(c.[EAIndustry],s.[EAIndustry]) [EAIndustry]
- ,COALESCE(c.[EAParentName],s.[EAParentName]) [EAParentName]
- ,COALESCE(c.[EAYearAttended],s.[EAYearAttended]) [EAYearAttended]
- ,COALESCE(c.[EAEventDate],s.[EAEventDate]) [EAEventDate]
- ,COALESCE(c.[WebinarIPA],s.[WebinarIPA]) [WebinarIPA]
- ,COALESCE(c.[EASpeaker],s.[EASpeaker]) [EASpeaker]
- ,COALESCE(c.[FeeType],s.[FeeType]) [FeeType]
- ,COALESCE(c.[Industry],s.[Industry]) [Industry]
- ,COALESCE(c.[NumberOfEmployees],s.[NumberOfEmployees]) [NumberOfEmployees]
- ,COALESCE(c.[FeeCap],s.[FeeCap]) [FeeCap]
- ,COALESCE(c.[SIC],s.[SIC]) [SIC]
- ,COALESCE(c.[Year],s.[Year]) [Year]
- ,COALESCE(c.[Billed],s.[Billed]) [Billed]
- ,COALESCE(c.[Collected],s.[Collected]) [Collected]
- ,COALESCE(c.[AccountReceivable],s.[AccountReceivable]) [AccountReceivable]
- ,COALESCE(c.[CPAContact],s.[CPAContact]) [CPAContact]
- ,COALESCE(c.[IndustryIntake],s.[IndustryIntake]) [IndustryIntake]
- ,COALESCE(c.[EstimatedCredits],s.[EstimatedCredits]) [EstimatedCredits]
- --,COALESCE(c.[PBDWIPAllocation],s.[PBDWIPAllocation]) [PBDWIPAllocation]
- --,COALESCE(c.[SBDWIPAllocation],s.[SBDWIPAllocation]) [SBDWIPAllocation]
- --,COALESCE(c.[SOE1WIPAllocation],s.[SOE1WIPAllocation]) [SOE1WIPAllocation]
- --,COALESCE(c.[SOE2WIPAllocation],s.[SOE2WIPAllocation]) [SOE2WIPAllocation]
- ,COALESCE(c.[Region],s.[Region]) [Region]
- ,COALESCE(c.[HistoricalAlliance],s.[HistoricalAlliance]) [HistoricalAlliance]
- ,COALESCE(c.[AddEG],s.[AddEG]) [AddEG]
- ,COALESCE(c.[OneTimeAdj],s.[OneTimeAdj]) [OneTimeAdj]
- ,COALESCE(c.[ReferralCategory],s.[ReferralCategory]) [ReferralCategory]
- ,COALESCE(c.[FO],s.[FO]) [FO]
- ,COALESCE(c.[Associations],s.[Associations]) [Associations]
- ,COALESCE(c.[CommissionPM],s.[CommissionPM]) [CommissionPM]
- ,COALESCE(c.[PMPct],s.[PMPct]) [PMPct]
- ,COALESCE(c.[PBDComPercent],s.[PBDComPercent]) [PBDComPercent]
- ,COALESCE(c.[SBDComPercent],s.[SBDComPercent]) [SBDComPercent]
- ,COALESCE(c.[PRDComPercent],s.[PRDComPercent]) [PRDComPercent]
- ,COALESCE(c.[SRDComPercent],s.[SRDComPercent]) [SRDComPercent]
- --,COALESCE(c.[SOE1ComPercent],s.[SOE1ComPercent]) [SOE1ComPercent]
- --,COALESCE(c.[SOE2ComPercent],s.[SOE2ComPercent]) [SOE2ComPercent]
- ,COALESCE(c.[OpRefSourceCPA],s.[OpRefSourceCPA]) [OpRefSourceCPA]
- ,COALESCE(c.[OpRefSourceConference],s.[OpRefSourceConference]) [OpRefSourceConference]
- ,COALESCE(c.[OpRefSourceNonConference],s.[OpRefSourceNonConference]) [OpRefSourceNonConference]
- ,COALESCE(c.[OpRefSourceDirect],s.[OpRefSourceDirect]) [OpRefSourceDirect]
- ,COALESCE(c.[OpRefSourceEA],s.[OpRefSourceEA]) [OpRefSourceEA]
- ,COALESCE(c.[OpRefSourceWebinar],s.[OpRefSourceWebinar]) [OpRefSourceWebinar]
- ,COALESCE(c.[OpRefSourceWebsite],s.[OpRefSourceWebsite]) [OpRefSourceWebsite]
- ,COALESCE(c.[OpRefSourceReferralSource],s.[OpRefSourceReferralSource]) [OpRefSourceReferralSource]
- ,COALESCE(c.[PM],s.[PM]) [PM]
- ,COALESCE(c.[CR],s.[CR]) [CR]
- ,COALESCE(c.[Quarter],s.[Quarter]) [Quarter]
- ,COALESCE(c.[Month],s.[Month]) [Month]
- ,COALESCE(c.[Week],s.[Week]) [Week]
- ,COALESCE(c.[CPANewExistingNewAgain],s.[CPANewExistingNewAgain]) [CPANewExistingNewAgain]
- ,COALESCE(c.[CPAOrignalSignedDate],s.[CPAOrignalSignedDate]) [CPAOrignalSignedDate]
- ,COALESCE(c.[OpRefSourceEmployee1],s.[OpRefSourceEmployee1]) [OpRefSourceEmployee1]
- ,COALESCE(c.[OpRefSourceEmployee2],s.[OpRefSourceEmployee2]) [OpRefSourceEmployee2]
- ,COALESCE(c.[OpRefSourceEmployee3],s.[OpRefSourceEmployee3]) [OpRefSourceEmployee3]
- ,COALESCE(c.[AnnualRevenue],s.[AnnualRevenue]) [AnnualRevenue]
- ,COALESCE(c.[OpRefSourceRavingFan],s.[OpRefSourceRavingFan]) [OpRefSourceRavingFan]
- ,COALESCE(c.[YearEnd], s.[YearEnd]) [YearEnd]
- ,COALESCE(c.[FeeCapPercentageType],s.[FeeCapPercentageType]) [FeeCapPercentageType]
- ,COALESCE(c.[BDAssist],s.[BDAssist]) [BDAssist]
- ,COALESCE(c.[RelatedEntity],s.[RelatedEntity]) [RelatedEntity]
- ,COALESCE(c.[MinTaxYear],s.[MinTaxYear]) [MinTaxYear]
- ,COALESCE(c.[Source],s.[Source]) [Source]
- ,s.LastUpdatedDate
- ,null
- ,null
- --INTO #BDMasterDataToUnPublished
- FROM [bdm].[BDMasterAppInsert] s
- LEFT JOIN #bdmChangeData c on s.id = c.BDMasterSourceId
- --order by s.ID
- --where s.id = 1630
- ) a order by id
- IF ISNULL(@IsUnPublished,0) = 1
- BEGIN
- IF EXISTS (SELECT * FROM #BDMasterDataToUnPublished)
- truncate table BDM.BDMasterUnPublished;
- INSERT INTO BDM.BDMasterUnPublished
- (
- [MattIndex]
- ,[Number]
- ,[Description]
- ,[Client]
- ,[MattStatus]
- ,[CloseDate]
- ,[IsEvergreenCCC]
- ,[EngTypeCCC]
- ,[EngSignedDateCCC]
- ,[OpportunityIDCCC]
- ,[ServiceLine]
- ,[State]
- ,[OriginalWIP]
- ,[AdjustedWIP]
- ,[MajorIndustry]
- ,[PBD]
- ,[SBD]
- ,[PRD]
- ,[SRD]
- ,[PBDAllocationPercent]
- ,[SBDAllocationPercent]
- ,[PRDAllocationPercent]
- ,[SRDAllocationPercent]
- ,[CPA]
- ,[CPAPercent]
- ,[ReferralSource]
- ,[CPAAlliance]
- ,[SFAccountID]
- ,[SFParentAccount]
- ,[SFChildID]
- ,[SFChildAccount]
- ,[EAReferral]
- ,[EATeam]
- ,[EAIndustry]
- ,[EAParentName]
- ,[EAYearAttended]
- ,[EAEventDate]
- ,[WebinarIPA]
- ,[EASpeaker]
- ,[FeeType]
- ,[Industry]
- ,[NumberOfEmployees]
- ,[FeeCap]
- ,[SIC]
- ,[Year]
- ,[Billed]
- ,[Collected]
- ,[AccountReceivable]
- ,[CPAContact]
- ,[IndustryIntake]
- ,[EstimatedCredits]
- ,[PBDWIPAllocation]
- ,[SBDWIPAllocation]
- ,[SOE1WIPAllocation]
- ,[SOE2WIPAllocation]
- ,[Region]
- ,[HistoricalAlliance]
- ,[AddEG]
- ,[OneTimeAdj]
- ,[ReferralCategory]
- ,[FO]
- ,[Associations]
- ,[CommissionPM]
- ,[PMPct]
- ,[PBDComPercent]
- ,[SBDComPercent]
- ,[PRDComPercent]
- ,[SRDComPercent]
- --,[SOE1ComPercent]
- --,[SOE2ComPercent]
- ,[OpRefSourceCPA]
- ,[OpRefSourceConference]
- ,[OpRefSourceNonConference]
- ,[OpRefSourceDirect]
- ,[OpRefSourceEA]
- ,[OpRefSourceWebinar]
- ,[OpRefSourceWebsite]
- ,[OpRefSourceReferralSource]
- ,[PM]
- ,[CR]
- ,[Quarter]
- ,[Month]
- ,[Week]
- ,[CPANewExistingNewAgain]
- ,[CPAOrignalSignedDate]
- ,[OpRefSourceEmployee1]
- ,[OpRefSourceEmployee2]
- ,[OpRefSourceEmployee3]
- ,[LastUpdatedDate]
- ,[OpRefSourceRavingFan]
- ,[AnnualRevenue]
- ,[YearEnd]
- ,[FeeCapPercentageType]
- ,[UpdatedWIP]
- ,[BookDate]
- ,[BDAssist]
- ,[RelatedEntity]
- ,[MinTaxYear]
- ,[Source]
- ,ISCloned_CCC
- ,MaxTaxYear
- )
- (
- SELECT
- [MattIndex]
- ,[Number]
- ,b.[Description]
- ,[Client]
- , CASE WHEN MattStatus IN ('KO','CANCELDUP','Cancel_NOEL','TERM','TERM_EG','TERM_ERCLIVE') THEN 'Suspended'
- WHEN MattStatus IN ('COMP_ERCLIVE','COMP','CLOSING','CLOSING_ERCLIVE') THEN 'Completed'
- WHEN MattStatus IN ('HOLDAR','HOLDUTL','HOLDREP','HOLDFYR','LINKED','PEND','HOLDAUD','PENDEG','INPROC'
- ,'HOLDRESELL','HOLDFYE','HOLDCLI','EGREADYTOASSIGN','NO_EL','HOLDBD','HOLDFF','HOLDAYE','PENDCOMP','HOLDARREP')
- THEN 'In-Process'
- WHEN MattStatus is null THEN
- CASE o.StageName
- WHEN 'Closed - Project Completed' THEN 'In-Process'
- WHEN 'Closed - Study Completed' THEN 'In-Process'
- WHEN 'Closed - Study in Process' THEN 'In-Process'
- WHEN 'Closed - Project in Process' THEN 'In-Process'
- ELSE 'Suspended'
- END
- ELSE MattStatus END [MattStatus]
- ,b.[CloseDate]
- ,[IsEvergreenCCC]
- ,Case when COALESCE([EngTypeCCC],'New') IN ('New','New Business') then 'New' WHEN [EngTypeCCC] in ('Follow - Up','FU') THEN 'FU' WHEN [EngTypeCCC] in ('Continuation','CONT') THEN 'New' ELSE EngTypeCCC END
- ,[EngSignedDateCCC]
- ,[OpportunityIDCCC]
- ,[ServiceLine]
- ,[State]
- ,[OriginalWIP]
- ,[AdjustedWIP]
- ,[MajorIndustry]
- ,[PBD]
- ,[SBD]
- ,[PRD]
- ,[SRD]
- ,[PBDAllocationPercent]
- ,[SBDAllocationPercent]
- ,[PRDAllocationPercent]
- ,[SRDAllocationPercent]
- ,[CPA]
- ,[CPAPercent]
- ,[ReferralSource]
- ,[CPAAlliance]
- ,[SFAccountID]
- ,[SFParentAccount]
- ,[SFChildID]
- ,[SFChildAccount]
- ,[EAReferral]
- ,[EATeam]
- ,[EAIndustry]
- ,[EAParentName]
- ,[EAYearAttended]
- ,[EAEventDate]
- ,[WebinarIPA]
- ,[EASpeaker]
- ,[FeeType]
- ,[Industry]
- ,[NumberOfEmployees]
- ,[FeeCap]
- ,[SIC]
- ,[Year]
- ,[Billed]
- ,[Collected]
- ,[AccountReceivable]
- ,[CPAContact]
- ,[IndustryIntake]
- ,[EstimatedCredits]
- ,COALESCE([PBDAllocationPercent],0) * [AdjustedWIP] [PBDWIPAllocation]
- ,COALESCE([SBDAllocationPercent],0) * [AdjustedWIP][SBDWIPAllocation]
- ,COALESCE([PRDAllocationPercent],0) * [AdjustedWIP][SOE1WIPAllocation]
- ,COALESCE([SRDAllocationPercent],0) * [AdjustedWIP][SOE2WIPAllocation]
- ,[Region]
- ,[HistoricalAlliance]
- ,[AddEG]
- ,[OneTimeAdj]
- ,[ReferralCategory]
- ,[FO]
- ,[Associations]
- ,[CommissionPM]
- ,[PMPct]
- ,[PBDComPercent]
- ,[SBDComPercent]
- ,[PRDComPercent]
- ,[SRDComPercent]
- --,[SOE1ComPercent]
- --,[SOE2ComPercent]
- ,[OpRefSourceCPA]
- ,[OpRefSourceConference]
- ,[OpRefSourceNonConference]
- ,[OpRefSourceDirect]
- ,[OpRefSourceEA]
- ,[OpRefSourceWebinar]
- ,[OpRefSourceWebsite]
- ,[OpRefSourceReferralSource]
- ,[PM]
- ,[CR]
- ,[Quarter]
- ,[Month]
- ,[Week]
- ,[CPANewExistingNewAgain]
- ,[CPAOrignalSignedDate]
- ,[OpRefSourceEmployee1]
- ,[OpRefSourceEmployee2]
- ,[OpRefSourceEmployee3]
- ,[LastUpdatedDate]
- ,[OpRefSourceRavingFan]
- ,[AnnualRevenue]
- ,[YearEnd]
- ,[FeeCapPercentageType]
- ,[UpdatedWIP]
- ,[OriginalDate]
- ,[BDAssist]
- ,[RelatedEntity]
- ,[MinTaxYear]
- ,[Source]
- ,ISCloned_CCC
- ,MaxTaxYear
- FROM #BDMasterDataToUnPublished b
- LEFT join
- SalesforceClone..Opportunity o on o.id = b.[OpportunityIDCCC])
- END
- ELSE
- SELECT [ID],
- [MattIndex]
- ,[Number]
- ,[Description]
- ,[Client]
- ,[MattStatus]
- ,[CloseDate]
- ,[IsEvergreenCCC]
- ,[EngTypeCCC]
- ,[EngSignedDateCCC]
- ,[OpportunityIDCCC]
- ,[ServiceLine]
- ,[State]
- ,[OriginalWIP]
- ,[AdjustedWIP]
- ,[MajorIndustry]
- ,[PBD]
- ,[SBD]
- ,[PRD]
- ,[SRD]
- ,[PBDAllocationPercent]
- ,[SBDAllocationPercent]
- ,[PRDAllocationPercent]
- ,[SRDAllocationPercent]
- ,[CPA]
- ,[CPAPercent]
- ,[ReferralSource]
- ,[CPAAlliance]
- ,[SFAccountID]
- ,[SFParentAccount]
- ,[SFChildID]
- ,[SFChildAccount]
- ,[EAReferral]
- ,[EATeam]
- ,[EAIndustry]
- ,[EAParentName]
- ,[EAYearAttended]
- ,[EAEventDate]
- ,[WebinarIPA]
- ,[EASpeaker]
- ,[FeeType]
- ,[Industry]
- ,[NumberOfEmployees]
- ,[FeeCap]
- ,[SIC]
- ,[Year]
- ,[Billed]
- ,[Collected]
- ,[AccountReceivable]
- ,[CPAContact]
- ,[IndustryIntake]
- ,[EstimatedCredits]
- ,COALESCE([PBDAllocationPercent],0) * [AdjustedWIP] [PBDWIPAllocation]
- ,COALESCE([SBDAllocationPercent],0) * [AdjustedWIP][SBDWIPAllocation]
- ,COALESCE([PRDAllocationPercent],0) * [AdjustedWIP][SOE1WIPAllocation]
- ,COALESCE([SRDAllocationPercent],0) * [AdjustedWIP][SOE2WIPAllocation]
- ,[Region]
- ,[HistoricalAlliance]
- ,[AddEG]
- ,[OneTimeAdj]
- ,[ReferralCategory]
- ,[FO]
- ,[Associations]
- ,[CommissionPM]
- ,[PMPct]
- ,[PBDComPercent]
- ,[SBDComPercent]
- ,[PRDComPercent]
- ,[SRDComPercent]
- --,[SOE1ComPercent]
- --,[SOE2ComPercent]
- ,[OpRefSourceCPA]
- ,[OpRefSourceConference]
- ,[OpRefSourceNonConference]
- ,[OpRefSourceDirect]
- ,[OpRefSourceEA]
- ,[OpRefSourceWebinar]
- ,[OpRefSourceWebsite]
- ,[OpRefSourceReferralSource]
- ,[PM]
- ,[CR]
- ,[Quarter]
- ,[Month]
- ,[Week]
- ,[CPANewExistingNewAgain]
- ,[CPAOrignalSignedDate]
- ,[OpRefSourceEmployee1]
- ,[OpRefSourceEmployee2]
- ,[OpRefSourceEmployee3]
- ,[LastUpdatedDate]
- ,[OpRefSourceRavingFan]
- ,[AnnualRevenue]
- ,[YearEnd]
- ,[FeeCapPercentageType]
- ,[UpdatedWIP]
- ,[OriginalDate]
- ,[BDAssist]
- ,[RelatedEntity]
- ,ISCloned_CCC
- ,MaxTaxYear
- FROM #BDMasterDataToUnPublished order by id
- END
- --Added proc to UnPublished to old source for legacy reports
- EXEC [BDM].[usprPopulateOldBDMasterTable]
- --Step 7
- USE [FP&A]
- GO
- /****** Object: StoredProcedure [dbo].[CPACombinedReportData] Script Date: 2/6/2025 11:06:52 AM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- CREATE PROC [dbo].[CPACombinedReportData] AS
- BEGIN
- set transaction isolation level read uncommitted
- /*
- drop table if exists #Round0;
- drop table if exists #Round1;
- drop table if exists #Round2;
- drop table if exists #Round3;
- drop table if exists #Round4;
- drop table if exists #Round5;
- drop table if exists #Round6;
- drop table if exists #Round7;
- drop table if exists #Round8;
- drop table if exists #Round9;
- drop table if exists #Round10;
- drop table if exists #Round11;
- drop table if exists #Round12;
- drop table if exists #Round13;
- drop table if exists #Round14;
- drop table if exists #Round15;
- drop table if exists #Round16;
- drop table if exists #Round17;
- drop table if exists #Round18;
- drop table if exists #Round19;
- SELECT CM.CPA_NAME,CF.CPAFirmName,CF.AccountID,CPAFirmIndex
- INTO #Round0
- FROM
- (
- SELECT CPA_NAME,MatterNUmber
- FROM
- [fp&a]..CPAMatch CM
- WHERE
- ARMIndex IN (
- SELECT ARMIndex
- FROM
- [fp&a]..CPAMatch
- GROUP BY ARMIndex
- HAVING COUNT(ARMIndex) = 1 AND SUM(COALESCE(TRY_CAST(AMOUNTDUETOCPA as numeric),0))>0)
- GROUP BY CPA_NAME,MatterNUmber
- ) CM
- JOIN
- TE_3E_PROD_Clone..Matter M on M.NUmber COLLATE SQL_Latin1_General_CP1_CI_AS = CM.MatterNUmber
- JOIN
- (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- GROUP BY MatterLkup
- HAVING COUNT(DISTINCT CPAFirm)=1
- )
- MCF on MCF.MatterLkup = M.MattINdex
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
- GROUP BY
- CM.CPA_NAME,CPAFirmName,CF.AccountID,CPAFirmIndex
- SELECT CM.CPA_NAME,CF.CPAFirmName,CF.AccountID,CPAFirmIndex
- INTO #Round1
- FROM
- (
- SELECT CPA_NAME,MatterNUmber
- FROM
- [fp&a]..CPAMatch CM
- WHERE
- ARMIndex IN (
- SELECT ARMIndex
- FROM
- [fp&a]..CPAMatch
- WHERE
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round0)
- GROUP BY ARMIndex
- HAVING COUNT(ARMIndex) = 1)
- AND
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round0)
- GROUP BY CPA_NAME,MatterNUmber
- ) CM
- JOIN
- TE_3E_PROD_Clone..Matter M on M.NUmber COLLATE SQL_Latin1_General_CP1_CI_AS = CM.MatterNUmber
- JOIN
- (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- GROUP BY MatterLkup
- HAVING COUNT(DISTINCT CPAFirm)=1
- )
- MCF on MCF.MatterLkup = M.MattINdex
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
- GROUP BY
- CM.CPA_NAME,CPAFirmName,CF.AccountID,CPAFirmIndex
- SELECT CM.CPA_NAME,CF.CPAFirmName,CF.AccountID,CPAFirmIndex
- INTO #Round2
- FROM
- (
- SELECT CPA_NAME,MatterNUmber
- FROM
- [fp&a]..CPAMatch CM
- WHERE
- ARMIndex IN (
- SELECT ARMIndex
- FROM
- [fp&a]..CPAMatch
- WHERE
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
- GROUP BY ARMIndex
- HAVING COUNT(ARMIndex) = 1)
- AND
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
- GROUP BY CPA_NAME,MatterNUmber
- ) CM
- JOIN
- TE_3E_PROD_Clone..Matter M on M.NUmber COLLATE SQL_Latin1_General_CP1_CI_AS = CM.MatterNUmber
- JOIN
- (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- WHERE
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round1)
- GROUP BY MatterLkup
- HAVING COUNT(DISTINCT CPAFirm)=1
- )
- MCF on MCF.MatterLkup = M.MattINdex
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
- GROUP BY
- CM.CPA_NAME,CPAFirmName,CF.AccountID,CPAFirmIndex
- SELECT CM.CPA_NAME,CF.CPAFirmName,CF.AccountID,CPAFirmIndex
- INTO #Round3
- FROM
- (
- SELECT CPA_NAME,MatterNUmber
- FROM
- [fp&a]..CPAMatch CM
- WHERE
- ARMIndex IN (
- SELECT ARMIndex
- FROM
- [fp&a]..CPAMatch
- WHERE
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
- GROUP BY ARMIndex
- HAVING COUNT(ARMIndex) = 1)
- AND
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
- GROUP BY CPA_NAME,MatterNUmber
- ) CM
- JOIN
- TE_3E_PROD_Clone..Matter M on M.NUmber COLLATE SQL_Latin1_General_CP1_CI_AS = CM.MatterNUmber
- JOIN
- (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- WHERE
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round2) AND
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round1)
- GROUP BY MatterLkup
- HAVING COUNT(DISTINCT CPAFirm)=1
- )
- MCF on MCF.MatterLkup = M.MattINdex
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
- GROUP BY
- CM.CPA_NAME,CPAFirmName,CF.AccountID,CPAFirmIndex
- SELECT CM.CPA_NAME,CF.CPAFirmName,CF.AccountID,CPAFirmIndex
- INTO #Round4
- FROM
- (
- SELECT CPA_NAME,[CLIENT ID]
- FROM
- [fp&a]..CPAMatch CM
- WHERE
- ARMIndex IN (
- SELECT ARMIndex
- FROM
- [fp&a]..CPAMatch
- WHERE
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round3) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
- GROUP BY ARMIndex
- HAVING COUNT(ARMIndex) = 1)
- AND
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round3) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
- GROUP BY CPA_NAME,[CLIENT ID]
- ) CM
- JOIN
- TE_3E_PROD_Clone..Matter M on M.Client = CM.[CLIENT ID]
- JOIN
- (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- WHERE
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round3) AND
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round2) AND
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round1)
- GROUP BY MatterLkup
- HAVING COUNT(DISTINCT CPAFirm)=1
- )
- MCF on MCF.MatterLkup = M.MattINdex
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
- GROUP BY
- CM.CPA_NAME,CPAFirmName,CF.AccountID,CPAFirmIndex
- SELECT CM.CPA_NAME,CF.CPAFirmName,CF.AccountID,CPAFirmIndex
- INTO #Round5
- --SELECT *
- FROM
- (
- SELECT CPA_NAME,ARMIndex
- FROM
- [fp&a]..CPAMatch CM
- WHERE
- ARMIndex IN (
- SELECT ARMIndex
- FROM
- [fp&a]..CPAMatch
- WHERE
- CPA_NAME != 'Null' AND
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round4) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round3) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
- GROUP BY ARMIndex
- HAVING COUNT(ARMIndex) = 1)
- AND
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round4) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round3) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
- GROUP BY CPA_NAME,ARMIndex
- ) CM
- JOIN
- TE_3E_PROD_Clone..ARMaster AM on AM.ARMIndex = CM.ARMIndex
- JOIN
- TE_3E_PROD_Clone..InvMaster IM on IM.InvIndex = AM.InvMaster
- JOIN
- TE_3E_PROD_Clone..Matter M on M.Mattindex = IM.LeadMatter
- JOIN
- (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- WHERE
- FeeAllocation is not null and
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round4) AND
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round3) AND
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round2) AND
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round1)
- GROUP BY MatterLkup
- HAVING COUNT(DISTINCT CPAFirm)=1
- )
- MCF on MCF.MatterLkup = M.MattINdex
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
- --WHERE CM.ARMIndex = 364262
- GROUP BY
- CM.CPA_NAME,CPAFirmName,CF.AccountID,CPAFirmIndex
- SELECT CM.CPA_NAME,CF.CPAFirmName,CF.AccountID,CPAFirmIndex
- INTO #Round6
- --SELECT *
- FROM
- (
- SELECT CPA_NAME,ARMIndex
- FROM
- [fp&a]..CPAMatch CM
- WHERE
- ARMIndex IN (
- SELECT ARMIndex
- FROM
- [fp&a]..CPAMatch
- WHERE
- CPA_NAME != 'Null' AND
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round5) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round4) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round3) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
- GROUP BY ARMIndex
- HAVING COUNT(ARMIndex) = 1)
- AND
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round5) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round4) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round3) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
- GROUP BY CPA_NAME,ARMIndex
- ) CM
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS = CM.CPA_NAME
- --JOIN
- --TE_3E_PROD_Clone..ARMaster AM on AM.ARMIndex = CM.ARMIndex
- --JOIN
- --TE_3E_PROD_Clone..InvMaster IM on IM.InvIndex = AM.InvMaster
- --JOIN
- --TE_3E_PROD_Clone..Matter M on M.Mattindex = IM.LeadMatter
- JOIN
- (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- WHERE
- --FeeAllocation is not null and
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round5) AND
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round4) AND
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round3) AND
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round2) AND
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round1)
- GROUP BY MatterLkup
- HAVING COUNT(DISTINCT CPAFirm)=1
- )
- MCF on CF.CPAFirmIndex = MCF.CPAFirm
- GROUP BY
- CM.CPA_NAME,CPAFirmName,CF.AccountID,CPAFirmIndex
- SELECT CM.CPA_NAME,CF.CPAFirmName,CF.AccountID,CPAFirmIndex
- INTO #Round7
- --SELECT *
- FROM
- (
- SELECT CPA_NAME,ARMIndex
- FROM
- [fp&a]..CPAMatch CM
- WHERE
- ARMIndex IN (
- SELECT ARMIndex
- FROM
- [fp&a]..CPAMatch
- WHERE
- CPA_NAME != 'Null' AND
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round6) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round5) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round4) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round3) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
- GROUP BY ARMIndex
- HAVING COUNT(ARMIndex) = 1)
- AND
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round6) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round5) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round4) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round3) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
- CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
- GROUP BY CPA_NAME,ARMIndex
- ) CM
- JOIN
- TE_3E_PROD_Clone..ARMaster AM on AM.ARMIndex = CM.ARMIndex
- JOIN
- TE_3E_PROD_Clone..InvMaster IM on IM.InvIndex = AM.InvMaster
- JOIN
- TE_3E_PROD_Clone..Matter M on M.Mattindex = IM.LeadMatter
- JOIN
- (SELECT Client,MAX(CPAFirm) CPAFirm
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm mcf
- JOIN
- TE_3E_PROD_Clone..Matter m on m.MattIndex = mcf.MatterLkup
- WHERE
- --FeeAllocation is not null and
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round6) AND
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round5) AND
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round4) AND
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round3) AND
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round2) AND
- CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round1)
- GROUP BY Client
- HAVING COUNT(DISTINCT CPAFirm)=1
- )
- MCF on MCF.Client = m.client
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
- GROUP BY
- CM.CPA_NAME,CPAFirmName,CF.AccountID,CPAFirmIndex
- SELECT CPA_NAME,CPAFirmName,a.id AccountID, CPAFirmIndex
- into #Round8
- FROM
- [fp&a]..CPAMatch cm
- JOIN
- SalesforceClone..account a on a.name = cm.CPA_NAME
- LEFT JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
- WHERE
- CPA_NAME NOT IN (
- SELECT CPA_NAME
- FROM
- #Round1
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round2
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round3
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round4
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round5
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round6
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round7)
- GROUP BY CPA_NAME,CPAFirmName,a.id , CPAFirmIndex
- SELECT CPA_NAME,CPAFirmName,cf.AccountID, cf.CPAFirmIndex
- into #Round9
- FROM
- [fp&a]..CPAMatch cm
- JOIN
- TE_3E_PROD_Clone..ARMaster AM on AM.ARMIndex = cm.ARMIndex
- JOIN
- TE_3E_PROD_Clone..Matter m on m.MattIndex = am.Matter
- JOIN
- SalesforceClone..Opportunity o on o.id = m.OpportunityID_CCC COLLATE SQL_Latin1_General_CP1_CI_AS
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = o.Referring_CPA_Firm_ID__c
- LEFT JOIN (
- SELECT CPAFirmIndex
- FROM
- #Round1
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round2
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round3
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round4
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round5
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round6
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round7
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round8) a on a.CPAFirmIndex = cf.CPAFirmIndex
- WHERE
- a.CPAFirmIndex is null and
- CPA_NAME NOT IN (
- SELECT CPA_NAME
- FROM
- #Round1
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round2
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round3
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round4
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round5
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round6
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round7
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round8)
- GROUP BY CPA_NAME,CPAFirmName,cf.AccountID , cf.CPAFirmIndex
- SELECT CPA_NAME,CPAFirmName,cf.AccountID, cf.CPAFirmIndex
- into #Round10
- FROM
- [fp&a]..CPAMatch cm
- JOIN
- TE_3E_PROD_Clone..ARMaster AM on AM.ARMIndex = cm.ARMIndex
- JOIN
- TE_3E_PROD_Clone..Matter m on m.MattIndex = am.Matter
- JOIN
- SalesforceClone..Opportunity o on o.id = m.OpportunityID_CCC COLLATE SQL_Latin1_General_CP1_CI_AS
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = o.Amending_CPA_Firm_ID__c
- LEFT JOIN (
- SELECT CPAFirmIndex
- FROM
- #Round1
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round2
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round3
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round4
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round5
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round6
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round7
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round8
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round9) a on a.CPAFirmIndex = cf.CPAFirmIndex
- WHERE
- a.CPAFirmIndex is null and
- CPA_NAME NOT IN (
- SELECT CPA_NAME
- FROM
- #Round1
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round2
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round3
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round4
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round5
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round6
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round7
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round8
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round9)
- GROUP BY CPA_NAME,CPAFirmName,cf.AccountID , cf.CPAFirmIndex
- SELECT CPA_NAME,CPAFirmName,cf.AccountID, cf.CPAFirmIndex
- into #Round11
- FROM
- [fp&a]..CPAMatch cm
- JOIN
- TE_3E_PROD_Clone..ARMaster AM on AM.ARMIndex = cm.ARMIndex
- JOIN
- TE_3E_PROD_Clone..Matter m on m.MattIndex = am.Matter
- JOIN
- TE_3E_PROD_Clone..Client c on c.ClientIndex = m.Client
- JOIN
- SalesforceClone..account ac on ac.id = c.AccountID_CCC COLLATE SQL_Latin1_General_CP1_CI_AS
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = ac.CPA_Account__c
- LEFT JOIN (
- SELECT CPAFirmIndex
- FROM
- #Round1
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round2
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round3
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round4
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round5
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round6
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round7
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round8
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round9
- UNION ALL
- SELECT CPAFirmIndex
- FROM
- #Round10) a on a.CPAFirmIndex = cf.CPAFirmIndex
- WHERE
- a.CPAFirmIndex is null and
- CPA_NAME NOT IN (
- SELECT CPA_NAME
- FROM
- #Round1
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round2
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round3
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round4
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round5
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round6
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round7
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round8
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round9
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round10)
- GROUP BY CPA_NAME,CPAFirmName,cf.AccountID , cf.CPAFirmIndex
- SELECT CPA_NAME,CPAFirmName,a.id AccountID, CPAFirmIndex
- into #Round12
- FROM
- [fp&a]..CPAMatch cm
- JOIN
- SalesforceClone..account a on a.name like '%' + cm.CPA_NAME + '%'
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
- WHERE
- CPA_NAME != 'Bbs' AND
- CPA_NAME NOT IN (
- SELECT CPA_NAME
- FROM
- #Round1
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round2
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round3
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round4
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round5
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round6
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round7
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round8
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round9
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round10
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round11)
- GROUP BY CPA_NAME,CPAFirmName,a.id , CPAFirmIndex
- SELECT CPA_NAME,CPAFirmName,a.id AccountID, CPAFirmIndex
- into #Round13
- FROM
- [fp&a]..CPAMatch cm
- JOIN
- SalesforceClone..account a on REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(a.name,'*',''),',',''),' & ',' '),' and ',' '),'.',''),' ',' ') = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(cm.CPA_NAME,'*',''),',',''),' & ',' '),' and ',' '),'.',''),' ',' ')
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
- WHERE
- CPA_NAME != 'Bbs' AND
- CPA_NAME NOT IN (
- SELECT CPA_NAME
- FROM
- #Round1
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round2
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round3
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round4
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round5
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round6
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round7
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round8
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round9
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round10
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round11
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round12)
- GROUP BY CPA_NAME,CPAFirmName,a.id , CPAFirmIndex
- SELECT CPA_NAME,CPAFirmName,a.id AccountID, CPAFirmIndex
- into #Round14
- FROM
- [fp&a]..CPAMatch cm
- JOIN
- SalesforceClone..account a on REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(a.name,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ') = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(cm.CPA_NAME,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ')
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
- WHERE
- CPA_NAME != 'Bbs' AND
- CPA_NAME NOT IN (
- SELECT CPA_NAME
- FROM
- #Round1
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round2
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round3
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round4
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round5
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round6
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round7
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round8
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round9
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round10
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round11
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round12
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round13)
- GROUP BY CPA_NAME,CPAFirmName,a.id , CPAFirmIndex
- SELECT CPA_NAME,CPAFirmName,a1.CPA_Account__c AccountID, CPAFirmIndex
- into #Round15
- FROM
- [fp&a]..CPAMatch cm
- JOIN
- SalesforceClone..Contact c on REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(c.name,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ') = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(cm.CPA_NAME,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ')
- JOIN
- SalesforceClone..account a1 on a1.CPA_Contact__c = c.id
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a1.CPA_Account__c
- WHERE
- CPA_NAME != 'Bbs' AND
- CPA_NAME NOT IN (
- SELECT CPA_NAME
- FROM
- #Round1
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round2
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round3
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round4
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round5
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round6
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round7
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round8
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round9
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round10
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round11
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round12
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round13
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round14)
- GROUP BY CPA_NAME,CPAFirmName,a1.CPA_Account__c , CPAFirmIndex
- SELECT CPA_NAME,CPAFirmName,c.AccountId AccountID, CPAFirmIndex
- into #Round16
- FROM
- [fp&a]..CPAMatch cm
- JOIN
- SalesforceClone..Contact c on REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(c.name,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ') = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(cm.CPA_NAME,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ')
- --JOIN
- --SalesforceClone..account a1 on a1.id = c.AccountId
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = c.AccountId
- WHERE
- CPA_NAME != 'Bbs' AND CPAFirmName not in ('Miller Ward & Co','Welker Harris & Co') AND
- CPA_NAME NOT IN (
- SELECT CPA_NAME
- FROM
- #Round1
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round2
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round3
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round4
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round5
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round6
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round7
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round8
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round9
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round10
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round11
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round12
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round13
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round14
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round15)
- GROUP BY CPA_NAME,CPAFirmName,c.AccountId , CPAFirmIndex
- SELECT CPA_NAME,CPAFirmName,a1.CPA_Account__c AccountID, CPAFirmIndex
- into #Round17
- FROM
- [fp&a]..CPAMatch cm
- JOIN
- SalesforceClone..Contact c on REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(c.name,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ') = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(cm.CPA_NAME,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ')
- JOIN
- SalesforceClone..account a1 on a1.id = c.AccountId
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a1.CPA_Account__c
- WHERE
- CPA_NAME != 'Bbs' AND CPAFirmName not in ('Miller Ward & Co','Welker Harris & Co','Harding Shymanski & Company Psc - Evansville IN') AND
- CPA_NAME NOT IN (
- SELECT CPA_NAME
- FROM
- #Round1
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round2
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round3
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round4
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round5
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round6
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round7
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round8
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round9
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round10
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round11
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round12
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round13
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round14
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round15
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round16)
- GROUP BY CPA_NAME,CPAFirmName,a1.CPA_Account__c , CPAFirmIndex
- SELECT CPA_NAME,CPAFirmName,a.id AccountID, CPAFirmIndex
- into #Round18
- FROM
- [fp&a]..CPAMatch cm
- JOIN
- SalesforceClone..account a on REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(a.name,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ') like '%' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(cm.CPA_NAME,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ') + '%'
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
- WHERE
- CPA_NAME != 'Bbs' AND
- CPA_NAME NOT IN (
- SELECT CPA_NAME
- FROM
- #Round1
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round2
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round3
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round4
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round5
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round6
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round7
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round8
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round9
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round10
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round11
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round12
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round13
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round14
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round15
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round16
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round17)
- GROUP BY CPA_NAME,CPAFirmName,a.id , CPAFirmIndex
- SELECT CPA_NAME,CPAFirmName,a.id AccountID, CPAFirmIndex
- into #Round19
- FROM
- [fp&a]..CPAMatch cm
- JOIN
- SalesforceClone..account a on REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(cm.CPA_NAME,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ') like '%' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(a.name,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ') + '%'
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
- WHERE
- CPA_NAME not in ('Bbs','Cla Financial Advisors, Llc','Clarke, Snow & Riley','Cpa Template','Hassan Cpa','Dean Dorton Allen Ford Pllc','Riitters Thompson & Olson PA') AND
- CPAFirmName not in ('CLA','CEA LLP','Freyberg Hinkle Ashland Powers & Stowell, SC','Anders','CBIZ','MPM, CPA'+char(39)+'s','Ssa PC','MSPC CPAs & Advisors, P. C.','Anders','AGN','ELO (FKA Endorf Lurken Olson & Co CPA LLC)','Main Amundson and Associates','C&D LLP (fka: Christensen & Drake)','PKF (FKA Batchelor, Frechette, Mc Crory, & Michael)','Smith Linden & Basso LLP','Tys') AND
- CPA_NAME NOT IN (
- SELECT CPA_NAME
- FROM
- #Round1
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round2
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round3
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round4
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round5
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round6
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round7
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round8
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round9
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round10
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round11
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round12
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round13
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round14
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round15
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round16
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round17
- UNION ALL
- SELECT CPA_NAME
- FROM
- #Round18)
- GROUP BY CPA_NAME,CPAFirmName,a.id , CPAFirmIndex
- */
- drop table if exists #Cpam
- /*
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS CPAFirmName,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS AccountID, CPAFirmIndex
- into #cpam
- FROM
- #Round1
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round2
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round3
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round4
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round5
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round6
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round7
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round8
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round9
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round10
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round11
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round12
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round13
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round14
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round15
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round16
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round17
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round18
- UNION ALL
- SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
- FROM
- #Round19
- */
- drop table if exists #Round0;
- drop table if exists #acc;
- SELECT CPA_NAME,CPAFirmName, AccountID, CPAFirmIndex
- into #Round0
- FROM
- (
- SELECT CPA_NAME,CPAFirmName,a.id AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn
- FROM
- [FP&A]..CPAMatch CM
- JOIN
- SalesforceClone..Account a on a.Name = CM.CPA_NAME
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
- LEFT JOIN
- (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- GROUP BY CPAFirm
- ) MCF on MCF.CPAFirm = CF.CPAFirmIndex
- ) a WHERE rn = 1
- GROUP BY CPA_NAME,CPAFirmName,AccountID , CPAFirmIndex
- INSERT INTO #Round0
- SELECT CPA_NAME,CPAFirmName,AccountID AccountID, CPAFirmIndex
- FROM
- (
- SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn
- FROM
- [FP&A]..CPAMatch CM
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS = cm.CPA_NAME
- LEFT JOIN
- (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- GROUP BY CPAFirm
- ) MCF on MCF.CPAFirm = CF.CPAFirmIndex
- WHERE AccountID is not null
- ) a WHERE rn = 1
- AND
- CPA_NAME NOT IN (
- SELECT CPA_NAME
- FROM
- #Round0)
- GROUP BY CPA_NAME,CPAFirmName,AccountID , CPAFirmIndex
- SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(a.name,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ') name,id
- INTO #acc
- FROM SalesforceClone..account a
- INSERT INTO #Round0
- SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex
- FROM
- (
- SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn
- FROM
- (SELECT * FROM
- [fp&a]..CPAMatch cm
- WHERE
- CPA_NAME NOT IN ('Null','Bbs','Hlb Usa','Agh, Llc','agn','Anders','Rost & Co., Cpas, P.C.','J&J Cpas','Braver Pc','Fisher, P.C.','Business Solutions, Llc','Campbell','Cohen & Company','Fisher, P.C.','Lk & Associates','Miller & Co., Plc','Ssa, P.C.','Family Farms') AND
- CPA_NAME NOT IN (
- SELECT CPA_NAME
- FROM
- #Round0))cm
- JOIN
- #acc a on name like '%' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(cm.CPA_NAME,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ') + '%'
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
- LEFT JOIN
- (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- GROUP BY CPAFirm
- ) MCF on MCF.CPAFirm = CF.CPAFirmIndex
- WHERE AccountID is not null
- AND
- CPAFirmName NOT IN ('Boas & Boas LLP','Landucci, Bick, Matter & Johnston LLP','Mullen Howard Hammatt & Co PA','Lublin Sussman Group LLP','Don Friedman','Bohlmann Accounting Group PLLC','Baden Gage & Schroeder LLC - Dupe2','Sharrard McGee & Co','Travis Wolff & Co.','CDPA','MSPC CPAs & Advisors, P. C.')
- ) a WHERE rn = 1
- GROUP BY CPA_NAME,CPAFirmName,AccountID , CPAFirmIndex
- INSERT INTO #Round0
- SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex
- FROM
- (
- SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn
- FROM
- (SELECT * FROM
- [fp&a]..CPAMatch cm
- WHERE
- CPA_NAME NOT IN ('Null','Bbs','Hlb Usa','Agh, Llc','agn','Anders','Rost & Co., Cpas, P.C.','J&J Cpas','Braver Pc','Fisher, P.C.','Business Solutions, Llc','Campbell','Cohen & Company','Fisher, P.C.','Lk & Associates','Miller & Co., Plc','Ssa, P.C.','Family Farms') AND
- CPA_NAME NOT IN (
- SELECT CPA_NAME
- FROM
- #Round0))cm
- JOIN
- #acc a on REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(cm.CPA_NAME,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ') like '%' + name + '%'
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
- LEFT JOIN
- (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- GROUP BY CPAFirm
- ) MCF on MCF.CPAFirm = CF.CPAFirmIndex
- WHERE AccountID is not null
- AND
- CPAFirmName NOT IN ('Boas & Boas LLP','Landucci, Bick, Matter & Johnston LLP','Mullen Howard Hammatt & Co PA','Lublin Sussman Group LLP','Don Friedman','Bohlmann Accounting Group PLLC','Baden Gage & Schroeder LLC - Dupe2','Sharrard McGee & Co','Travis Wolff & Co.','CDPA','MSPC CPAs & Advisors, P. C.')
- ) a WHERE rn = 1
- GROUP BY CPA_NAME,CPAFirmName,AccountID , CPAFirmIndex
- SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(a.CPAFirmName,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ') name,CPAFirmIndex,AccountID
- INTO #acc3e
- FROM TE_3E_PROD_Clone..AG_CPAFirm a
- INSERT INTO #Round0
- SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex
- FROM
- (
- SELECT CPA_NAME,name CPAFirmName,AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn
- FROM
- (SELECT * FROM
- [fp&a]..CPAMatch cm
- WHERE
- CPA_NAME NOT IN ('Null','Bbs','Hlb Usa','Agh, Llc','agn','Anders','Rost & Co., Cpas, P.C.','J&J Cpas','Braver Pc','Fisher, P.C.','Business Solutions, Llc','Campbell','Cohen & Company','Fisher, P.C.','Lk & Associates','Miller & Co., Plc','Ssa, P.C.','Family Farms') AND
- CPA_NAME NOT IN (
- SELECT CPA_NAME
- FROM
- #Round0))cm
- JOIN
- #acc3e a on REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(cm.CPA_NAME COLLATE SQL_Latin1_General_CP1_CI_AS,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ') like '%' + name + '%'
- LEFT JOIN
- (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- GROUP BY CPAFirm
- ) MCF on MCF.CPAFirm = a.CPAFirmIndex
- WHERE AccountID is not null
- AND
- name COLLATE SQL_Latin1_General_CP1_CI_AS NOT IN ('MBE','RKE','Boas & Boas LLP','Landucci, Bick, Matter & Johnston LLP','Mullen Howard Hammatt & Co PA','Lublin Sussman Group LLP','Don Friedman','Bohlmann Accounting Group PLLC','Baden Gage & Schroeder LLC - Dupe2','Sharrard McGee & Co','Travis Wolff & Co.','CDPA','MSPC CPAs & Advisors, P. C.')
- ) a WHERE rn = 1
- GROUP BY CPA_NAME,CPAFirmName,AccountID , CPAFirmIndex
- INSERT INTO #Round0
- SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex
- FROM
- (
- SELECT CPA_NAME,name CPAFirmName,AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn
- FROM
- (SELECT * FROM
- [fp&a]..CPAMatch cm
- WHERE
- CPA_NAME NOT IN ('Null','Bbs','Hlb Usa','Agh, Llc','agn','Anders','Rost & Co., Cpas, P.C.','J&J Cpas','Braver Pc','Fisher, P.C.','Business Solutions, Llc','Campbell','Cohen & Company','Fisher, P.C.','Lk & Associates','Miller & Co., Plc','Ssa, P.C.','Family Farms') AND
- CPA_NAME NOT IN (
- SELECT CPA_NAME
- FROM
- #Round0))cm
- JOIN
- #acc3e a on name like '%' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(cm.CPA_NAME COLLATE SQL_Latin1_General_CP1_CI_AS,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'Company','Co'),' Cpas',''),' LLC',''),' PC',''),' P C',''),' PLC',''),char(39)+'s','') ,' ',' ') + '%'
- LEFT JOIN
- (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- GROUP BY CPAFirm
- ) MCF on MCF.CPAFirm = a.CPAFirmIndex
- WHERE AccountID is not null
- AND
- name COLLATE SQL_Latin1_General_CP1_CI_AS NOT IN ('MBE','RKE','Boas & Boas LLP','Landucci, Bick, Matter & Johnston LLP','Mullen Howard Hammatt & Co PA','Lublin Sussman Group LLP','Don Friedman','Bohlmann Accounting Group PLLC','Baden Gage & Schroeder LLC - Dupe2','Sharrard McGee & Co','Travis Wolff & Co.','CDPA','MSPC CPAs & Advisors, P. C.')
- ) a WHERE rn = 1
- GROUP BY CPA_NAME,CPAFirmName,AccountID , CPAFirmIndex
- INSERT INTO #Round0
- SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex-- ,a2.name--,MatterNUmber
- FROM
- (
- SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn,MatterNUmber
- FROM
- (SELECT CPA_NAME,MatterNUmber FROM
- [fp&a]..CPAMatch CM
- where
- CPA_NAME NOT IN (SELECT CPA_NAME
- FROM
- #Round0) AND
- ARMIndex IN (
- SELECT ARMIndex
- FROM
- [fp&a]..CPAMatch
- GROUP BY ARMIndex
- HAVING COUNT(ARMIndex) = 1 AND SUM(COALESCE(TRY_CAST(AMOUNTDUETOCPA as numeric),0))>0)
- GROUP BY CPA_NAME,MatterNUmber
- ) CM
- JOIN
- TE_3E_PROD_Clone..Matter M on M.NUmber COLLATE SQL_Latin1_General_CP1_CI_AS = CM.MatterNUmber
- JOIN
- (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- GROUP BY MatterLkup
- HAVING COUNT(DISTINCT CPAFirm)=1
- )
- MCF on MCF.MatterLkup = M.MattINdex
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
- LEFT JOIN
- (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- GROUP BY CPAFirm
- ) MCF2 on MCF.CPAFirm = CF.CPAFirmIndex
- WHERE AccountID is not null
- ) a
- JOIN
- SalesForceClone..account a2 on a2.id = a.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS
- WHERE rn = 1
- GROUP BY
- CPA_NAME,CPAFirmName,AccountID,CPAFirmIndex--,a2.name--,MatterNUmber
- INSERT INTO #Round0
- SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex-- ,a2.name--,MatterNUmber
- FROM
- (
- SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn,MatterNUmber
- FROM
- (SELECT CPA_NAME,MatterNUmber FROM
- [fp&a]..CPAMatch CM
- where
- CPA_NAME NOT IN (SELECT CPA_NAME
- FROM
- #Round0) AND
- ARMIndex IN (
- SELECT ARMIndex
- FROM
- [fp&a]..CPAMatch
- GROUP BY ARMIndex
- HAVING COUNT(ARMIndex) = 1 )
- GROUP BY CPA_NAME,MatterNUmber
- ) CM
- JOIN
- TE_3E_PROD_Clone..Matter M on M.NUmber COLLATE SQL_Latin1_General_CP1_CI_AS = CM.MatterNUmber
- JOIN
- (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- GROUP BY MatterLkup
- HAVING COUNT(DISTINCT CPAFirm)=1
- )
- MCF on MCF.MatterLkup = M.MattINdex
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
- LEFT JOIN
- (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- GROUP BY CPAFirm
- ) MCF2 on MCF.CPAFirm = CF.CPAFirmIndex
- WHERE AccountID is not null
- ) a
- JOIN
- SalesForceClone..account a2 on a2.id = a.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS
- WHERE rn = 1
- GROUP BY
- CPA_NAME,CPAFirmName,AccountID,CPAFirmIndex--,a2.name--,MatterNUmber
- INSERT INTO #Round0
- SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex-- ,a2.name--,MatterNUmber
- FROM
- (
- SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn,MatterNUmber
- FROM
- (SELECT CPA_NAME,MatterNUmber FROM
- [fp&a]..CPAMatch CM
- where
- CPA_NAME NOT IN (SELECT CPA_NAME
- FROM
- #Round0) AND
- ARMIndex IN (
- SELECT ARMIndex
- FROM
- [fp&a]..CPAMatch
- where
- CPA_NAME NOT IN (SELECT CPA_NAME
- FROM
- #Round0)
- GROUP BY ARMIndex
- HAVING COUNT(ARMIndex) = 1 )
- GROUP BY CPA_NAME,MatterNUmber
- ) CM
- JOIN
- TE_3E_PROD_Clone..Matter M on M.NUmber COLLATE SQL_Latin1_General_CP1_CI_AS = CM.MatterNUmber
- JOIN
- (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- where
- CPAFirm NOT IN (SELECT CPAFirmIndex
- FROM
- #Round0)
- GROUP BY MatterLkup
- HAVING COUNT(DISTINCT CPAFirm)=1
- )
- MCF on MCF.MatterLkup = M.MattINdex
- JOIN
- TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
- LEFT JOIN
- (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
- FROM
- TE_3E_PROD_Clone..AG_MattCPAFirm
- GROUP BY CPAFirm
- ) MCF2 on MCF.CPAFirm = CF.CPAFirmIndex
- WHERE AccountID is not null
- ) a
- JOIN
- SalesForceClone..account a2 on a2.id = a.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS
- WHERE rn = 1
- GROUP BY
- CPA_NAME,CPAFirmName,AccountID,CPAFirmIndex--,a2.name--,MatterNUmber
- SELECT CPA_NAME, CPAFirmName, AccountID, CPAFirmIndex
- into #cpam
- FROM
- #Round0
- --SELECT *
- --FROM
- --#cpam
- drop table if exists #cpahm;
- select
- c.*
- --, cpa1.[Type] [CPA1_Type]
- --, cpa1.[ParentId] [CPA1_ParentId]
- --, cpa1.CreatedDate [CPA1_CreatedDate]
- , coalesce(cpa4.[Id], cpa3.[Id], cpa2.[Id], cpa1.[Id]) [CPATop_AccountId]
- , coalesce(cpa4.[Name], cpa3.[Name], cpa2.[Name], cpa1.[Name]) [CPATop_Name]
- --, cpa2.[Id] [CPA2_AccountId]
- --, cpa2.[Name] [CPA2_Name]
- --, cpa2.[ParentId] [CPA2_ParentId]
- --, cpa3.[Id] [CPA3_AccountId]
- --, cpa3.[Name] [CPA3_Name]
- --, cpa3.[ParentId] [CPA3_ParentId]
- --, cpa4.[Id] [CPA4_AccountId]
- --, cpa4.[Name] [CPA4_Name]
- --, cpa4.[ParentId] [CPA4_ParentId]
- into #cpahm
- from
- #cpam c
- left join
- SalesForceClone.dbo.Account cpa1 on cpa1.[Id] = c.AccountID
- left join
- SalesForceClone.dbo.Account cpa2 on cpa2.[Id] = cpa1.[ParentId]
- left join
- SalesForceClone.dbo.Account cpa3 on cpa3.[Id] = cpa2.[ParentId]
- left join
- SalesForceClone.dbo.Account cpa4 on cpa4.id = cpa3.ParentId
- drop table if exists #cpa;
- select
- a.[CPAId]
- , a.[CPAName]
- into #cpa
- from
- (
- select
- o.Referring_CPA_Firm_ID__c [CPAId]
- , o.CPA_Referral_Firm__c [CPAName]
- from
- SalesForceClone.dbo.Opportunity o
- where
- StageName like '%closed%'
- and o.Referring_CPA_Firm_ID__c is not null
- group by
- o.Referring_CPA_Firm_ID__c
- , o.CPA_Referral_Firm__c
- union all
- select
- o.Amending_CPA_Firm_ID__c [CPAId]
- , o.Amending_CPA_Firm__c [CPAName]
- from
- SalesForceClone.dbo.Opportunity o
- where
- StageName like '%closed%'
- and o.Amending_CPA_Firm_ID__c is not null
- group by
- o.Amending_CPA_Firm_ID__c
- , o.Amending_CPA_Firm__c
- union all
- select
- cpa.Id [CPAId]
- , cpa.[Name] [CPAName]
- from
- SalesForceClone.dbo.Opportunity o
- left join
- SalesForceClone.dbo.Account a on a.id = o.AccountId
- left join
- SalesForceClone.dbo.Account cpa on cpa.id = a.CPA_Account__c
- where
- o.StageName like '%closed%'
- and cpa.Id is not null
- group by
- cpa.Id
- , cpa.[Name]
- ) a
- group by
- [CPAId]
- , [CPAName]
- drop table if exists #cpah;
- select
- c.[CPAId] [CPA1_AccountId]
- , c.[CPAName] [CPA1_Name]
- , cpa1.[Type] [CPA1_Type]
- , cpa1.[ParentId] [CPA1_ParentId]
- , cpa1.CreatedDate [CPA1_CreatedDate]
- , coalesce(cpa4.[Id], cpa3.[Id], cpa2.[Id], cpa1.[Id]) [CPATop_AccountId]
- , coalesce(cpa4.[Name], cpa3.[Name], cpa2.[Name], cpa1.[Name]) [CPATop_Name]
- , cpa2.[Id] [CPA2_AccountId]
- , cpa2.[Name] [CPA2_Name]
- , cpa2.[ParentId] [CPA2_ParentId]
- , cpa3.[Id] [CPA3_AccountId]
- , cpa3.[Name] [CPA3_Name]
- , cpa3.[ParentId] [CPA3_ParentId]
- , cpa4.[Id] [CPA4_AccountId]
- , cpa4.[Name] [CPA4_Name]
- , cpa4.[ParentId] [CPA4_ParentId]
- into #cpah
- from
- #cpa c
- left join
- SalesForceClone.dbo.Account cpa1 on cpa1.[Id] = c.[CPAId]
- left join
- SalesForceClone.dbo.Account cpa2 on cpa2.[Id] = cpa1.[ParentId]
- left join
- SalesForceClone.dbo.Account cpa3 on cpa3.[Id] = cpa2.[ParentId]
- left join
- SalesForceClone.dbo.Account cpa4 on cpa4.id = cpa3.ParentId
- --SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
- drop table if exists #Base;
- SELECT CPAMatchId,
- CPA_NAME
- , CM.Client,
- CASE WHEN PAIDINFULL ='0' THEN NULL ELSE PAIDINFULL END [Client Paid In Full], CM.INVOICENUMBER,
- CASE WHEN (INVOICEDATE='1/0/1900' OR INVOICEDATE='0') THEN '' ELSE FORMAT(try_convert(DATE, INVOICEDATE), 'MM/dd/yyyy') END [Invoice Date],
- try_convert(DECIMAL(15,2),CASE WHEN INVOICEAMOUNT='0' THEN '' WHEN ROW_NUMBER()OVER(Partition By CM.INVOICENUMBER,CM.Client ORDER BY CM.ARMIndex) != 1 AND CM.ARMIndex != -1 THEN '0' ELSE INVOICEAMOUNT END) [Invoice Amount],
- try_convert(DECIMAL(15,2),CASE WHEN AMOUNTPAID is null THEN '0' ELSE AMOUNTPAID END) [Amount Paid],
- try_convert(DECIMAL(15,2),CASE WHEN EXPENSES IS NULL THEN '0' ELSE EXPENSES END) [Expenses],
- try_convert(DECIMAL(15,2),CASE WHEN AMOUNTPAIDLESSEXPENSES IS NULL THEN '0' ELSE AMOUNTPAIDLESSEXPENSES END) [Amount Paid Less Expenses],
- try_convert(Decimal(15,2),CASE WHEN AMOUNTDUETOCPA IS NULL OR (TRY_CAST(AMOUNTDUETOCPA as decimal(15,2))>2000000000000 AND AMOUNTPAID = '0') THEN '0' ELSE AMOUNTDUETOCPA END) [Amount Due To CPA],
- try_convert(DECIMAL(15,2),CASE WHEN AMOUNTPAIDTOCPA = '0' OR (TRY_CAST(AMOUNTDUETOCPA as decimal(15,2))>2000000000000 AND AMOUNTPAID = '0') THEN NULL ELSE AMOUNTPAIDTOCPA END) [Amount Paid To CPA],
- CASE WHEN (DATEPAIDTOCPA='1/0/1900' OR DATEPAIDTOCPA='0') THEN '' ELSE FORMAT(try_convert(DATE, DATEPAIDTOCPA), 'MM/dd/yyyy') END [Date Paid],
- try_convert(Decimal(15,2), REMAININGDUETOCPA ) [Remaining Amount Due to CPA]
- ,CASE
- WHEN MAX(NULLIF(COALESCE(CASE WHEN nord.Mattindex is null and COALESCE(CM.ARMIndex,-1) != -1 THEN 225 END, MD.PG2,C.PG2,C2.PG2,-1),-1))OVER(PARTITION BY CPA_NAME)
- = MIN(NULLIF(COALESCE(CASE WHEN nord.Mattindex is null and COALESCE(CM.ARMIndex,-1) != -1 THEN 225 END, MD.PG2,C.PG2,C2.PG2,-1),-1))OVER(PARTITION BY CPA_NAME) THEN
- MAX(NULLIF(COALESCE(CASE WHEN nord.Mattindex is null and COALESCE(CM.ARMIndex,-1) != -1 THEN 225 END, MD.PG2,C.PG2,C2.PG2,-1),-1))OVER(PARTITION BY CPA_NAME)
- WHEN MAX(NULLIF(COALESCE(CASE WHEN nord.Mattindex is null and COALESCE(CM.ARMIndex,-1) != -1 THEN 225 END, MD.PG2,C.PG2,C2.PG2,-1),-1))OVER(PARTITION BY CPA_NAME,CM.Client)
- = MIN(NULLIF(COALESCE(CASE WHEN nord.Mattindex is null and COALESCE(CM.ARMIndex,-1) != -1 THEN 225 END, MD.PG2,C.PG2,C2.PG2,-1),-1))OVER(PARTITION BY CPA_NAME,CM.Client) THEN
- MAX(NULLIF(COALESCE(CASE WHEN nord.Mattindex is null and COALESCE(CM.ARMIndex,-1) != -1 THEN 225 END, MD.PG2,C.PG2,C2.PG2,-1),-1))OVER(PARTITION BY CPA_NAME,CM.Client)
- ELSE COALESCE(CASE WHEN nord.Mattindex is null and COALESCE(CM.ARMIndex,-1) != -1 THEN 225 END, MD.PG2,C.PG2,C2.PG2,-1)
- END
- SL
- ,CM.MattCategory
- INTO #Base
- FROM [FP&A].dbo.CPAMatch CM
- LEFT JOIN
- TE_3E_PROD_Clone..ARMaster AM on AM.ARMIndex = CM.ARMIndex
- OUTER APPLY
- (SELECT TOP 1 MD.* ,CASE WHEN MattStatus in ('KO','TERM') AND PracticeGRoup = 225 THEN 110
- WHEN (pc.PGDetHdr is null OR FNDate >AM.InvDate) AND PracticeGRoup = 225 THEN 110
- ELSE PracticeGRoup END PG2,FnDate
- FROM
- TE_3E_PROD_Clone..MattDate MD
- JOIN
- TE_3E_PROD_Clone..Matter M on M.MattIndex = MD.Matterlkup
- JOIN
- TE_3E_PROD_Clone..PGDetHdr_CCC PH on PH.MatterLkUp = M.MattIndex --AND PH.NxEndDate = '99991231' AND PH.NxStartDate != '99991231'
- LEFT JOIN
- (SELECT PGDetHdr,MIN(FNDATE) FnDate FROM TE_3E_PROD_Clone..PGDetChild_CCC PC WHERE TriggerType = 'FN' GROUP BY PGDetHdr) PC on PC.PGDetHdr = PH.PGDetHdr_CCCID
- WHERE MD.MatterLkUp = AM.Matter and MD.NxEndDate = '99991231' --and MD.PracticeGroup IN (@PG)
- ORDER by MD.NxStartDate,COALESCE(FnDate,GETDATE())) MD
- OUTER APPLY
- (SELECT TOP 1 MD.*,CASE WHEN MattStatus in ('KO','TERM') AND PracticeGRoup = 225 THEN 110
- WHEN (pc.PGDetHdr is null OR FNDate >IM.InvDate) AND PracticeGRoup = 225 THEN 110
- ELSE PracticeGRoup END PG2
- FROM
- TE_3E_PROD_Clone..Payor P
- JOIN
- TE_3E_PROD_Clone..InvMaster IM on IM.DefPayor = P.PayorIndex
- JOIN
- TE_3E_PROD_Clone..ARMaster AM on AM.InvMaster = IM.InvIndex
- JOIN
- TE_3E_PROD_Clone..MattDate MD on MD.MatterLkUp = AM.Matter and NxEndDate = '99991231'
- JOIN
- TE_3E_PROD_Clone..Matter M on M.MattIndex = MD.Matterlkup
- JOIN
- TE_3E_PROD_Clone..PGDetHdr_CCC PH on PH.MatterLkUp = M.MattIndex --AND PH.NxEndDate = '99991231' AND PH.NxStartDate != '99991231'
- LEFT JOIN
- (SELECT PGDetHdr,MIN(FNDATE) FnDate FROM TE_3E_PROD_Clone..PGDetChild_CCC PC WHERE TriggerType = 'FN' GROUP BY PGDetHdr) PC on PC.PGDetHdr = PH.PGDetHdr_CCCID
- WHERE P.Entity = CM.[CLIENT ID] --and MD.PracticeGroup IN (@PG)
- ORDER BY CASE WHEN IM.InvDate = TRY_CAST(CM.INVOICEDATE as datetime) THEN 0 ELSE 1 END,ABS(CM.INVOICEAMOUNT + AM.ARAmt),COALESCE(FnDate,GETDATE())
- ) C
- OUTER APPLY
- (SELECT TOP 1 MD.*,CASE WHEN MattStatus in ('KO','TERM') AND PracticeGRoup = 225 THEN 110
- WHEN (pc.PGDetHdr is null OR FNDate >IM.InvDate) AND PracticeGRoup = 225 THEN 110
- ELSE PracticeGRoup END PG2
- FROM
- TE_3E_PROD_Clone..Payor P
- JOIN
- TE_3E_PROD_Clone..InvMaster IM on IM.DefPayor = P.PayorIndex
- JOIN
- TE_3E_PROD_Clone..ARMaster AM on AM.InvMaster = IM.InvIndex
- JOIN
- TE_3E_PROD_Clone..MattDate MD on MD.MatterLkUp = AM.Matter and NxEndDate = '99991231'
- JOIN
- TE_3E_PROD_Clone..Matter M on M.MattIndex = MD.Matterlkup
- JOIN
- TE_3E_PROD_Clone..PGDetHdr_CCC PH on PH.MatterLkUp = M.MattIndex --AND PH.NxEndDate = '99991231' AND PH.NxStartDate != '99991231'
- LEFT JOIN
- (SELECT PGDetHdr,MIN(FNDATE) FnDate FROM TE_3E_PROD_Clone..PGDetChild_CCC PC WHERE TriggerType = 'FN' GROUP BY PGDetHdr) PC on PC.PGDetHdr = PH.PGDetHdr_CCCID
- WHERE P.DisplayName COLLATE SQL_Latin1_General_CP1_CI_AS = CM.Client --and MD.PracticeGroup IN (@PG)
- ORDER BY CASE WHEN IM.InvDate = TRY_CAST(CM.INVOICEDATE as datetime) THEN 0 ELSE 1 END,ABS(CM.INVOICEAMOUNT + AM.ARAmt),COALESCE(FnDate,GETDATE())
- ) C2
- OUTER APPLY
- (SELECT TOP 1 mrd.* FROM TE_3E_PROD_Clone..Matter m
- JOIN
- TE_3E_PROD_Clone..Client c on c.ClientIndex = m.Client
- JOIN
- TE_3E_PROD_Clone..Matter mrd on mrd.client = c.ClientINdex
- JOIN
- TE_3E_PROD_Clone..MattDate MD on MD.Matterlkup = mrd.MattIndex AND NxEndDate = '99991231' and NxStartDate != '99991231' and PracticeGroup in (110,120,130)
- WHERE m.MattIndex = AM. Matter) nord
- where
- cpamatchid not in (select cpamatchid from [FP&A].dbo.CPAMatch where ARMIndex != -1 and isnull(trim(AMOUNTDUETOCPA),'0') = '0' and CPAMatchId is not null)
- --AND (COALESCE(CASE WHEN nord.Mattindex is null and COALESCE(CM.ARMIndex,-1) != -1 THEN 225 END, MD.PG2,C.PG2,C2.PG2,-1) IN (@PG))
- --AND CPA_NAME = @CPAParameter) IN (@PG))
- --AND CPA_NAME = 'Somerset Cpas'
- drop table if exists #SLD;
- SELECT *
- INTO #SLD
- FROM (
- SELECT CM.CPA_NAME
- ,CM.[Amount Paid To CPA]
- ,pg.Description SLD
- FROM
- (
- SELECT *
- FROM
- #Base) CM
- LEFT JOIN
- TE_3E_PROD_CLONE..PracticeGRoup pg on pg.code = CM.SL
- ) p PIVOT
- (SUM([AMount Paid To CPA]) FOR SLD IN ([R&D Services],[ERC Services],[179D Services])) p
- drop table if exists #SLO;
- SELECT CPA_NAME
- ,[R&D Services] [R&D Services OS]
- ,[ERC Services] [ERC Services OS]
- ,[179D Services] [179D Services OS]
- INTO #SLO
- FROM (
- SELECT CM.CPA_NAME
- ,CM.[Remaining Amount Due to CPA]
- ,pg.Description SLD
- FROM
- (
- SELECT *
- FROM
- #Base) CM
- LEFT JOIN
- TE_3E_PROD_CLONE..PracticeGRoup pg on pg.code = CM.SL
- ) p PIVOT
- (SUM([Remaining Amount Due to CPA]) FOR SLD IN ([R&D Services],[ERC Services],[179D Services])) p
- drop table if exists #FAAmts;
- SELECT
- [CPATop_AccountId]
- , [CPATop_Name]
- , SUM(ClientPaidLessExpenses) ClientPaidLessExpenses
- , SUM(AMountDueToCPA)AMountDueToCPA
- , SUM(AmountPaidToCPA) AmountPaidToCPA
- , SUM([R&D Services]) [R&D Services]
- , SUM([ERC Services])[ERC Services]
- , SUM([Other Services])[Other Services]
- , SUM(AmountOutStandingToCPA) AmountOutStandingToCPA
- , SUM([R&D Services OS]) [R&D Services OS]
- , SUM([ERC Services OS])[ERC Services OS]
- , SUM([Other Services OS])[Other Services OS]
- , SUM(ERCClientPaid)ERCClientPaid
- INTO #FAAmts
- FROM
- (
- SELECT a.*
- , [CPATop_AccountId]
- , [CPATop_Name]
- ,ROW_NUMBER()OVER(PArtition by a.CPA_Name ORDER BY DIFFERENCE(a.CPA_NAME,CPATop_Name) desc) rn
- FROM
- (
- SELECT
- a.CPA_Name
- , State
- , COUNT(Distinct a.Client) NbrClients
- , SUM(TRY_CAST(InvoiceAmount as numeric(12,2))) ClientInvoices
- , SUM(TRY_CAST(AMOUNTPAIDLESSEXPENSES as numeric(12,2))) ClientPaidLessExpenses
- , SUM(TRY_CAST(AMOUNTDUETOCPA as numeric(12,2))) AMountDueToCPA
- , SUM(TRY_CAST(AMOUNTPAIDTOCPA as numeric(12,2))) AmountPaidToCPA
- , CASE WHEN [ERC Services] is null AND [179D Services] is null AND [R&D Services]>SUM(TRY_CAST(AMOUNTPAIDTOCPA as numeric(12,2))) THEN SUM(TRY_CAST(AMOUNTPAIDTOCPA as numeric(12,2))) ELSE ([R&D Services]) END [R&D Services]
- , CASE WHEN [R&D Services] is null AND [179D Services] is null AND [ERC Services]>SUM(TRY_CAST(AMOUNTPAIDTOCPA as numeric(12,2))) THEN SUM(TRY_CAST(AMOUNTPAIDTOCPA as numeric(12,2))) ELSE ([ERC Services]) END [ERC Services]
- , COALESCE(SUM(TRY_CAST(AMOUNTPAIDTOCPA as numeric(12,2))),0)
- -(COALESCE(CASE WHEN [ERC Services] is null AND [179D Services] is null AND [R&D Services]>SUM(TRY_CAST(AMOUNTPAIDTOCPA as numeric(12,2))) THEN SUM(TRY_CAST(AMOUNTPAIDTOCPA as numeric(12,2))) ELSE ([R&D Services]) END,0))
- -(COALESCE(CASE WHEN [R&D Services] is null AND [179D Services] is null AND [ERC Services]>SUM(TRY_CAST(AMOUNTPAIDTOCPA as numeric(12,2))) THEN SUM(TRY_CAST(AMOUNTPAIDTOCPA as numeric(12,2))) ELSE ([ERC Services]) END,0))
- [Other Services]
- , CASE WHEN [ERC Services OS] is null AND [179D Services OS] is null AND [R&D Services OS]>SUM(TRY_CAST(REMAININGDUETOCPA as numeric(12,2))) THEN SUM(TRY_CAST(REMAININGDUETOCPA as numeric(12,2))) ELSE ([R&D Services OS]) END [R&D Services OS]
- , CASE WHEN [R&D Services OS] is null AND [179D Services OS] is null AND [ERC Services OS]>SUM(TRY_CAST(REMAININGDUETOCPA as numeric(12,2))) THEN SUM(TRY_CAST(REMAININGDUETOCPA as numeric(12,2))) ELSE ([ERC Services OS]) END [ERC Services OS]
- , COALESCE(SUM(TRY_CAST(REMAININGDUETOCPA as numeric(12,2))),0)
- -(COALESCE(CASE WHEN [ERC Services OS] is null AND [179D Services OS] is null AND [R&D Services OS]>SUM(TRY_CAST(REMAININGDUETOCPA as numeric(12,2))) THEN SUM(TRY_CAST(REMAININGDUETOCPA as numeric(12,2))) ELSE ([R&D Services OS]) END,0))
- -(COALESCE(CASE WHEN [R&D Services OS] is null AND [179D Services OS] is null AND [ERC Services OS]>SUM(TRY_CAST(REMAININGDUETOCPA as numeric(12,2))) THEN SUM(TRY_CAST(REMAININGDUETOCPA as numeric(12,2))) ELSE ([ERC Services OS]) END,0))
- [Other Services OS]
- , SUM(TRY_CAST(REMAININGDUETOCPA as numeric(12,2))) AmountOutStandingToCPA
- , COUNT(DISTINCT CASE WHEN COALESCE([ERC Services],0) + COALESCE([ERC Services OS],0)>0 THEN Client END) ERCClientPaid
- FROM (
- SELECT Distinct CM.*,COALESCE(MAX(a2.BillingState)OVER(Partition By CPA_Name),MAX(NBP.CPAState)OVER(Partition By CPA_Name),MAX(NBF.CPAState)OVER(Partition By CPA_Name),MAX(a.BillingState)OVER(Partition By CPA_Name),MAX(ad.State COLLATE SQL_Latin1_General_CP1_CI_AS)OVER(Partition By CPA_Name)) State
- FROM
- [FP&A]..CPAMatch CM
- LEFT JOIN
- (SELECT CPAEntity,CPAFirm
- FROM
- TE_3E_PROD_Clone..CPADetails_CCC
- GROUP BY CPAEntity,CPAFirm)
- cd on cd.CPAEntity = CM.CPAID
- LEFT JOIN
- SalesforceClone..account a on a.Name = cd.CPAFirm COLLATE SQL_Latin1_General_CP1_CI_AS
- LEFT JOIN
- TE_3E_PROD_Clone..Payee P on P.NAme COLLATE SQL_Latin1_General_CP1_CI_AS = CM.CPA_NAME
- LEFT JOIN
- TE_3E_PROD_Clone..Site s on s.SiteIndex = P.CkSite
- LEFT JOIN
- TE_3E_PROD_Clone..Address ad on ad.AddrIndex = s.Address
- LEFT JOIN
- (SELECT CPAFirm,CPAState
- FROM
- TE_3E_PROD_Clone.[dbo].[NBI_Import_CPADetails_CCC]
- GROUP BY CPAFirm,CPAState) NBF on NBF.CPAFirm = cd.CPAFirm
- LEFT JOIN
- TE_3E_PROD_Clone..Entity e on e.EntIndex = CM.CPAID
- LEFT JOIN
- (SELECT CPAName,CPAState
- FROM
- TE_3E_PROD_Clone.[dbo].[NBI_Import_CPADetails_CCC]
- GROUP BY CPAName,CPAState
- ) NBP on NBP.CPAName = e.DisplayName
- LEFT JOIN
- TE_3E_PROD_Clone.[dbo].[AG_CPAFirm] cf on cf.CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS = CM.CPA_NAME
- LEFT JOIN
- SalesforceClone..account a2 on a2.id = cf.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS
- ) a
- LEFT JOIN
- #SLD SL on SL.CPA_NAME = a.CPA_NAME
- LEFT JOIN
- #SLO SO on SO.CPA_NAME = a.CPA_NAME
- GROUP BY
- a.CPA_Name
- , State
- , ([R&D Services])
- , ([ERC Services])
- , [179D Services]
- , ([R&D Services OS])
- , ([ERC Services OS])
- , [179D Services OS]
- ) a
- JOIN
- #cpahm chm on chm.CPA_NAme = a.CPA_NAME
- )b
- WHERE rn = 1
- GROUP BY
- [CPATop_AccountId]
- , [CPATop_Name]
- drop table if exists #cpafinal;
- select
- o.Id [OpportunityId]
- , a.id [AccountId]
- , a.[Name] [AccountName]
- , c.CPA1_AccountId [CPAAccountId]
- , c.CPATop_Name [CPAName]
- , c.[CPATop_AccountId] [CPATop_AccountId]
- , con.[Name] [CPAContact]
- into #cpafinal
- from
- SalesForceClone.dbo.Account a
- left join
- SalesForceClone.dbo.Contact con on con.Id = a.CPA_Contact__c
- join
- SalesforceClone.dbo.Opportunity o on o.AccountId = a.Id
- left join
- #cpah c on c.CPA1_AccountId = COALESCE(a.CPA_Account__c,o.Amending_CPA_Firm_ID__c ,o.Referring_CPA_Firm_ID__c)
- group by
- o.Id
- , a.id
- , a.[Name]
- , c.CPA1_AccountId
- , c.CPATop_Name
- , con.[Name]
- , c.[CPATop_AccountId]
- drop table if exists #IsTalent;
- SELECT AccountId
- , CASE WHEN Service_Type__c IN ('External Audit','Tax Services','AMS','Business Advisory & Valuation') THEN 1 ELSE 0 END IsTalent
- into #IsTalent
- FROM
- SalesforceClone.dbo.Opportunity
- WHERE
- Service_Type__c IN ('External Audit','Tax Services','AMS','Business Advisory & Valuation')
- GROUP BY
- AccountId
- , CASE WHEN Service_Type__c IN ('External Audit','Tax Services','AMS','Business Advisory & Valuation') THEN 1 ELSE 0 END
- drop table if exists #Credits;
- select
- m.[MattIndex]
- , m.[Number] [Job_No]
- , m.OpportunityID_CCC [OpportunityId]
- , c.AccountID_CCC [AccountId]
- , m.[DisplayName] [Description]
- , m.[Client]
- , c.[DisplayName] [Company]
- , s.[Code] [State]
- , m.[EngSignedDate_CCC] [DateSigned]
- , year(m.[EngSignedDate_CCC]) [Year]
- , replace(ms.[Description],'CLOSING','Closing') [Status]
- , md.[Description] SL
- , case
- when m.MattCategory = 'NEW' then 'New'
- when m.MattCategory = 'FU' then 'FU'
- when et.[Description] = 'New Business' then 'New'
- when et.[Description] = 'Follow - Up' then 'FU'
- when et.[Description] = 'Continuation' then 'Continuation'
- end [New_FU]
- , isnull ( coalesce(pc.[FinalCredits],0), 0) [FinalCredit]
- , Coalesce(pc.[Total],0) [Total]
- , case when md.[PracticeGroup] = 225 then coalesce(pc.[FinalCredits],0) else Coalesce(pc.[Total],0) end [Total2]
- , atk.[BD1] [PBD]
- , CASE WHEN BDMC.[MattIndex] is not null then 1 else 0 end [StudyCount]
- , cpa.[CPAAccountId]
- , coalesce(cpa.[CPAName],'Direct') [CPA]
- , cpa.[CPAContact] [CPA_Contact]
- , case when md.[PracticeGroup] = 225 then 1 else 0 end [isERC]
- , case when pc.[FinalCredits]!= 0 then 1 else pc.[FinalCredits] end isFinalCredits
- , CASE WHEN BDM.[MattIndex] is not null then AdjustedWIP else 0 end AdjWIP
- , SUM(CASE WHEN BDM.[MattIndex] is not null then AdjustedWIP else 0 end)OVER(Partition BY m.[Client]) ClientTotalWIP
- , [CPATop_AccountId]
- into #Credits
- from
- TE_3E_PROD_Clone.dbo.Matter m
- LEFT JOIN
- (SELECT BDM.[MattIndex],SUM(AdjustedWIP)AdjustedWIP,OpportunityIDCCC
- FROM
- [FP&A].BDM.BDMasterUnpublished BDM
- WHERE
- BDM.[EngTypeCCC] = 'New'
- GROUP BY BDM.[MattIndex],OpportunityIDCCC) BDM on BDM.[MattIndex] = m.Mattindex
- LEFT JOIN
- (SELECT BDM.[MattIndex],OpportunityIDCCC
- FROM
- [FP&A].BDM.BDMasterUnpublished BDM
- WHERE
- BDM.[EngTypeCCC] = 'New' and BDM.OneTimeAdj = '0'
- GROUP BY BDM.[MattIndex],OpportunityIDCCC) BDMC on BDMC.[MattIndex] = m.Mattindex
- join
- TE_3E_PROD_Clone.dbo.Client c on c.ClientIndex = m.Client
- left join
- TE_3E_PROD_Clone.[dbo].[Site] si on si.[SiteIndex] = c.[InvoiceSite]
- left join
- TE_3E_PROD_Clone.[dbo].[Address] a on si.[Address] = a.[AddrIndex]
- left join
- TE_3E_PROD_Clone.[dbo].[State] s on a.[State] = s.[Code]
- join
- TE_3E_PROD_Clone.dbo.MattStatus ms on ms.code = m.MattStatus
- left join
- TE_3E_PROD_Clone.[dbo].[EngType_CCC] et on et.[Code] = m.[EngType_CCC]
- left join
- (
- select
- row_number() over(partition by MatterLkUp order by effstart desc, nxStartDate desc, nxEndDate desc) [Rn]
- , PGDetHdr_CCCID
- , MatterLkUp
- , AdjWIP
- from
- TE_3E_PROD_Clone.dbo.PGDetHdr_CCC
- ) ph on ph.MatterLkUp = m.MattIndex and ph.[Rn] = 1
- left join
- (
- select
- PGDetHdr
- , sum([FinalCredit]) [FinalCredits]
- , sum([Total]) [Total]
- from
- TE_3E_PROD_Clone.dbo.PGDetChild_CCC
- group by
- PGDetHdr
- ) pc on pc.PGDetHdr = ph.PGDetHdr_CCCID
- left join
- (
- select
- row_number() over(partition by md.MatterLkUp order by md.effstart desc, md.nxStartDate desc, md.nxEndDate desc) [Rn]
- , md.MatterLkUp
- , md.[PracticeGroup]
- , pg.[Description]
- from
- TE_3E_PROD_Clone.dbo.MattDate md
- left join
- TE_3E_PROD_Clone.dbo.PracticeGroup pg on pg.code = md.PracticeGroup
- ) md on md.MatterLkUp = m.MattIndex and md.[Rn] = 1
- left join
- (
- select
- row_number() over (partition by atk.[MatterLkUp] order by atk.[EffStart] desc) [Rn]
- , atk.[MatterLkUp]
- , atk.[BDTkpr1]
- , [FP&A].[dbo].[fGetFirstNameLastName](tk.DisplayName) [BD1]
- from
- TE_3E_PROD_Clone.[dbo].[AssociatedTkprs_CCC] atk
- left join
- TE_3E_PROD_Clone.dbo.Timekeeper tk on tk.TkprIndex = atk.BDTkpr1
- ) atk on atk.[MatterLkUp] = m.[MattIndex] and atk.[rn] = 1
- left join
- #cpafinal cpa on cpa.OpportunityId = m.OpportunityID_CCC collate SQL_Latin1_General_CP1_CI_AS
- where
- ms.[Description] not in ('Cancel NoEL Received','Cancelled - Duplicate')
- and md.[Description] not like '%-Z%'
- drop table if exists [FP&A]..CPAMatchandCredits;
- SELECT
- c.ParentCPA
- , a.BillingState State
- , a.BillingCity City
- , a.BillingPostalCode CPAZipCode
- , COALESCE(a.Alliance__c,'Direct') Alliance
- , bd.Name BD
- , rd.Name RD
- , credits.NoofClients
- , Credits.StudyCount
- , FA.ClientPaidLessExpenses
- , FA.AMountDueToCPA TotalAmountDuetoCPA
- , FA.AmountPaidToCPA TotalPaidtoCPA
- , FA.AmountOutStandingToCPA TotalAmountOutsandingtoCPA
- , COALESCE(FA.[ERC Services],0) + COALESCE(FA.[ERC Services OS],0) ERCAmountDueToCPA
- , COALESCE(FA.[ERC Services],0) ERCPaidToCPA
- , COALESCE(FA.[ERC Services OS],0) ERCAmountOutstandingToCPA
- , COALESCE(FA.[R&D Services],0) + COALESCE(FA.[R&D Services OS],0) [R&DAmountDueToCPA]
- , COALESCE(FA.[R&D Services],0) [R&DPaidToCPA]
- , COALESCE(FA.[R&D Services OS],0) [R&DAmountOutstandingToCPA]
- , COALESCE(FA.[Other Services],0) + COALESCE(FA.[Other Services OS],0) OtherAmountDueToCPA
- , COALESCE(FA.[Other Services],0) OtherPaidToCPA
- , COALESCE(FA.[Other Services OS],0) OtherAmountOutstandingToCPA
- , credits.AdjWIP [TotalAdjustedWIP]
- , credits.NoofBigClients
- , TotalCreditsDElivered
- , NoofERCClients
- , CASE WHEN ERCClientPaid>NoofERCClients THEN NoofERCClients ELSE ERCClientPaid END ERCClientPaid
- , ERCCreditsDElivered
- , bderc.Name ERCBD
- , rderc.Name ERCRD
- , RDNew
- , RDFU
- , ERC
- , CASE WHEN IsTalent = 1 THEN 'Yes' ELSE 'No' END IsTalent
- INTO [FP&A]..CPAMatchandCredits
- FROM
- (SELECT CPATop_Name ParentCPA
- ,CPATop_AccountId ParentCPAId
- FROM
- #cpah c
- GROUP BY
- CPATop_Name
- ,CPATop_AccountId) c
- JOIN
- SalesforceClone..Account a on a.id = c.ParentCPAId
- JOIN
- SalesforceClone..[User] bd on bd.id = a.OwnerId
- LEFT JOIN
- SalesforceClone..[User] rd on rd.id = a.caller__c
- LEFT JOIN
- (SELECT [CPATop_AccountId]
- , COUNT(DISTINCT AccountId) NoofClients
- , COUNT(DISTINCT CASE WHEN ClientTotalWIP>100000 THEN AccountId END) NoofBigClients
- , SUM(AdjWIP) AdjWIP
- , SUM([FinalCredit]) TotalCreditsDElivered
- , COUNT(DISTINCT CASE WHEN isERC = 1 THEN AccountId END) NoofERCClients
- , SUM(DISTINCT CASE WHEN isERC = 1 THEN [FinalCredit] END) ERCCreditsDElivered
- , SUM(StudyCount)StudyCount
- FROM
- #Credits
- GROUP BY
- [CPATop_AccountId]
- ) Credits on credits.[CPATop_AccountId] = c.ParentCPAId
- LEFT JOIN
- #FAAmts FA on FA.CPATop_AccountId = c.ParentCPAId
- LEFT JOIN
- SalesforceClone..[User] bderc on bderc.id = a.[Technical_Director_ERC__c]
- LEFT JOIN
- SalesforceClone..[User] rderc on rderc.id = a.[ERC_Relationship_Director__c]
- LEFT JOIN (
- SELECT *
- FROM
- (
- SELECT AccountID
- , Case
- when EngagementType = 150 AND PracticeGroup = 110 THEN 'RDNew'
- WHEN EngagementType = 125 AND PracticeGroup = 110 THEN 'RDFU'
- WHEN PracticeGroup = 225 THEN 'ERC'
- ELSE 'Other'
- END Type
- , ACFDD.FeePercentage
- FROM
- [TE_3E_PROD_Clone].dbo.[AG_CPAFirm] ACF
- JOIN
- [TE_3E_PROD_Clone].[dbo].[AG_CPAFirmDate] ACFD on ACF.CPAFirmIndex = ACFD.AG_CPAFirmLkUp and ACFD.NxEndDate = '99991231' and ACFD.NxStartDate != '99991231'
- JOIN
- [TE_3E_PROD_Clone].[dbo].[AG_CPAFirmDateDet] ACFDD on ACFDD.CPAFirmDate = ACFD.AG_CPAFirmDateID
- WHERE
- PracticeGroup IN (110,225)
- )a
- PIVOT (MAX(FeePercentage) FOR TYpe in ([RDNew],[RDFU],[ERC]))p
- ) Perc on Perc.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = c.ParentCPAId
- LEFT JOIN
- #IsTalent T on T.AccountId = c.ParentCPAId
- END
- --END OF PROCESS
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement