Advertisement
takz

BDM

Feb 6th, 2025 (edited)
400
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 281.20 KB | None | 0 0
  1. --START OF PROCESS
  2.  
  3. -- There are 7 steps
  4.  
  5. --Step 1 Executes; exec BDM.GETBDMasterReferralData
  6. --step 2 Executes; exec bdm.GETBDMasterMatterBilledCollected
  7. --Step 3 Executes; exec BDM.GetBDMasterMatterDataFrom3E
  8. --step 4 Executes; exec bdm.GETBDMasterSource
  9. --Step 5 Executes; exec bdm.ValidateBDMasterSourceData
  10. --step 6 Executes; exec [BDM].[proc_UnPublishedBDMasterMatterData] 1
  11. --Step 7 Executes; exec CPACombinedReportData
  12.  
  13.  
  14.  --Below are the stored procedure definition for each step
  15.  
  16. -- definitions are labeled by each steps in order of execution, i.e. step 1 - step 7
  17.  
  18.  
  19. --Step 1
  20.  
  21. USE [FP&A]
  22. GO
  23.  
  24. /****** Object:  StoredProcedure [BDM].[GETBDMasterReferralData]    Script Date: 2/6/2025 9:54:04 AM ******/
  25. SET ANSI_NULLS ON
  26. GO
  27.  
  28. SET QUOTED_IDENTIFIER ON
  29. GO
  30.  
  31. CREATE PROCEDURE [BDM].[GETBDMasterReferralData]
  32. AS BEGIN
  33.  
  34. if object_id('tempdb.dbo.#bdmOppOnCrsRecord','U') is not null
  35. drop table #bdmOppOnCrsRecord;
  36.  
  37. select distinct oncrs.id, oncrs.Opportunity__c, oncrs.RecordTypeId
  38. into #bdmOppOnCrsRecord
  39. from SalesforceClone..Opportunity_Non_CPA_Referral_Source__c oncrs
  40. JOIN SalesforceClone..RecordType rt on rt.id = oncrs.RecordTypeId
  41.  
  42. if object_id('tempdb.dbo.#bdmOppRecordType','U') is not null
  43. drop table #bdmOppRecordType;
  44.  
  45. select  p.Opportunity__c, p.RecordType1, p.RecordType2, p.RecordType3, p.RecordType4
  46. into #bdmOppRecordType
  47. from (
  48. select   oncrs.Opportunity__c, oncrs.RecordTypeId --, rt.name
  49. , CONCAT('RecordType' , ROW_NUMBER() OVER(PARTITION BY OPPortunity__c order by oncrs.recordtypeid desc)) as rn
  50. from #bdmOppOnCrsRecord oncrs
  51. --where  Opportunity__c in
  52. --('0061W00001HstToQAJ','0061W00001MpxrrQAB','0061W00001UCOYOQA5',
  53. --'0061W00001GFxW6QAL','0061W00001U9UbiQAF','0061W00001SJcdQQAT')
  54. ) a
  55. PIVOT (
  56.     min(RecordTypeId)
  57.     For rn in ([RecordType1],[RecordType2],[RecordType3],[RecordType4])
  58. )p
  59.  
  60.  
  61. if object_id('tempdb.dbo.#bdmOppOnCRSwithCampaign','U') is not null
  62. drop table #bdmOppOnCRSwithCampaign
  63. ;
  64. select o.*
  65. , oncrs1.Referral_Information__c [RF1]
  66. , oncrs2.Referral_Information__c [RF2]
  67. , oncrs3.Referral_Information__c [RF3]
  68. , oncrs4.Referral_Information__c [RF4]
  69. , oncrs1.Campaign__c [Campaign1]
  70. , oncrs2.Campaign__c [Campaign2]
  71. , oncrs3.Campaign__c [Campaign3]
  72. , oncrs4.Campaign__c [Campaign4]
  73. , oncrs1.Account__c [Account1]
  74. , oncrs2.Account__c [Account2]
  75. , oncrs3.Account__c [Account3]
  76. , oncrs4.Account__c [Account4]
  77. , oncrs1.Referring_CPA_Firm__c [RefAccount1]
  78. , oncrs2.Referring_CPA_Firm__c [RefAccount2]
  79. , oncrs3.Referring_CPA_Firm__c [RefAccount3]
  80. , oncrs4.Referring_CPA_Firm__c [RefAccount4]
  81. , ISNULL(oncrs1.Non_Conference__c, oncrs1.Non_conference_Other__c) [NonConference1]
  82. , ISNULL(oncrs2.Non_Conference__c, oncrs2.[Non_conference_Other__c]) [NonConference2]
  83. , ISNULL(oncrs3.Non_Conference__c, oncrs3.Non_conference_Other__c) [NonConference3]
  84. , ISNULL(oncrs4.Non_Conference__c, oncrs4.Non_conference_Other__c) [NonConference4]
  85. , ISNULL(oncrs1.ag_Employee_1__c, oncrs1.Other_Employee_1__c) [Employee1-1]
  86. , ISNULL(oncrs1.ag_Employee_2__c, oncrs1.Other_Employee_2__c) [Employee2-1]
  87. , ISNULL(oncrs1.ag_Employee_3__c, oncrs1.Other_Employee_3__c) [Employee3-1]
  88. , ISNULL(oncrs2.ag_Employee_1__c, oncrs2.Other_Employee_1__c) [Employee1-2]
  89. , ISNULL(oncrs2.ag_Employee_2__c, oncrs2.Other_Employee_2__c) [Employee2-2]
  90. , ISNULL(oncrs2.ag_Employee_3__c, oncrs2.Other_Employee_3__c) [Employee3-2]
  91. , ISNULL(oncrs3.ag_Employee_1__c, oncrs3.Other_Employee_1__c) [Employee1-3]
  92. , ISNULL(oncrs3.ag_Employee_2__c, oncrs3.Other_Employee_2__c) [Employee2-3]
  93. , ISNULL(oncrs3.ag_Employee_3__c, oncrs3.Other_Employee_3__c) [Employee3-3]
  94. , ISNULL(oncrs4.ag_Employee_1__c, oncrs4.Other_Employee_1__c) [Employee1-4]
  95. , ISNULL(oncrs4.ag_Employee_2__c, oncrs4.Other_Employee_2__c) [Employee2-4]
  96. , ISNULL(oncrs4.ag_Employee_3__c, oncrs4.Other_Employee_3__c) [Employee3-4]
  97. , oncrs1.Referral_Source__c [RefSource1]
  98. , oncrs2.Referral_Source__c [RefSource2]
  99. , oncrs3.Referral_Source__c [RefSource3]
  100. , oncrs4.Referral_Source__c [RefSource4]
  101. , CASE WHEN bdm.OpportunityIDCCC is not null and oncrs1.LastModifiedDate > GETDATE()-1 THEN 1
  102.         WHEN bdm.OpportunityIDCCC is not null and oncrs2.LastModifiedDate > GETDATE()-1 THEN 1
  103.         WHEN bdm.OpportunityIDCCC is not null and oncrs3.LastModifiedDate > GETDATE()-1 THEN 1
  104.         WHEN bdm.OpportunityIDCCC is not null and oncrs4.LastModifiedDate > GETDATE()-1 THEN 1
  105.         ELSE 0 END [RecordForUpdate]
  106. into #bdmOppOnCRSwithCampaign
  107. from #bdmOppRecordType o
  108. 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
  109. 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
  110. 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
  111. 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
  112. OUTER APPLY (select top 1 OpportunityIDCCC from BDM.BDMasterSOurce where OpportunityIDCCC = o.Opportunity__c) bdm
  113.  
  114. if object_id('tempdb.dbo.#BDMOppRefData','U') is not null
  115. drop table #BDMOppRefData;
  116.  
  117. select b.Opportunity__c, b.RecordType1, b.RecordType2, b.RecordType3,  b.RecordType4
  118. , CASE
  119.     WHEN rt1.Name = 'Raving Fan' and b.Account1 is not null Then a1.Name
  120.     WHEN rt2.Name = 'Raving Fan' and b.Account2 is not null Then a2.Name
  121.     WHEN rt3.Name = 'Raving Fan' and b.Account3 is not null Then a3.Name
  122.     WHEN rt4.Name = 'Raving Fan' and b.Account4 is not null Then a4.Name
  123.    
  124.  ELSE NULL END [OpRefSourceRavingFan]
  125. , CASE
  126.     WHEN rt1.Name = 'CPA' and b.RefAccount1 is not null Then rf1.Name
  127.     WHEN rt2.Name = 'CPA' and b.RefAccount2 is not null Then rf2.Name
  128.     WHEN rt3.Name = 'CPA' and b.RefAccount3 is not null Then rf3.Name
  129.     WHEN rt4.Name = 'CPA' and b.RefAccount4 is not null Then rf4.Name
  130.    ELSE NULL END  [OpRefSourceCPA]
  131.  , CASE
  132.     WHEN rt1.Name = 'Conference' and c1.Type = 'Seminar / Conference' Then c1.Name
  133.     WHEN rt2.Name = 'Conference' and c2.Type = 'Seminar / Conference' Then c2.Name
  134.     WHEN rt3.Name = 'Conference' and c3.Type = 'Seminar / Conference' Then c3.Name
  135.     WHEN rt4.Name = 'Conference' and c4.Type = 'Seminar / Conference' Then c4.Name
  136.   ELSE NULL END [OpRefSourceConference]
  137.  , CASE
  138.     WHEN rt1.Name = 'Non-Conference' and NonConference1 is not null Then NonConference1
  139.     WHEN rt2.Name = 'Non-Conference' and NonConference2 is not null Then NonConference2
  140.     WHEN rt3.Name = 'Non-Conference' and NonConference3 is not null Then NonConference3
  141.     WHEN rt4.Name = 'Non-Conference' and NonConference4 is not null Then NonConference4
  142.   ELSE NULL END [OpRefSourceNonConference]
  143.   , CASE
  144.     WHEN rt1.Name = 'Direct' and c1.Type in ('Bubble', 'Seminar / Conference') Then c1.Name
  145.     WHEN rt2.Name = 'Direct' and c2.Type in ('Bubble', 'Seminar / Conference') Then c2.Name
  146.     WHEN rt3.Name = 'Direct' and c3.Type in ('Bubble', 'Seminar / Conference') Then c3.Name
  147.     WHEN rt4.Name = 'Direct' and c4.Type in ('Bubble', 'Seminar / Conference') Then c4.Name
  148.   ELSE NULL END [OpRefSourceDirect]
  149.   , CASE
  150.     WHEN rt1.Name = 'E&A'  Then c1.Name
  151.     WHEN rt2.Name = 'E&A'  Then c2.Name
  152.     WHEN rt3.Name = 'E&A'  Then c3.Name
  153.     WHEN rt4.Name = 'E&A'  Then c4.Name
  154.   ELSE NULL END [OpRefSourceEA]
  155.   , CASE
  156.     WHEN rt1.Name = 'Referral Source' and rs1.Name is not Null Then rs1.Name
  157.     WHEN rt2.Name = 'Referral Source' and rs2.Name is not Null Then rs2.Name
  158.     WHEN rt3.Name = 'Referral Source' and rs3.Name is not Null Then rs3.Name
  159.     WHEN rt4.Name = 'Referral Source' and rs4.Name is not Null Then rs4.Name
  160.   ELSE NULL END [OpRefSourceReferralSource]
  161.   , CASE
  162.     WHEN rt1.Name in ('E&A Other','Direct') and c1.Type in ('Website') Then c1.Name
  163.     WHEN rt2.Name in ('E&A Other','Direct') and c2.Type in ('Website') Then c2.Name
  164.     WHEN rt3.Name in ('E&A Other','Direct') and c3.Type in ('Website') Then c3.Name
  165.     WHEN rt4.Name in ('E&A Other','Direct') and c4.Type in ('Website') Then c4.Name
  166.   ELSE NULL END [OpRefSourceWebsite]
  167.   , CASE
  168.     WHEN rt1.Name in ('E&A Other','Direct') and c1.Type in ('Webinar') Then c1.Name
  169.     WHEN rt2.Name in ('E&A Other','Direct') and c2.Type in ('Webinar') Then c2.Name
  170.     WHEN rt3.Name in ('E&A Other','Direct') and c3.Type in ('Webinar') Then c3.Name
  171.     WHEN rt4.Name in ('E&A Other','Direct') and c4.Type in ('Webinar') Then c4.Name
  172.   ELSE NULL END [OpRefSourceWebinar]
  173. , CASE
  174.     WHEN ISNULL(b.[Employee1-1],ISNULL(b.[Employee1-2], ISNULL(b.[Employee1-3],b.[Employee1-4]))) IS NOT NULL
  175.         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])))))
  176.   ELSE NULL END [OpRefSourceEmployee1]
  177. , CASE
  178.     WHEN ISNULL(b.[Employee2-1],ISNULL(b.[Employee2-2], ISNULL(b.[Employee2-3],b.[Employee2-4]))) IS NOT NULL
  179.         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])))))
  180.   ELSE NULL END [OpRefSourceEmployee2]
  181. , CASE
  182.     WHEN ISNULL(b.[Employee3-1],ISNULL(b.[Employee3-2], ISNULL(b.[Employee3-3],b.[Employee3-4]))) IS NOT NULL
  183.         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])))))
  184.   ELSE NULL END [OpRefSourceEmployee3]
  185. , CASE WHEN b.RecordForUpdate = 1 THEN 1
  186.         WHEN rt1.LastModifiedDate > GETDATE()-1 THEN 1
  187.         WHEN rt2.LastModifiedDate > GETDATE()-1 THEN 1
  188.         WHEN rt3.LastModifiedDate > GETDATE()-1 THEN 1
  189.         WHEN rt4.LastModifiedDate > GETDATE()-1 THEN 1
  190.         WHEN c1.LastModifiedDate > GETDATE()-1 THEN 1
  191.         WHEN c2.LastModifiedDate > GETDATE()-1 THEN 1
  192.         WHEN c3.LastModifiedDate > GETDATE()-1 THEN 1
  193.         WHEN c4.LastModifiedDate > GETDATE()-1 THEN 1
  194.     ELSE 0 END [RecordForUpdate]
  195. into #BDMOppRefData
  196. from #bdmOppOnCRSwithCampaign b
  197. LEFT JOIN SalesforceClone..RecordType rt1 on rt1.id =  b.RecordType1
  198. LEFT JOIN SalesforceClone..RecordType rt2 on rt2.id =  b.RecordType2
  199. LEFT JOIN SalesforceClone..RecordType rt3 on rt3.id =  b.RecordType3
  200. LEFT JOIN SalesforceClone..RecordType rt4 on rt4.id =  b.RecordType4
  201. LEFT JOIN SalesforceClone..Campaign c1 on c1.id =  b.Campaign1
  202. LEFT JOIN SalesforceClone..Campaign c2 on c2.id =  b.Campaign2
  203. LEFT JOIN SalesforceClone..Campaign c3 on c3.id =  b.Campaign3
  204. LEFT JOIN SalesforceClone..Campaign c4 on c4.id =  b.Campaign4
  205. LEFT JOIN SalesforceClone..Account a1 on a1.id =  b.Account1
  206. LEFT JOIN SalesforceClone..Account a2 on a2.id =  b.Account2
  207. LEFT JOIN SalesforceClone..Account a3 on a3.id =  b.Account3
  208. LEFT JOIN SalesforceClone..Account a4 on a4.id =  b.Account4
  209. LEFT JOIN SalesforceClone..Account rf1 on rf1.id =  b.RefAccount1
  210. LEFT JOIN SalesforceClone..Account rf2 on rf2.id =  b.RefAccount2
  211. LEFT JOIN SalesforceClone..Account rf3 on rf3.id =  b.RefAccount3
  212. LEFT JOIN SalesforceClone..Account rf4 on rf4.id =  b.RefAccount4
  213. LEFT JOIN SalesforceClone..Account rs1 on rs1.id =  b.RefSource1
  214. LEFT JOIN SalesforceClone..Account rs2 on rs2.id =  b.RefSource2
  215. LEFT JOIN SalesforceClone..Account rs3 on rs3.id =  b.RefSource3
  216. LEFT JOIN SalesforceClone..Account rs4 on rs4.id =  b.RefSource4
  217. OUTER APPLY (select top 1 OpportunityIDCCC from BDM.BDMasterSOurce where OpportunityIDCCC = b.Opportunity__c) bdm
  218.  
  219. IF EXISTS(select count(*) from #BDMOppRefData)
  220. BEGIN
  221. truncate table BDM.[BDMasterOppReferralInfo]
  222.  
  223. insert into BDM.[BDMasterOppReferralInfo]
  224. (
  225.     [Opportunity__c] ,
  226.     [RecordType1] ,
  227.     [RecordType2] ,
  228.     [RecordType3] ,
  229.     [RecordType4] ,
  230.     [OpRefSourceRavingFan] ,
  231.     [OpRefSourceCPA] ,
  232.     [OpRefSourceConference] ,
  233.     [OpRefSourceNonConference] ,
  234.     [OpRefSourceDirect] ,
  235.     [OpRefSourceEA] ,
  236.     [OpRefSourceEmployee1] ,
  237.     [OpRefSourceEmployee2] ,
  238.     [OpRefSourceEmployee3] ,
  239.     [OpRefSourceReferralSource],
  240.     [OpRefSourceWebsite],
  241.     [OpRefSourceWebinar],
  242.     [RecordForUpdate]
  243. )  
  244. (select [Opportunity__c] ,
  245.     [RecordType1] ,
  246.     [RecordType2] ,
  247.     [RecordType3] ,
  248.     [RecordType4] ,
  249.     [OpRefSourceRavingFan] ,
  250.     [OpRefSourceCPA] ,
  251.     [OpRefSourceConference] ,
  252.     [OpRefSourceNonConference] ,
  253.     [OpRefSourceDirect] ,
  254.     [OpRefSourceEA] ,
  255.     [OpRefSourceEmployee1] ,
  256.     [OpRefSourceEmployee2] ,
  257.     [OpRefSourceEmployee3]  ,
  258.     [OpRefSourceReferralSource],
  259.     [OpRefSourceWebsite],
  260.     [OpRefSourceWebinar],
  261.     [RecordForUpdate]
  262.     from #BDMOppRefData)
  263. END
  264.  
  265. END
  266. GO
  267.  
  268.  
  269. --Step 2
  270.  
  271. USE [FP&A]
  272. GO
  273.  
  274. /****** Object:  StoredProcedure [BDM].[GETBDMasterMatterBilledCollected]    Script Date: 2/6/2025 10:09:00 AM ******/
  275. SET ANSI_NULLS ON
  276. GO
  277.  
  278. SET QUOTED_IDENTIFIER ON
  279. GO
  280.  
  281.  
  282.  
  283.  
  284.  
  285.  
  286.  
  287.  
  288.  
  289.  
  290.  
  291.  
  292.  
  293. CREATE PROCEDURE [BDM].[GETBDMasterMatterBilledCollected]
  294. AS BEGIN
  295.  
  296. truncate table BDM.BDMasterMatterBilledCollected
  297. INSERT INTO BDM.BDMasterMatterBilledCollected
  298. SELECT Number
  299. ,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
  300. ,FutureYear
  301. ,      SUM(AdjWIPPerYearFEDState) AdjWIPPerYearFEDState  
  302. ,      SUM(BilledSplit) BilledSplit
  303. ,      SUM(CollectedSplit)  CollectedSplit
  304. , MIN(Year) [MinYear]
  305. --into BDM.BDMasterMatterBilledCollected
  306. FROM
  307. (
  308.         SELECT
  309.              m.Number
  310.         ,      m.EngSignedDate_CCC
  311.        ,      pc.Year
  312.        ,      m.Month_CCC
  313.        ,      MattStatus
  314.        ,      pc.Total
  315.        ,      ph.FeeCapPct
  316.        ,      CASE WHEN [PracticeGroup] in ('110','120','130') THEN
  317.                         CASE WHEN pc.Year>YEAR(DATEADD(M,-m.Month_CCC,m.EngSignedDate_CCC)) THEN 1  
  318.                             -- WHEN pc.Year=YEAR(DATEADD(M,-m.Month_CCC,m.EngSignedDate_CCC)) THEN 1    
  319.                              ELSE 0 END
  320.               ELSE NULL END FutureYear
  321.        ,      IsFederal
  322.        ,      State
  323.        ,      Billed
  324.        ,      Collected
  325.  
  326.        ,      pc.Total * ph.FeeCapPct/100 AdjWIPPerYearFEDState
  327.        ,      PH.AdjWIP - (COALESCE(priorCredits,0))*(ph.FeeCapPct/100) RemWIPbeforeRecord
  328.        ,      PH.AdjWIP - (COALESCE(priorCredits,0)+pc.Total)*(ph.FeeCapPct/100) RemWIPAfterRecord  
  329.        ,ph.AdjWIP
  330.        ---Need these Cases
  331.        ,      CASE  
  332.                     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)
  333.                     WHEN  (COALESCE(priorCredits,0)+pc.Total)*(ph.FeeCapPct/100)<=Billed THEN (pc.Total)*(ph.FeeCapPct/100)
  334.                     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)
  335.  
  336.                     ELSE 0
  337.              END BilledSplit
  338.        --,      CASE  
  339.                 --  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
  340.        --             WHEN  (COALESCE(priorCredits,0)+pc.Total)*(ph.FeeCapPct/100)<=Billed THEN 2
  341.        --             WHEN  Billed BETWEEN (COALESCE(priorCredits,0))*(ph.FeeCapPct/100) AND (COALESCE(priorCredits,0)+pc.Total)*(ph.FeeCapPct/100) THEN 3
  342.  
  343.        --             ELSE 0
  344.        --      END BilledSplitid
  345.        ,      CASE  
  346.                     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)
  347.                     WHEN  (COALESCE(priorCredits,0)+pc.Total)*(ph.FeeCapPct/100)<=Collected THEN (pc.Total)*(ph.FeeCapPct/100)
  348.                     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)
  349.  
  350.                     ELSE 0
  351.              END CollectedSplit
  352.  
  353.  
  354.  
  355.        FROM
  356.        TE_3E_Prod_Clone..matter m
  357.        JOIN
  358.        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'
  359.        JOIN
  360.        (SELECT  PGDetHdr,MAX(PGDetChild_CCCID) PGDetChild_CCCID
  361.               ,      IsFederal
  362.        ,      State
  363.        ,SUM(Total) Total
  364.        ,Year
  365.        FROM
  366.        TE_3E_PROD_Clone..PGDetChild_CCC pc
  367.        WHERE
  368.        IsGeneralWork = 0 and pc.Total>=0
  369.        GROUP BY
  370.         PGDetHdr
  371.        ,      IsFederal
  372.        ,      State
  373.        ,Year) pc on pc.PGDetHdr = ph.PGDetHdr_CCCID
  374.        left join
  375.         (
  376.             select
  377.                 row_number() over(partition by md.MatterLkUp order by md.effstart desc, md.nxStartDate desc, md.nxEndDate desc) [Rn]
  378.             ,   md.MatterLkUp
  379.             ,   md.[PracticeGroup]
  380.             , TimeStamp
  381.             from
  382.                 TE_3E_PROD_Clone.dbo.MattDate md
  383.         ) md on md.MatterLkUp = m.MattIndex and md.[Rn] = 1
  384.        OUTER APPLY -- need this function
  385.        (SELECT SUM(Total) priorCredits
  386.        FROM
  387.        TE_3E_PROD_Clone..PGDetChild_CCC ipc
  388.        WHERE
  389.        (ipc.Year<pc.Year OR (ipc.Year=pc.Year and ipc.PGDetChild_CCCID != pc.PGDetChild_CCCID AND ipc.State<COALESCE(pc.State,'zz')))
  390.        and ipc.PGDetHdr = pc.PGDetHdr and IsGeneralWork = 0
  391.        ) pcp
  392.        LEFT JOIN
  393.        (SELECT
  394.             NewMattIndex    Matter
  395.         ,   SUM(Billed)     Billed
  396.         ,   SUM(Collected)  Collected
  397.         FROM
  398.             (SELECT
  399.                 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
  400.             ,*
  401.             FROM
  402.                 (SELECT
  403.                     m.MattIndex
  404.                 ,   m.Number
  405.                 ,   m.MattStatus
  406.                 ,   COALESCE(M.CloseDate,CASE WHEN m.MattStatus IN ('TERM','COMP','CLOSING') THEN MattStatusDate END) CloseDate
  407.                 ,   md.PracticeGroup
  408.                 ,   md.Arrangement
  409.                 ,   PH.AdjWIP
  410.                 ,   PH.FeeCapPct
  411.                 ,   SUM(
  412.                         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)
  413.                         WHEN md.PracticeGRoup = 130 then COALESCE(EngineerReview,0)
  414.                         WHEN pc.TriggerType IN ('RQ','PQ','NQ') THEN 0
  415.                         ELSE COALESCE(ValueAssessment,0) * 0.8 END) BillableCredit
  416.                 ,   SUM(
  417.                         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)
  418.                         WHEN md.PracticeGRoup = 130 then COALESCE(EngineerReview,0)
  419.                         WHEN pc.TriggerType IN ('RQ','PQ','NQ') THEN 0
  420.                         ELSE COALESCE(ValueAssessment,0) * 0.8 END) * (COALESCE(PH.FeeCapPct,0)/100)
  421.                         -COALESCE(SUM(Billed)OVER(Partition By m.MattIndex Order by InvDate, InvMaster),0)+COALESCE(Billed,0)
  422.                         BillableWIPatDate
  423.                 ,   Billed
  424.                 ,   Collected
  425.                 ,   InvMaster
  426.                 ,   InvDate
  427.                 FROM
  428.                      (SELECT
  429.                         Matter
  430.                         ,      SUM(CASE WHEN ARList IN ('Bill','BillRev','Woff','WoffRev') THEN ARFee ELSE 0 END) Billed
  431.                         ,      SUM(CASE WHEN ARList IN ('Receipt','RcptRev') THEN -ARFee ELSE 0 END) Collected
  432.                         ,   InvMaster
  433.                         ,   InvDate
  434.                        FROM
  435.                         TE_3E_PROD_Clone..ARMaster
  436.                     --  where matter = 7042
  437.                        GROUP BY Matter
  438.                         ,   InvMaster
  439.                         ,   InvDate ) AR
  440.                 JOIN
  441.                     (
  442.                     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
  443.                     FROM (
  444.                     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
  445.                     FROM
  446.                         [TE_3E_PROD_Clone].[dbo].matter m
  447.                     UNION ALL
  448.                     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
  449.                     FROM
  450.                         [TE_3E_PROD_Clone].[dbo].matter_audit m
  451.                     )m)m on AR.Matter = m.MattIndex and AR.InvDate between m.NxStartDate and m.NxEndDate
  452.                 JOIN
  453.                     TE_3E_PROD_Clone..MattDate MD on MD.Matterlkup = m.MattIndex and AR.InvDate between md.NxStartDate and md.NxEndDate and md.NxStartDate != '99991231'
  454.                 JOIN
  455.                     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'
  456.                 JOIN
  457.                     TE_3E_PROD_Clone..PGDetChild_CCC PC on PC.PGDetHdr = PH.PGDetHdr_CCCID
  458.                 --WHERE
  459.                 --m.MattIndex = 58865
  460.                 GROUP BY
  461.                     m.MattIndex
  462.                 ,   m.Number
  463.                 ,   m.MattStatus
  464.                 ,   COALESCE(M.CloseDate,CASE WHEN m.MattStatus IN ('TERM','COMP','CLOSING') THEN MattStatusDate END)
  465.                 ,   md.PracticeGroup
  466.                 ,   md.Arrangement
  467.                 ,   PH.AdjWIP
  468.                 ,   PH.FeeCapPct
  469.                 ,   Billed
  470.                 ,   Collected
  471.                 ,   InvMaster
  472.                 ,   InvDate
  473.                 ) AR
  474.             ) AR
  475.         GROUP BY
  476.             AR.NewMattIndex) BC on BC.Matter = m.MattIndex
  477.       -- where number in ('003790.0012','003790.0019')
  478.         --300025.0001','009401.0007')
  479.        )Splits
  480. GROUP BY
  481. Number,FutureYear,FutureYear*Year
  482. order by 1,2
  483.  
  484. END
  485. GO
  486.  
  487.  
  488. --Step 3
  489.  
  490. USE [FP&A]
  491. GO
  492.  
  493. /****** Object:  StoredProcedure [BDM].[GETBDMasterMatterDataFrom3E]    Script Date: 2/6/2025 10:25:24 AM ******/
  494. SET ANSI_NULLS ON
  495. GO
  496.  
  497. SET QUOTED_IDENTIFIER ON
  498. GO
  499.  
  500.  
  501.  
  502. CREATE PROCEDURE  [BDM].[GETBDMasterMatterDataFrom3E]
  503. AS BEGIN
  504.  
  505.  
  506. if object_id('tempdb.dbo.#Duals','U') is not null
  507. drop table #Duals;
  508.  
  509. SELECT MattINdex
  510. INTO #Duals
  511. FROM (
  512.  
  513. SELECT MattIndex, COUNT(mattindex)Over(partition by OpportunityID_CCC) - COUNT(mattindex)Over(partition by OpportunityID_CCC,year(minday),month(minday)) dual
  514. FROM (
  515. SELECT MattIndex,OpportunityID_CCC,DATEADD(d,0,DATEDIFF(d,0,MIN(TimeStamp))) MinDay
  516. FROM (
  517. SELECT MattIndex,OpportunityID_CCC,TimeStamp
  518. FROM
  519. TE_3E_PROD_Clone..Matter
  520. UNION ALL
  521. SELECT MattIndex,OpportunityID_CCC,TimeStamp
  522. FROM
  523. TE_3E_PROD_Clone..Matter_audit
  524. UNION ALL
  525. SELECT MattIndex,OpportunityID_CCC,OpenDate
  526. FROM
  527. TE_3E_PROD_Clone..Matter
  528. where OpenDate<='20181015') a
  529. where
  530. OpportunityID_CCC is not null
  531. GROUP BY
  532. MattIndex,OpportunityID_CCC
  533. ) b
  534. ) c
  535. WHERE dual >1
  536.  
  537.  
  538. if object_id('tempdb.dbo.#bdmMatterInfo','U') is not null
  539. drop table #bdmMatterInfo;
  540.  
  541. select
  542.     cast(a.[OpportunityID_CCC] as nvarchar(64)) [OpportunityID_CCC]
  543. ,   a.[Number]
  544. ,   cast(a.[MattIndex] as int) [MattIndex]
  545. ,   cast(a.[AltNumber] as nvarchar(64)) [AltNumber]
  546. ,   a.DisplayName
  547. ,   a.Description
  548. ,   a.Client
  549. ,   a.ClientId
  550. ,   a.CloseDate
  551. ,   a.Currency
  552. ,   a.IsEvergreenCCC
  553. ,   a.ServiceLine
  554. ,   a.State
  555. ,   cast(a.[Signed_Date] as datetime) [EngSignedDateCCC]
  556. ,   cast(a.[BD1_ID] as int) [BD1ID]
  557. ,   cast(a.[BD2_ID] as int) [BD2ID]
  558. ,   cast(a.[BD3_ID] as int) [BD3ID]
  559. ,   cast(a.[SOE_1_ID] as int) [SOE1ID]
  560. ,   cast(a.[SOE_2_ID] as int) [SOE2ID]
  561. ,   cast(a.[QC_ID] as int) [QCID]
  562. ,   cast(a.[TD_ID] as int) [TDID]
  563. ,   cast(a.[PM_ID] as int) [PMID]
  564. ,   cast(a.[PBD] as nvarchar(200)) [PBD]
  565. ,   cast(a.[SBD] as nvarchar(200)) [SBD]
  566. ,   cast(a.[PRD] as nvarchar(200)) [PRD]
  567. ,   cast(a.[SRD] as nvarchar(200)) [SRD]
  568. ,   cast(a.[PM] as nvarchar(200)) [PM]
  569. ,   cast(a.[Original_WIP] as decimal(16,2)) [OriginalWIP]
  570. ,   cast(a.[Fees_Collected] as decimal(16,2)) [Collected]
  571. ,   cast(a.[Credit] as decimal(16,2)) [Credit]
  572. ,   cast(a.[Total_Invoiced] as decimal(38,2)) [Billed] --Billed Amount to be change to Total_Invoiced
  573. ,   cast(a.[Worked_WIP] as decimal(17,2)) [WorkedWIP]
  574. ,   cast(a.[Pending_Invoices] as decimal(38,2)) [PendingInvoices]
  575. ,   cast(coalesce(case  
  576.                     when a.[179DWriteDownFlag] = 1 then 0  
  577.                     when coalesce(a.[VAERFNDeliveredCnt],0) >= 0 then a.[Adjusted_WIP] 
  578.                     else a.[Original_WIP]  
  579.                     end,0) as decimal(16,2)) [TotalWIP]
  580. ,   cast(a.[Hours_Worked] as decimal(38,5)) [HoursWorked]
  581. ,   cast(coalesce(a.[Remaining_WIP],0) as decimal(16,2)) [RemainingWIP]
  582. --, CASE WHEN a.MattStatus IN ('COMP','CLOSING','CLOSING_ERCLIVE') THEN cast(coalesce(a.[Total_Invoiced],0) as decimal(16,2)) ELSE
  583. --              cast(coalesce(a.[Adjusted_WIP],0) as decimal(16,2)) END [AdjustedWIP]
  584. ,   cast(coalesce(a.[Adjusted_WIP],0) as decimal(16,2)) [AdjustedWIP]
  585. ,   cast(coalesce(a.[Unbilled_WIP],0) as decimal(38,2)) [UnbilledWIP]
  586. ,   cast(coalesce(a.[Unbilled_Worked_WIP],0) as decimal(38,2)) [UnbilledWorkedWIP]
  587. ,   cast(coalesce(case when a.[Balance] < 0 then 0 else a.[Balance] end,0) as decimal(38,2)) [Balance]
  588. ,   cast(coalesce(a.[Unworked_Unbilled],0) as decimal(38,2)) [UnworkedUnbilled] --find not in use
  589. ,   cast(a.[BD1_Allocation] as decimal(38,2)) [BD1Allocation]
  590. ,   cast(a.[BD2_Allocation] as decimal(38,2)) [BD2Allocation]
  591. ,   cast(a.[BD3_Allocation] as decimal(38,2)) [BD3Allocation]
  592. ,   cast(a.[RD1_Allocation] as decimal(38,2)) [RD1Allocation]
  593. ,   cast(a.[RD2_Allocation] as decimal(38,2)) [RD2Allocation]
  594. ,   cast(coalesce(a.[Original_WIP] * a.[BD1_Allocation],0) as decimal(38,2)) [BD1OrgWIPAlloc]
  595. ,   cast(coalesce(a.[Original_WIP] * a.[BD2_Allocation],0) as decimal(38,2)) [BD2OrgWIPAlloc]
  596. ,   cast(coalesce(a.[Original_WIP] * a.[BD3_Allocation],0) as decimal(38,2)) [BD3OrgWIPAlloc]
  597. ,   cast(coalesce(a.[Original_WIP] * a.[RD1_Allocation],0) as decimal(38,2)) [RD1OrgWIPAlloc]
  598. ,   cast(coalesce(a.[Original_WIP] * a.[RD2_Allocation],0) as decimal(38,2)) [RD2OrgWIPAlloc]
  599. ,   cast(coalesce(a.[Adjusted_WIP] * a.[BD1_Allocation],0) as decimal(38,2)) [BD1AdjWIPAlloc]
  600. ,   cast(coalesce(a.[Adjusted_WIP] * a.[BD2_Allocation],0) as decimal(38,2)) [BD2AdjWIPAlloc]
  601. ,   cast(coalesce(a.[Adjusted_WIP] * a.[BD3_Allocation],0) as decimal(38,2)) [BD3AdjWIPAlloc]
  602. ,   cast(coalesce(a.[Adjusted_WIP] * a.[RD1_Allocation],0) as decimal(38,2)) [RD1AdjWIPAlloc]
  603. ,   cast(coalesce(a.[Adjusted_WIP] * a.[RD2_Allocation],0) as decimal(38,2)) [RD2AdjWIPAlloc]
  604. ,   cast(a.[BD1_Fees_Billed] as decimal(38,2)) [BD1FeesBilled]
  605. ,   cast(a.[BD2_Fees_Billed] as decimal(38,2)) [BD2FeesBilled]
  606. ,   cast(a.[BD3_Fees_Billed] as decimal(38,2)) [BD3FeesBilled]
  607. ,   cast(a.[RD1_Fees_Billed] as decimal(38,2)) [RD1FeesBilled]
  608. ,   cast(a.[RD2_Fees_Billed] as decimal(38,2)) [RD2FeesBilled]
  609. ,   cast(a.[BD1_Fees_Collected] as decimal(38,2)) [BD1FeesCollected]
  610. ,   cast(a.[BD2_Fees_Collected] as decimal(38,2)) [BD2FeesCollected]
  611. ,   cast(a.[BD3_Fees_Collected] as decimal(38,2)) [BD3FeesCollected]
  612. ,   cast(a.[RD1_Fees_Collected] as decimal(38,2)) [RD1FeesCollected]
  613. ,   cast(a.[RD2_Fees_Collected] as decimal(38,2)) [RD2FeesCollected]
  614. ,   a.[OriginalSignedDate]
  615. ,   a.VAERFNDeliveredCnt
  616. , Case When a.MaxTaxYear> a.MinTaxYear then 'Multi' else 'Single' end [StudyYears]
  617. , a.MajorIndustry
  618. , a.PracticeGroupCode [Code]
  619. ,   a.MattStatus
  620. ,   a.MattCategory
  621. , a.EngType_CCC [EngTypeCCC]
  622. ,   a.EngStatus_CCC [EngStatusCCC]
  623. ,   a.Updated_WIP [UpdatedWIP]
  624. ,   a.MinTaxYear
  625. ,   a.MaxTaxYear
  626. ,   CASE WHEN IsCloned_CCC = 1 OR a.EngType_CCC = 'FU' then 0 else a.[1x_Adj._Flag] end [1TimeAdj]
  627. , a.StudyYear
  628. , RecordForUpdate
  629. ,IsCloned_CCC
  630. into #bdmMatterInfo
  631. from
  632.     (
  633.         select
  634.             m.*
  635.         ,   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]
  636.         ,   CAST(coalesce(case 
  637.                         when /*m.[PracticeGroupCode] IN (225) AND*/ m.[MattStatus] in ('KO','CANCELDUP','Cancel_NOEL','TERM','TERM_EG') THEN 0
  638.                         --when [VAERFNDeliveredCnt] = 0 and m.[PracticeGroupCode] IN (225) THEN [OrigWIP]
  639.                         when m.[PracticeGroupCode] IN (225,150,175) OR [NxUnit] = 20 THEN AdjWIP
  640.                         when m.[MattStatus] in ('Cancel_NOEL','CANCELDUP') then 0  
  641.                         when [179DWriteDownFlag] = 1 then 0
  642.                         when  m.[PracticeGroupCode] IN (130) and [179DUnder60Flag] = 1 and [RevSFAmount]>[AdjWIPrvs] THEN [RevSFAmount]
  643.                         when m.[MattStatus] in ('COMP','CLOSING','KO','TERM','CLOSING_ERCLIVE','COMP_ERCLIVE','TERM_ERCLIVE') then [AdjWIPrvs] 
  644.                         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]  
  645.                         when [VAERFNDeliveredCnt] = 0 and [NxUnit] != 20 then coalesce([RevSFAmount], [AdjWIPrvs]) 
  646.                         when m.[MattStatus] not in ('Cancel_NOEL','CANCELDUP') then [AdjWIPrvs]
  647.                         else   
  648.                             case   
  649.                                 when [OpportunityID_CCC] is null then [OrigWIP]
  650.                                 when row_number() over (partition by [OpportunityID_CCC] order by m.[MattIndex]) > 1 then 0
  651.                                 else coalesce(case 
  652.                                                 when [NxUnit] = 20 and [OrigWIP] = 0 then [Amount] 
  653.                                                 when [NxUnit] = 20 or [Amount] = 0 then [OrigWIP]  
  654.                                                 else [RevSFAmount] 
  655.                                                 end, [OrigWIP])
  656.                                 end
  657.                         end
  658.                     , 0) as decimal(38,2)) [Adjusted_WIP]
  659.         ,   CAST(coalesce(case  --Per Harry 3/29/2022 should be the same as Adj WIP excluding alterations based on Status -KR
  660.                         --when m.[MattStatus] in ('Cancel_NOEL','CANCELDUP') then 0
  661.                         when /*m.[PracticeGroupCode] IN (225) AND*/ m.[MattStatus] in ('KO','CANCELDUP','Cancel_NOEL','TERM','TERM_EG') THEN 0
  662.                         when m.[PracticeGroupCode] IN (225,150,175) OR [NxUnit] = 20 THEN AdjWIP   
  663.                         when [179DWriteDownFlag] = 1 then 0
  664.                         --when m.[MattStatus] in ('COMP','CLOSING','KO','TERM','CLOSING_ERCLIVE','COMP_ERCLIVE','TERM_ERCLIVE') then [AdjWIPrvs]   
  665.                         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] 
  666.                         when [VAERFNDeliveredCnt] = 0 and [NxUnit] != 20 then coalesce([RevSFAmount], [AdjWIPrvsUW])   
  667.                         --when m.[MattStatus] not in ('Cancel_NOEL','CANCELDUP') then [AdjWIPrvs]  
  668.                         else [AdjWIPrvsUW]
  669.                             --case 
  670.                             --  when [OpportunityID_CCC] is null then [OrigWIP]
  671.                             --  when row_number() over (partition by [OpportunityID_CCC] order by m.[MattIndex]) > 1 then 0
  672.                             --  else coalesce(case 
  673.                             --                  when [NxUnit] = 20 and [OrigWIP] = 0 then [Amount] 
  674.                             --                  when [NxUnit] = 20 or [Amount] = 0 then [OrigWIP]  
  675.                             --                  else [RevSFAmount] 
  676.                             --                  end, [OrigWIP])
  677.                             --  end
  678.                         end
  679.                     , 0) as decimal(38,2)) [Updated_WIP]
  680.         ,   coalesce(case
  681.                         when [179DWriteDownFlag] = 1 then 0
  682.                         when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 then 0
  683.                         when [VAERFNDeliveredCnt] = 0 then [RevSFCredit]
  684.                         end
  685.                     , [PHCredit], 0) [Credit]
  686.         ,   coalesce(case
  687.                         when [179DWriteDownFlag] = 1 then 0
  688.                         when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 then 0
  689.                         when [VAERFNDeliveredCnt] = 0 and [WorkAmt] < [RevSFAmount] then [WorkAmt]
  690.                         when [VAERFNDeliveredCnt] = 0 and [WorkAmt] >= [RevSFAmount] then [RevSFAmount]
  691.                         end
  692.                     , [AdjWIPrvs] - [RemainingWIP], 0) [Worked_WIP]
  693.         ,   CAST(coalesce(case 
  694.                         when [179DWriteDownFlag] = 1 then 0
  695.                         when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] != 'FU' then 0
  696.                         when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] is null then 0
  697.                         when [VAERFNDeliveredCnt] = 0 and [WorkAmt] < [RevSFAmount] then [RevSFAmount] - [WorkAmt] 
  698.                         when [VAERFNDeliveredCnt] = 0 and [WorkAmt] >= [RevSFAmount] then 0
  699.                         end
  700.                     , [RemainingWIP]) as decimal(38,2)) [Remaining_WIP]
  701.         ,   CAST(coalesce(case 
  702.                         when [179DWriteDownFlag] = 1 then 0
  703.                         when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] != 'FU' then 0
  704.                         when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] is null then 0
  705.                         when [VAERFNDeliveredCnt] = 0 then [RevSFAmount] - [Total_Invoiced]
  706.                         end
  707.                     , [AdjWIPrvs] - [Total_Invoiced]) as decimal(38,2)) [Unbilled_WIP]
  708.         ,   coalesce(case  
  709.                         when [179DWriteDownFlag] = 1 then 0
  710.                         when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] != 'FU' then 0
  711.                         when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] is null then 0
  712.                         when [VAERFNDeliveredCnt] = 0 then [RevSFAmount] - [RevSFAmount] - [WorkAmt] - [Total_Invoiced] - [Pending_Invoices]   
  713.                         end
  714.                     , [AdjWIPrvs] - [RemainingWIP] - [Total_Invoiced] - [Pending_Invoices]) [Unbilled_Worked_WIP]
  715.         ,   coalesce(case  
  716.                         when [179DWriteDownFlag] = 1 then 0
  717.                         when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] != 'FU' then 0
  718.                         when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] is null then 0
  719.                         when [VAERFNDeliveredCnt] = 0 then ([RevSFAmount] * [CurrentTaxYearPct]) - [RevSFAmount] - [WorkAmt] - [Total_Invoiced] - [Pending_Invoices]   
  720.                         end
  721.                     , [AdjWIPrvs] - [RemainingWIP] - [Total_Invoiced] - [Pending_Invoices]) [Balance]
  722.         ,   coalesce(case  
  723.                         when [179DWriteDownFlag] = 1 then 0
  724.                         when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] != 'FU' then 0
  725.                         when [VAERFNDeliveredCnt] = 0 and [FutureTaxYearPct] = 1 and [NxUnit] != 20 and m.[MattCategory] is null then 0
  726.                         when [VAERFNDeliveredCnt] = 0 and [WorkAmt] < [RevSFAmount] then [RevSFAmount] - [WorkAmt] 
  727.                         when [VAERFNDeliveredCnt] = 0 and [WorkAmt] >= [RevSFAmount] then 0
  728.                         end
  729.                     , [RemainingWIP]) [Unworked_Unbilled]
  730.         ,   [Total_Invoiced] * [BD1_Allocation] [BD1_Fees_Billed]
  731.         ,   [Total_Invoiced] * [BD2_Allocation] [BD2_Fees_Billed]  
  732.         ,   [Total_Invoiced] * [BD3_Allocation] [BD3_Fees_Billed]  
  733.         ,   [Total_Invoiced] * [RD1_Allocation] [RD1_Fees_Billed]  
  734.         ,   [Total_Invoiced] * [RD2_Allocation] [RD2_Fees_Billed]
  735.         ,   [Fees_Collected] * [BD1_Allocation] [BD1_Fees_Collected]
  736.         ,   [Fees_Collected] * [BD2_Allocation] [BD2_Fees_Collected]
  737.         ,   [Fees_Collected] * [BD3_Allocation] [BD3_Fees_Collected]
  738.         ,   [Fees_Collected] * [RD1_Allocation] [RD1_Fees_Collected]
  739.         ,   [Fees_Collected] * [RD2_Allocation] [RD2_Fees_Collected]
  740.         ,   bd1.EmployeeFullName [PBD]
  741.         ,   bd2.EmployeeFullName [SBD]
  742.         ,   SOE1.EmployeeFullName [PRD]
  743.         ,   SOE2.EmployeeFullName [SRD]
  744.         ,   PM.EmployeeFullName [PM]
  745.  
  746.         , CASE WHEN f.Number IS NOT NULL AND TimeStampFromYesterday > 0 THEN 1 ELSE 0 END [RecordForUpdate]
  747.        
  748.         from
  749.             (
  750.                 select
  751.                     ma.*
  752.                 ,   coalesce(case
  753.                         when ma.[PracticeGroupCode] = 175 then ma.[AdjWIP]
  754.                         when ma.[FutureTaxYearTodayCnt] > 0 then 0
  755.                         when [1x_Adj._Flag] = 1 --1xadj
  756.                          AND ma.[Total_Invoiced] = 0
  757.                          AND [MattStatus] in ('COMP','CLOSING','KO','TERM','CLOSING_ERCLIVE','COMP_ERCLIVE','TERM_ERCLIVE') THEN ma.[AdjWIP]
  758.                         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]                           
  759.                         else ma.[AdjWIP]
  760.                         end,0) [AdjWIPrvs]
  761.                                 ,   coalesce(case
  762.                         when ma.[PracticeGroupCode] = 175 then ma.[AdjWIP]
  763.                         when ma.[FutureTaxYearTodayCnt] > 0 then 0
  764.                         when [1x_Adj._Flag] = 1 --1xadj
  765.                          AND ma.[Total_Invoiced] = 0
  766.                          AND [MattStatus] in ('COMP','CLOSING','KO','TERM','CLOSING_ERCLIVE','COMP_ERCLIVE','TERM_ERCLIVE') THEN ma.[AdjWIP]
  767.                         when [MattStatus] in ('COMP','CLOSING','KO','TERM','CLOSING_ERCLIVE','COMP_ERCLIVE','TERM_ERCLIVE') then ma.[AdjWIP]                           
  768.                         else ma.[AdjWIP]
  769.                         end,0) [AdjWIPrvsUW]
  770.                 ,   case
  771.                         when ma.[PracticeGroupCode] = 175 then ma.[Amount]
  772.                         when ma.[FutureTaxYearTodayCnt] > 0 then 0
  773.                         when ma.[MattStatus] IN ('CANCELDUP','Cancel_NOEL') then 0
  774.                         when (ma.[FutureTaxYearPct] = 1 and ma.[NxUnit] != 20 and COALESCE(ma.[EngType_CCC],'New') = 'FU' and [1x_Adj._Flag] = 1) then ma.[OrigWIP]
  775.                         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)
  776.                         end [RevSFAmount]
  777.                 ,   case
  778.                         when ma.[PracticeGroupCode] = 175 then ma.[SFCredit]
  779.                         when ma.[FutureTaxYearTodayCnt] > 0 then 0
  780.                         when ma.[MattStatus] IN ('CANCELDUP','Cancel_NOEL') then 0
  781.                         when (ma.[FutureTaxYearPct] = 1 and ma.[NxUnit] != 20 and COALESCE(ma.[EngType_CCC],'New') = 'FU' and [1x_Adj._Flag] = 1) then ma.[PHCredit]
  782.                         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)
  783.                         end [RevSFCredit]
  784.                 --, case
  785.                 --      when ma.[BillingGroup] = 0 then ma.[Billed_Amount]
  786.                 --      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]
  787.                 --      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
  788.                 --      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
  789.                 --      end [BilledAdj]
  790.                 FROM
  791.                 (SELECT ma.*
  792.                 ,   coalesce(case
  793.                                         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
  794.                                     --  when COALESCE(ma.[EngType_CCC],'New') = 'FU'  and ma.[MinTaxYear] >  ma.[YearEngSigned] and ma.[PracticeGroupCode] in (110,120,130) then 1
  795.                                         when COALESCE(ma.[EngType_CCC],'New') IN ('NEW','CONT') and ma.[MinTaxYear] >= ma.[YearEngSigned] and ma.[PracticeGroupCode] in (110,120,130) then 1
  796.                                         end, 0) [1x_Adj._Flag]
  797.                
  798.                 from
  799.                     (
  800.                         select
  801.                             m.[OpportunityID_CCC]
  802.                         ,   m.[MattIndex]
  803.                         ,   m.[Number]
  804.                         ,   m.[Client] [ClientId]
  805.                         ,   m.DisplayName [DisplayName]
  806.                         ,   c.DisplayName [Client]
  807.                         ,   m.AltNumber [AltNumber]
  808.                         ,   m.Description [Description]
  809.                         ,   m.CloseDate [CloseDate]
  810.                         ,   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]
  811.                         ,   m.Currency [Currency]
  812.                         ,   m.IsEvergreen_CCC [IsEvergreenCCC]
  813.                         ,   m.EngStatus_CCC
  814.                         ,   COALESCE(case
  815.                                 WHEN pg.[Code] = 225 THEN 'NEW'
  816.                                 WHEN Cloned.IsCloned_CCC = 1 AND m.MattCategory != 'NEW' then 'FU'
  817.                                 when et.[Description] = 'New Business' then 'NEW'
  818.                                 when et.[Description] =  'Follow - Up' then 'FU'
  819.                                 when et.[Description] =  'Continuation' then 'CONT'
  820.                             end,m.MattCategory) [EngType_CCC]
  821.                         ,   a.State as [State]
  822.                         ,   mi.Description [MajorIndustry]
  823.                         ,   m.[EngSignedDate_CCC]
  824.                         ,   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]
  825.                         ,   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]
  826.                         ,   CASE WHEN d.Mattindex is not null THEN
  827.                         coalesce(
  828.                                      m.MattCategory
  829.                                     , case
  830.                                         when et.[Description] = 'New Business' then 'NEW'
  831.                                         when et.[Description] =  'Follow - Up' then 'FU'
  832.                                         when et.[Description] =  'Continuation' then 'CONT'
  833.                                         end
  834.                                     , case
  835.                                         when o.[Type] = 'New Business' and COALESCE(Cloned.IsCloned_CCC,0) = 0 then 'NEW'
  836.                                         when o.[Type] = 'Follow-Up' and COALESCE(Cloned.IsCloned_CCC,0) = 0 then 'FU'
  837.                                         when o.[Type] = 'Continuation' and COALESCE(Cloned.IsCloned_CCC,0) = 0 then 'CONT'
  838.                                         end ) ELSE
  839.                         coalesce(case
  840.                                         when o.[Type] = 'New Business' and COALESCE(Cloned.IsCloned_CCC,0) = 0 then 'NEW'
  841.                                         when o.[Type] = 'Follow-Up' and COALESCE(Cloned.IsCloned_CCC,0) = 0 then 'FU'
  842.                                         when o.[Type] = 'Continuation' and COALESCE(Cloned.IsCloned_CCC,0) = 0 then 'CONT'
  843.                                         end
  844.                                     , m.MattCategory
  845.                                     , case
  846.                                         when et.[Description] = 'New Business' then 'NEW'
  847.                                         when et.[Description] =  'Follow - Up' then 'FU'
  848.                                         when et.[Description] =  'Continuation' then 'CONT'
  849.                                         end) END [MattCategory]
  850.                         ,   m.[MattStatus]
  851.                         ,   coalesce(o.[BD1_TKID], case when eu.[NxUnit] = 20 then atk.[BD1_ID] end,-1) [BD1_ID]
  852.                         ,   coalesce(o.[BD2_TKID], case when eu.[NxUnit] = 20 then atk.[BD2_ID] end,-1) [BD2_ID]
  853.                         ,   coalesce(atk.[BD3_ID],-1) [BD3_ID]
  854.                         ,   coalesce(o.[SOE1_TKID], case when eu.[NxUnit] = 20 then atk.[SOE1_ID] end,-1) [SOE_1_ID]
  855.                         ,   coalesce(o.[SOE2_TKID], case when eu.[NxUnit] = 20 then atk.[SOE2_ID] end,-1) [SOE_2_ID]
  856.                         ,   coalesce(qc.[QC_ID],-1) [QC_ID]
  857.                         ,   coalesce(md.[TD_ID],-1) [TD_ID]
  858.                         ,   coalesce(md.[PM_ID],-1) [PM_ID]
  859.                         ,   CASE WHEN pg.Description in ('R&D Services', 'SALT Services') THEN 110 ELSE pg.[Code] END [PracticeGroupCode]
  860.                         ,   pg.[Description] [ServiceLine]
  861.                         ,   count(m.[OpportunityID_CCC]) over(partition by m.[OpportunityID_CCC]) [SFOppCnt]
  862.                         ,   o.[Amount]
  863.                         ,   CAST(o.[Credit] as Decimal(18,2)) [SFCredit]
  864.                         ,   ph.[EffStart]
  865.                         ,   ph.[OrigWIP]
  866.                         --, ph.[AdjWIP]
  867.                         ,   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]
  868.                         --, ph.[RemainingWIP]
  869.                         ,   CASE WHEN pg.[Code] in ('110','120','130','225') and StudyCredit is not null and StudyCredit > 0
  870.                                     then CAST(ph.[RemainingWIP]*(PHCredit/StudyCredit) as Decimal(18,2)) else ph.RemainingWIP end [RemainingWIP]
  871.                         ,   ph.[VAERFN]
  872.                         ,   ph.[PHCredit]
  873.                         ,   ph.[CurrentTaxYearPct]
  874.                         ,   ph.[FutureTaxYearPct]
  875.                         ,   ph.[FutureTaxYearTodayCnt]
  876.                         ,   ph.[FutureTaxYearCnt]
  877.                         ,   ph.[CurrentTaxYearCnt]
  878.                         ,   coalesce(ph.[VAERFNDeliveredCnt],0) [VAERFNDeliveredCnt]
  879.                         ,   coalesce(al.[SignedByGECnt],0) [SignedByGECnt]
  880.                         --, 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]
  881.                         ,   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]
  882.                         ,   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]
  883.                         ,   coalesce(oa.BD1_Allocation__c2,1) [BD1_Allocation]
  884.                         ,   coalesce(oa.BD2_Allocation__c2,0) [BD2_Allocation]
  885.                         ,   coalesce(oa.BD3_Allocation__c2,0) [BD3_Allocation]
  886.                         ,   coalesce(oa.RD1_Allocation__c2,1) [RD1_Allocation]
  887.                         ,   coalesce(oa.RD2_Allocation__c2,0) [RD2_Allocation]
  888.                         --, coalesce(im.[IMFee],0) [Billed_Amount]
  889.                         ,   row_number() over(partition by m.[Client], replace(pg.[Description],'SALT','R&D') order by m.[Number]) [Rn]
  890.                         --, sum(coalesce(im.[IMFee],0)) over(partition by m.[Client], replace(pg.[Description],'SALT','R&D')) [TotalBilledClient]
  891.                         ,   sum(coalesce(ph.AdjWIP,0)) over(partition by m.[Client], replace(pg.[Description],'SALT','R&D') order by m.MattIndex) [SubtotalAdjWIPClient]
  892.                         --, coalesce(ar.[Reciept],0) [Fees_Collected]
  893.                         ,   coalesce(CASE WHEN pg.[Code] in ('110','120','130') and StudyCredit is not null and StudyCredit > 0    
  894.                                     then ar.[Reciept]*(PHCredit/StudyCredit) else ar.[Reciept] end,0) [Fees_Collected]
  895.                         ,   coalesce(tc.[WorkHrs],0) [Hours_Worked]
  896.                         ,   coalesce(tc.[WorkAmt],0) [WorkAmt]
  897.                         ,   coalesce(mp.[Pending_Invoices],0) [Pending_Invoices]
  898.                         ,   eu.[NxUnit]
  899.                         ,   case when bg.matter is not null then 1 else 0 end [BillingGroup]
  900.                         ,   coalesce(ortb.[Total_Invoiced],0) [R&D_Invoiced]
  901.                         ,   0 [R&D_Invoiced_Overrun]
  902.                         ,   coalesce(ortb.[Total_Invoiced],0) [R&D_TotalInvoiced]
  903.                         ,   coalesce(ortb.[Total_Invoiced],0) [ERC_Invoiced]
  904.                         ,   0 [ERC_Invoiced_Overrun]
  905.                         ,   coalesce(ortb.[Total_Invoiced],0) [ERC_TotalInvoiced]
  906.                         --, coalesce(ortb.[Total_Invoiced],0) [Total_Invoiced]
  907.                         ,   coalesce(CASE WHEN pg.[Code] in ('110','120','130') and StudyCredit is not null and StudyCredit > 0
  908.                                 then ortb.[Total_Invoiced]*(PHCredit/StudyCredit) else ortb.[Total_Invoiced] end,0) [Total_Invoiced]
  909.                         --, [tax_Year]
  910.                         , Case When MaxTaxYear> MinTaxYear then 'Multi' else 'Single' end [StudyYears]
  911.                         , m.IsEvergreen_CCC
  912.                         ,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]
  913.                         , Evergreen_2__c
  914.                         , COALESCE(MinTaxYear, year(
  915.                         --coalesce(o.Engagement_Letter_Signed_Date__c, m.[EngSignedDate_CCC], o.CloseDate))
  916.                         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
  917.                         WHEN m.[EngSignedDate_CCC]<=COALESCE(o.CloseDate,m.[EngSignedDate_CCC]) AND m.[EngSignedDate_CCC] is not null THEN m.[EngSignedDate_CCC]
  918.                         WHEN o.CloseDate IS not null THEN o.CloseDate
  919.                         ELSE coalesce(o.Engagement_Letter_Signed_Date__c, m.[EngSignedDate_CCC], o.CloseDate)
  920.                         END )
  921.                         ) MinTaxYear --MinTaxYear
  922.                         , MaxTaxYear
  923.                         , StudyYear
  924.                         , o.Fee_Cap_Percentage__c
  925.                         ,COALESCE(FeeCapPct,o.FeeCap) FeeCap
  926.                         , CASE WHEN ph.TimeStampFromYesterday > 0 THEN 1
  927.                                 WHEN m.TimeStamp > GETDATE()-1 THEN 1
  928.                                 WHEN c.TimeStamp > GETDATE()-1 THEN 1
  929.                                 WHEN eu.TimeStamp > GETDATE()-1 THEN 1
  930.                                 WHEN atk.TimeStamp > GETDATE()-1 THEN 1
  931.                                 WHEN MD.TimeStamp > GETDATE()-1 THEN 1
  932.                                 WHEN TC.TimeStamp > GETDATE()-1 THEN 1
  933.                             ELSE 1 /* force updates 0*/ END [TimeStampFromYesterday]
  934.                             ,o.Id
  935.                             ,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
  936.                             ,d.Mattindex dual
  937.                             ,FirstFU.Mattindex FirstFU
  938.                         from
  939.                             [TE_3E_PROD_CLONE].[dbo].[Matter] m
  940.                         LEFT JOIN
  941.                         (SELECT MAttindex,IsCloned_CCC
  942.                         FROM
  943.                         (
  944.                         SELECT
  945.                             LEAD(m.MattIndex,1)OVER(PARTITION BY OpportunityID_CCC,Client Order by OpenDate,m.Mattindex) MattIndex
  946.                         ,   1 IsCloned_CCC
  947.                         ,   LEAD(OpportunityID_CCC,1)OVER(PARTITION BY OpportunityID_CCC,Client Order by OpenDate,m.Mattindex) OpportunityID_CCC
  948.                         ,   LEAD(EngID_CCC,1)OVER(PARTITION BY OpportunityID_CCC,Client Order by OpenDate,m.Mattindex) EngID_CCC
  949.                         FROM
  950.                         TE_3E_PROD_Clone..Matter M
  951.                         LEFT JOIN (SELECT Mattindex FROM TE_3E_PROD_CLone..matter_audit WHERE IsEvergreen_CCC = 1 GROUP BY Mattindex) waseg on waseg.MAttindex = M.Mattindex
  952.                         WHERE IsEvergreen_CCC = 1 or waseg.MattIndex is not null
  953.                         ) a
  954.                         WHERE
  955.                         (IsCloned_CCC = 1 and OpportunityID_CCC != EngID_CCC and LEFT(EngID_CCC,2) != '00')
  956.                         OR (LEFT(OpportunityID_CCC,2) != '00')
  957.                         ) cloned on cloned.MAttindex = m.Mattindex
  958.                         LEFT JOIN
  959.                         #Duals d on d.Mattindex = m.MattIndex
  960.                         LEFT JOIN
  961.                         (
  962.                         SELECT MIN(MattINdex) Mattindex
  963.                         FROM
  964.                         TE_3E_PROD_Clone..Matter
  965.                         WHERE
  966.                         MattCategory = 'FU'
  967.                         AND
  968.                         OpportunityID_CCC is not null
  969.                         AND
  970.                         [IsEvergreen_CCC] = 1
  971.                         GROUP BY
  972.                         OpportunityID_CCC
  973.                         HAVING COUNT(Mattindex)>1
  974.                         ) FirstFU on FirstFU.Mattindex = m.MattIndex
  975.                         join
  976.                             [TE_3E_PROD_CLONE].[dbo].[Client] c on c.ClientIndex = m.Client
  977.                         left JOIN
  978.                             TE_3E_PROD_Clone..Site s on s.SiteIndex = c.InvoiceSite
  979.                         left JOIN
  980.                         TE_3E_PROD_Clone..address a on a.addrindex = s.address
  981.                         LEFT JOIN
  982.                             TE_3E_PROD_Clone..MajorIndustry_CCC mi on mi.Code = c.MajorIndustry_CCC
  983.                         left join
  984.                             (
  985.                                 select [Entity], [NxUnit], row_number() over(partition by [Entity] order by timestamp desc) [Rn]
  986.                                 , TimeStamp [TimeStamp]
  987.                                 from [TE_3E_PROD_CLONE].[dbo].[EntityUnit_CCC]
  988.                             ) eu on eu.[Entity] = c.[Entity] and eu.[Rn] = 1
  989.                         left join
  990.                             [TE_3E_PROD_CLONE].[dbo].[EngType_CCC] et on et.[Code] = m.[EngType_CCC]
  991.                         left join
  992.                             (
  993.                                 select
  994.                                     row_number() over (partition by [MatterLkUp] order by [EffStart] desc) [RN]
  995.                                 ,   [MatterLkUp]
  996.                                 ,   [TimeStamp]
  997.                                 ,   (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]
  998.                                 ,   (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]
  999.                                 ,   (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]
  1000.                                 ,   (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]
  1001.                                 ,   (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]
  1002.                                 from
  1003.                                     [TE_3E_PROD_CLONE].[dbo].[AssociatedTkprs_CCC] atk
  1004.                             ) atk on atk.[MatterLkUp] = m.[MattIndex] and atk.[rn] = 1
  1005.                         left join
  1006.                             (
  1007.                                 select
  1008.                                     row_number() over (partition by [matterlkup] order by [NxEndDate] desc, [NxStartDate] desc, [EffStart] desc) [rn]
  1009.                                 ,   [MatterLkUp]
  1010.                                 ,   [SpvTkpr]
  1011.                                 ,   [RspTkpr]
  1012.                                 ,   (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e where e.[3E_Source_TK_Id] = [SpvTkpr] and e.[SCDIsCurrent] = 1) [TD_ID]
  1013.                                 ,   (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e where e.[3E_Source_TK_Id] = [RspTkpr] and e.[SCDIsCurrent] = 1) [PM_ID]
  1014.                                 ,   [PracticeGroup]
  1015.                                 ,   [TimeStamp]
  1016.                                 from
  1017.                                     [TE_3E_PROD_CLONE].[dbo].[MattDate] md
  1018.                             ) MD on MD.[MatterLkUp] = M.[MattIndex] and md.[rn] = 1
  1019.                         left join
  1020.                             [TE_3E_PROD_CLONE].[dbo].[PracticeGroup] pg on pg.[Code] = md.[PracticeGroup]
  1021.                         left join
  1022.                             (
  1023.                                 select tc.[Matter], sum(tc.[WorkHrs]) [WorkHrs], sum(tc.[WorkAmt]) [WorkAmt], Max(TimeStamp) [TimeStamp]
  1024.                                 from [TE_3E_PROD_CLONE].[dbo].[Timecard] tc
  1025.                                 where tc.[IsActive] = 1
  1026.                                 group by tc.[Matter]
  1027.                             ) tc on tc.Matter = m.MattIndex
  1028.                         left join
  1029.                             (
  1030.                                     select
  1031.                                     [MattIndex]
  1032.                                 ,   [PGDetHdr_CCCID]
  1033.                                 ,   [AdjWIP]
  1034.                                 ,   [RemainingWIP]
  1035.                                 ,   [OrigWIP]
  1036.                                 ,   [EngSignedDate_CCC]
  1037.                                 ,   [EffStart]
  1038.                                 ,   [MaxTaxYear]
  1039.                                 , [MinTaxYear]
  1040.                                 ,   [TaxYearGreaterThanEL]
  1041.                                 ,   /*case
  1042.                                         when [OpportunityID_CCC] is null and [MattCategory] = 'FU' and [IsEvergreen_CCC] = 1 and [TaxYearGreaterThanEL] = 1
  1043.                                         then cast(cast([MaxTaxYear] + 1 as char(4)) + '0101' as datetime)
  1044.                                         else*/ [EngSignedDate_CCC]
  1045.                                         /*end*/ [SignedDate]
  1046.                                 ,   [Credit] [PHCredit]
  1047.                                 ,   [StudyCredit]
  1048.                                 ,   [VAERFN]
  1049.                                 ,   [VAERFNDeliveredCnt]
  1050.                                 ,   [TaxYearCnt]
  1051.                                 ,   [FutureTaxYearCnt]
  1052.                                 ,   [CurrentTaxYearCnt]
  1053.                                 --, case when [FutureTaxYearCnt] = 0 then 0 else [TaxYearCnt] / [FutureTaxYearCnt] end [FutureTaxYearPct]
  1054.                                 --, case when [CurrentTaxYearCnt] = 0 then 0 else [TaxYearCnt] / [CurrentTaxYearCnt] end [CurrentTaxYearPct]
  1055.                                 ,   case when [TaxYearCnt] = 0 then 0 else cast([FutureTaxYearCnt] as float) / cast([TaxYearCnt] as float) end [FutureTaxYearPct]  
  1056.                                 ,   case when [TaxYearCnt] = 0 then 0 else cast([CurrentTaxYearCnt] as float) / cast([TaxYearCnt] as float) end [CurrentTaxYearPct]
  1057.                                 ,   [FutureTaxYearTodayCnt]
  1058.                                 ,   [TimeStampFromYesterday]
  1059.                                 ,   [StudyYear]
  1060.                                 ,Id
  1061.                                 ,FeeCapPct
  1062.                                 from
  1063.                                 (
  1064.                                     select
  1065.                                         [MattIndex]
  1066.                                     ,   [EngSignedDate_CCC]
  1067.                                     ,   [MattCategory]
  1068.                                     ,   [IsEvergreen_CCC]
  1069.                                     ,   [OpportunityID_CCC]
  1070.                                     ,   [PGDetHdr_CCCID]
  1071.                                     ,   [AdjWIP]
  1072.                                     ,   [RemainingWIP]
  1073.                                     ,   [OrigWIP]
  1074.                                     ,   [EffStart]
  1075.                                     ,   [ELSigned]
  1076.                                     ,   max([Year]) [MaxTaxYear]
  1077.                                     ,   min([Year]) [MinTaxYear]
  1078.                                     ,   sum([TaxYearGreaterThanEL]) [TaxYearGreaterThanEL]
  1079.                                     ,   sum([Credit]) [Credit]
  1080.                                     ,   sum([VAERFN]) [VAERFN]
  1081.                                     ,   sum([VAERFNDeliveredCnt]) [VAERFNDeliveredCnt]
  1082.                                     ,   sum([TaxYearCnt]) [TaxYearCnt]
  1083.                                     ,   sum([FutureTaxYearCnt]) [FutureTaxYearCnt]
  1084.                                     ,   sum([CurrentTaxYearCnt]) [CurrentTaxYearCnt]
  1085.                                     ,   sum([FutureTaxYearTodayCnt]) [FutureTaxYearTodayCnt]
  1086.                                     ,   sum([TimeStampFromYesterday]) [TimeStampFromYesterday]
  1087.                                     ,   [StudyCredit]  
  1088.                                     --, CASE WHEN [PracticeGroup] in ('110','120','130') and  (pc.[YEAR] IS NULL OR pc.[YEAR] < Year([ELSigned])) Then 'PreviousYear'  
  1089.                                     --  WHEN [PracticeGroup] in ('110','120','130') and pc.[YEAR] = Year([ELSigned]) Then 'CurrentYear'
  1090.                                     --  WHEN [PracticeGroup] in ('110','120','130') and pc.[YEAR] > Year([ELSigned]) Then 'FutureYear' 
  1091.                                     --  Else NULL END 'StudyYear'
  1092.                                     ,CASE WHEN [PracticeGroup] in ('110','120','130')  
  1093.                                         THEN CASE WHEN pc.Year>YEAR(DATEADD(M,-pc.Month_CCC,pc.EngSignedDate_CCC)) THEN pc.Year -- 'FutureYear'    
  1094.                                                 --WHEN pc.Year=YEAR(DATEADD(M,-pc.Month_CCC,pc.EngSignedDate_CCC)) THEN 'CurrentYear'  
  1095.                                                 ELSE 0 END ELSE NULL END [StudyYear]
  1096.                                                 ,MAX(pc.Id) Id
  1097.                                                 ,FeeCapPct
  1098.                                     from
  1099.                                     (
  1100.                                         select
  1101.                                             m.MattIndex
  1102.                                         ,   m.[EngSignedDate_CCC]
  1103.                                         ,   m.[MattCategory]
  1104.                                         ,   m.Month_CCC
  1105.                                         ,   m.[IsEvergreen_CCC]
  1106.                                         ,   m.[OpportunityID_CCC]
  1107.                                         ,   ph.[MatterLkUp]
  1108.                                         ,   ph.[PGDetHdr_CCCID]
  1109.                                         ,   ph.[AdjWIP]
  1110.                                         ,   ph.[RemainingWIP]
  1111.                                         ,   ph.[OrigWIP]
  1112.                                         ,   ph.[EffStart]
  1113.                                         ,   coalesce(o.[Engagement_Letter_Signed_Date__c], m.[EngSignedDate_CCC], o.[CloseDate]) [ELSigned]
  1114.                                         ,   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(
  1115.                                                                         --coalesce(o.Engagement_Letter_Signed_Date__c, m.[EngSignedDate_CCC], o.CloseDate))
  1116.                                                                         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
  1117.                                                                         WHEN m.[EngSignedDate_CCC]<=COALESCE(o.CloseDate,m.[EngSignedDate_CCC]) AND m.[EngSignedDate_CCC] is not null THEN m.[EngSignedDate_CCC]
  1118.                                                                         WHEN o.CloseDate IS not null THEN o.CloseDate
  1119.                                                                         ELSE coalesce(o.Engagement_Letter_Signed_Date__c, m.[EngSignedDate_CCC], o.CloseDate)
  1120.                                                                         END )) [Year]
  1121.                                         ,   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]
  1122.                                         ,   sum(coalesce(pc.[TotalCredit], pc.[FinalCredit], pc.[EngineerReview], pc.[ValueAssessment], pc.[OrigCredit])) [Credit]
  1123.                                         ,   sum(coalesce(pcf.[TotalCredit], pcf.[FinalCredit], pcf.[EngineerReview], pcf.[ValueAssessment], pcf.[OrigCredit])) [StudyCredit]
  1124.                                         ,   sum(coalesce(pc.[FinalCredit], pc.[EngineerReview], pc.[ValueAssessment])) [VAERFN]
  1125.                                         ,   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]
  1126.                                         ,   coalesce(sum(case when pc.[Year] is not null then 1 end),0) [TaxYearCnt]
  1127.                                         ,   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]
  1128.                                         ,   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]
  1129.                                         ,   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]
  1130.                                         ,   md.PracticeGroup
  1131.                                         ,   coalesce(sum(case when m.TimeStamp  > GETDATE()-1 THEN 1
  1132.                                                               when ph.TimeStamp > GETDATE()-1 THEN 1
  1133.                                                               when md.TimeStamp > GETDATE()-1 THEN 1
  1134.                                                               when pc.TimeStamp > GETDATE()-1 THEN 1
  1135.                                                               ELSE 0 END),0) [TimeStampFromYesterday]
  1136.                                         ,o.Id
  1137.                                         ,FeeCapPct
  1138.                                         from
  1139.                                             [TE_3E_PROD_CLONE].[dbo].[Matter] m
  1140.                                             --left JOin [FP&App].bdm.BDMasterSource bd on bd.Number = m.Number COLLATE SQL_Latin1_General_CP1_CI_AS
  1141.                                         left join
  1142.                                             (
  1143.                                                 select
  1144.                                                     row_number() over (partition by [matterlkup] order by [NxEndDate] desc, [NxStartDate] , [EffStart] desc) [Rn]
  1145.                                                 ,   [PGDetHdr_CCCID]
  1146.                                                 ,   [MatterLkUp]
  1147.                                                 ,   [AdjWIP]
  1148.                                                 ,   [RemainingWIP]
  1149.                                                 ,   [OrigWIP]
  1150.                                                 ,   [EffStart]
  1151.                                                 ,   [TimeStamp]
  1152.                                                 ,   FeeCapPct/100 FeeCapPct
  1153.                                                 from
  1154.                                                     [TE_3E_PROD_CLONE].[dbo].[PGDetHdr_CCC]
  1155.                                             ) ph on ph.[MatterLkUp] = m.[MattIndex] and ph.[Rn] = 1
  1156.                                         left join
  1157.                                             (
  1158.                                                 select
  1159.                                                     row_number() over(partition by md.MatterLkUp order by md.effstart desc, md.nxStartDate , md.nxEndDate desc) [Rn]
  1160.                                                 ,   md.MatterLkUp
  1161.                                                 ,   md.[PracticeGroup]
  1162.                                                 , TimeStamp
  1163.                                                 from
  1164.                                                     TE_3E_PROD_Clone.dbo.MattDate md
  1165.                                             ) md on md.MatterLkUp = m.MattIndex and md.[Rn] = 1
  1166.                                         left join
  1167.                                             (
  1168.                                                 select
  1169.                                                     pc1.[PGDetHdr]
  1170.                                                 ,   [Year]
  1171.                                                 ,   sum(pc1.[OrigCredit])+SUM(COALESCE(adj.[OrigCredit],0)) [OrigCredit]
  1172.                                                 ,   sum(pc1.[ValueAssessment])+SUM(COALESCE(adj.[ValueAssessment],0)) [ValueAssessment]
  1173.                                                 ,   sum(pc1.[EngineerReview])+SUM(COALESCE(adj.[EngineerReview],0)) [EngineerReview]
  1174.                                                 ,   sum(pc1.[FinalCredit])+SUM(COALESCE(adj.[FinalCredit],0)) [FinalCredit]
  1175.                                                 ,   sum(pc1.[Total])+SUM(COALESCE(adj.[Total],0)) [TotalCredit]
  1176.                                                 , MAX(timestamp) [TimeStamp]
  1177.                                                 from
  1178.                                                     [TE_3E_PROD_CLONE].[dbo].[PGDetChild_CCC] pc1
  1179.                                                 LEFT JOIN
  1180.                                                     (SELECT [PGDetHdr]
  1181.                                                     ,SUM(CASE WHEN year is null THEN [OrigCredit] ELSE 0 END)/NULLIF(COUNT(CASE WHEN year is not null THEN [OrigCredit]  END),0)[OrigCredit]
  1182.                                                     ,SUM(CASE WHEN year is null THEN [ValueAssessment] ELSE 0 END)/NULLIF(COUNT(CASE WHEN year is not null THEN [ValueAssessment]  END),0)[ValueAssessment]
  1183.                                                     ,SUM(CASE WHEN year is null THEN [EngineerReview] ELSE 0 END)/NULLIF(COUNT(CASE WHEN year is not null THEN [EngineerReview]  END),0)[EngineerReview]
  1184.                                                     ,SUM(CASE WHEN year is null THEN [FinalCredit] ELSE 0 END)/NULLIF(COUNT(CASE WHEN year is not null THEN [FinalCredit]  END),0)[FinalCredit]
  1185.                                                     ,SUM(CASE WHEN year is null THEN [Total] ELSE 0 END)/NULLIF(COUNT(CASE WHEN year is not null THEN [Total]  END),0)[Total]
  1186.                                                     FROM
  1187.                                                         [TE_3E_PROD_CLONE].[dbo].[PGDetChild_CCC]
  1188.                                                         GROUP BY [PGDetHdr]) adj on adj.PGDetHdr = pc1.PGDetHdr
  1189.                                                 where COALESCE(pc1.IsGeneralWork,0)  = 0 and pc1.year is not null
  1190.                                                 group by
  1191.                                                     pc1.[PGDetHdr]
  1192.                                                 ,   [Year]
  1193.                                             ) pc on pc.[PGDetHdr] = ph.[PGDetHdr_CCCID]
  1194.                                             left join  
  1195.                                             (  
  1196.                                                 select 
  1197.                                                     [PGDetHdr] 
  1198.                                                 ,   sum([OrigCredit]) [OrigCredit] 
  1199.                                                 ,   sum([ValueAssessment]) [ValueAssessment]   
  1200.                                                 ,   sum([EngineerReview]) [EngineerReview] 
  1201.                                                 ,   sum([FinalCredit]) [FinalCredit]   
  1202.                                                 ,   sum([Total]) [TotalCredit]
  1203.                                                 , MAX(timestamp) [TimeStamp]   
  1204.                                                 from   
  1205.                                                     [TE_3E_PROD_CLONE].[dbo].[PGDetChild_CCC] where COALESCE(IsGeneralWork,0)  = 0--where [Year] is not null   
  1206.                                                 group by   
  1207.                                                     [PGDetHdr] 
  1208.                                             ) pcf on pcf.[PGDetHdr] = ph.[PGDetHdr_CCCID]  
  1209.                                         left join
  1210.                                             [SalesforceClone].[dbo].[Opportunity] o on o.[ID] = m.[OpportunityID_CCC] collate SQL_Latin1_General_CP1_CI_AS
  1211.                                         --where LEFT(m.Number,6) = '313717'
  1212.                                         group by
  1213.                                             m.MattIndex
  1214.                                         ,   m.[EngSignedDate_CCC]
  1215.                                         ,   m.[MattCategory]
  1216.                                         ,   m.Month_CCC
  1217.                                         ,   m.[IsEvergreen_CCC]
  1218.                                         ,   m.[OpportunityID_CCC]
  1219.                                         ,   ph.[MatterLkUp]
  1220.                                         ,   ph.[PGDetHdr_CCCID]
  1221.                                         ,   ph.[AdjWIP]
  1222.                                         ,   ph.[RemainingWIP]
  1223.                                         ,   ph.[OrigWIP]
  1224.                                         ,   ph.[EffStart]
  1225.                                         ,   coalesce(o.[Engagement_Letter_Signed_Date__c], m.[EngSignedDate_CCC], o.[CloseDate])
  1226.                                         ,   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(
  1227.                                                                         --coalesce(o.Engagement_Letter_Signed_Date__c, m.[EngSignedDate_CCC], o.CloseDate))
  1228.                                                                         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
  1229.                                                                         WHEN m.[EngSignedDate_CCC]<=COALESCE(o.CloseDate,m.[EngSignedDate_CCC]) AND m.[EngSignedDate_CCC] is not null THEN m.[EngSignedDate_CCC]
  1230.                                                                         WHEN o.CloseDate IS not null THEN o.CloseDate
  1231.                                                                         ELSE coalesce(o.Engagement_Letter_Signed_Date__c, m.[EngSignedDate_CCC], o.CloseDate)
  1232.                                                                         END ))  --pc.[Year]
  1233.                                         ,   md.PracticeGroup
  1234.                                         ,o.id
  1235.                                         ,FeeCapPct
  1236.                                     ) pc
  1237.                                     group by
  1238.                                         MattIndex
  1239.                                     ,   [EngSignedDate_CCC]
  1240.                                     ,   [MattCategory]
  1241.                                     ,   [IsEvergreen_CCC]
  1242.                                     ,   [OpportunityID_CCC]
  1243.                                     ,   [PGDetHdr_CCCID]
  1244.                                     ,   [AdjWIP]
  1245.                                     ,   [RemainingWIP]
  1246.                                     ,   [OrigWIP]
  1247.                                     ,   [EffStart]
  1248.                                     ,   [ELSigned]
  1249.                                     ,   [StudyCredit]  
  1250.                                     --, CASE WHEN [PracticeGroup] in ('110','120','130') and  (pc.[YEAR] IS NULL OR pc.[YEAR] < Year([ELSigned])) Then 'PreviousYear'  
  1251.                                     --  WHEN [PracticeGroup] in ('110','120','130') and pc.[YEAR] = Year([ELSigned]) Then 'CurrentYear'
  1252.                                     --  WHEN [PracticeGroup] in ('110','120','130') and pc.[YEAR] > Year([ELSigned]) Then 'FutureYear' 
  1253.                                     --  Else NULL END
  1254.                                     ,CASE WHEN [PracticeGroup] in ('110','120','130')  
  1255.                                         THEN CASE WHEN pc.Year>YEAR(DATEADD(M,-pc.Month_CCC,pc.EngSignedDate_CCC)) THEN  pc.Year  --'FutureYear'   
  1256.                                                 --WHEN pc.Year=YEAR(DATEADD(M,-pc.Month_CCC,pc.EngSignedDate_CCC)) THEN 'CurrentYear'  
  1257.                                                 ELSE 0 END ELSE NULL END
  1258.                                                 ,FeeCapPct
  1259.                                                
  1260.                                 ) a
  1261.                             ) ph on ph.[MattIndex] = M.[MattIndex]
  1262.                         left join
  1263.                             (
  1264.                                 select
  1265.                                     ptm.[fileID]
  1266.                                 ,   f.[fileAccCode]
  1267.                                 ,   feqc.[feeExtID]
  1268.                                 ,   ptm.[projectrole]
  1269.                                 ,   ptm.[isPrimary]
  1270.                                 ,   (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e where e.[3E_Source_TK_Id] = feqc.[feeExtID] and e.[SCDIsCurrent] = 1) [QC_ID]
  1271.                                 ,   row_number() over (partition by ptm.[fileID] order by ptm.[isPrimary] desc) [Rn]
  1272.                                 from
  1273.                                     [MS_LIVE_Clone].[dbo].[udFiProjectTeam] ptm
  1274.                                 left join
  1275.                                     [MS_LIVE_Clone].[config].[dbFile] f on ptm.[fileID] = f.[fileID]
  1276.                                 left join
  1277.                                     [MS_LIVE_Clone].[dbo].[dbFeeEarner] FEQC on FEQC.[feeusrID] = ptm.[employee]
  1278.                                 where
  1279.                                     ptm.[projectRole] = 'QC'
  1280.                                     and f.[fileAccCode] is not null
  1281.                             ) qc on qc.[fileAccCode] = m.[MattIndex] and qc.[rn] = 1
  1282.                         left join
  1283.                             (
  1284.                                 select
  1285.                                     [Opportunity__c]
  1286.                                 ,   case when [BD1_Allocation__c] > 1 then [BD1_Allocation__c] / 100 else [BD1_Allocation__c] end [BD1_Allocation__c2]
  1287.                                 ,   case when [BD2_Allocation__c] > 1 then [BD2_Allocation__c] / 100 else [BD2_Allocation__c] end [BD2_Allocation__c2]
  1288.                                 ,   case when [BD3_Allocation__c] > 1 then [BD3_Allocation__c] / 100 else [BD3_Allocation__c] end [BD3_Allocation__c2]
  1289.                                 ,   case when [RD1_Allocation__c] > 1 then [RD1_Allocation__c] / 100 else [RD1_Allocation__c] end [RD1_Allocation__c2]
  1290.                                 ,   case when [RD2_Allocation__c] > 1 then [RD2_Allocation__c] / 100 else [RD2_Allocation__c] end [RD2_Allocation__c2]
  1291.                                 ,   row_number() over(partition by [Opportunity__C] order by lastmodifiedDate desc) [Rn]
  1292.                                 from
  1293.                                     [SalesforceClone].[dbo].[Opportunity_Analytics__c]
  1294.                             ) OA on OA.[Opportunity__c] = M.[OpportunityID_CCC] collate SQL_Latin1_General_CP1_CI_AS and oa.Rn = 1
  1295.                         left join
  1296.                             (
  1297.                                 select
  1298.                                     o.[Id]
  1299.                                 ,   o.[Engagement_Letter_Signed_Date__c]
  1300.                                 ,   o.[CloseDate]
  1301.                                 ,   o.[Amount]
  1302.                                 ,   o.[Type]
  1303.                                 ,   o.[Fee_Cap_Percentage__c]
  1304.                                 ,(CASE 
  1305.                                         WHEN o.[Fee_Cap_Percentage__c] is not null then o.[Fee_Cap_Percentage__c]  
  1306.                                         WHEN o.[Fee_Cap_Percentage_Gross__c] is not null then o.[Fee_Cap_Percentage_Gross__c]  
  1307.                                         ELSE o.[Fee_Cap_Percentage_Input__c]   
  1308.                                         END) / 100 [FeeCap]
  1309.                                 ,   case
  1310.                                         when o.[Amount] is null or o.[Fee_Cap_Percentage__c] is null then null
  1311.                                         when o.[Amount] = 0 or o.[Fee_Cap_Percentage__c] = 0 then 0
  1312.                                         else o.[Amount] / (o.[Fee_Cap_Percentage__c] / 100)
  1313.                                         end [Credit]
  1314.                                 ,   (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e
  1315.                                         left join [MS_LIVE_Clone].[dbo].dbFeeEarner msfe on msfe.feeExtID = e.[3E_Source_TK_Id]
  1316.                                         left join [MS_LIVE_Clone].[dbo].dbUser msu on msu.usrID = msfe.feeusrID
  1317.                                         left join [SalesforceClone].[dbo].[User] u on u.email = msu.usrEmail
  1318.                                         where u.id = o.OwnerId and e.[SCDIsCurrent] = 1
  1319.                                         order by e.SF_Source_id desc) [BD1_TKID]
  1320.                                 ,   (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e
  1321.                                         left join [MS_LIVE_Clone].[dbo].dbFeeEarner msfe on msfe.feeExtID = e.[3E_Source_TK_Id]
  1322.                                         left join [MS_LIVE_Clone].[dbo].dbUser msu on msu.usrID = msfe.feeusrID
  1323.                                         left join [SalesforceClone].[dbo].[User] u on u.email = msu.usrEmail
  1324.                                         where u.id = o.Primary_Director_Name__c and e.[SCDIsCurrent] = 1
  1325.                                         order by e.SF_Source_id desc) [BD2_TKID]
  1326.                                 ,   (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e
  1327.                                         left join [MS_LIVE_Clone].[dbo].dbFeeEarner msfe on msfe.feeExtID = e.[3E_Source_TK_Id]
  1328.                                         left join [MS_LIVE_Clone].[dbo].dbUser msu on msu.usrID = msfe.feeusrID
  1329.                                         left join [SalesforceClone].[dbo].[User] u on u.email = msu.usrEmail
  1330.                                         where u.id = o.Primary_Relationship_Director__c and e.[SCDIsCurrent] = 1
  1331.                                         order by e.SF_Source_id desc) [SOE1_TKID]
  1332.                                 ,   (select top 1 [EmployeeId] from [Rubix].[dim].[Employee] e
  1333.                                         left join [MS_LIVE_Clone].[dbo].[dbFeeEarner] msfe on msfe.[feeExtID] = e.[3E_Source_TK_Id]
  1334.                                         left join [MS_LIVE_Clone].[dbo].[dbUser] msu on msu.[usrID] = msfe.[feeusrID]
  1335.                                         left join [SalesforceClone].[dbo].[User] u on u.[email] = msu.[usrEmail]
  1336.                                         where u.[id] = o.[X2nd_Relationship_Director__c] and e.[SCDIsCurrent] = 1
  1337.                                         order by e.[SF_Source_id] desc) [SOE2_TKID]
  1338.                                 ,o.Evergreen_2__c
  1339.                                 from
  1340.                                     [SalesforceClone].[dbo].[Opportunity] o
  1341.                                 where
  1342.                                     coalesce(o.ag_Company__c,'') != 'ForrestBrown'
  1343.                             ) o on o.[ID] = m.[OpportunityID_CCC] collate SQL_Latin1_General_CP1_CI_AS
  1344.                             left join
  1345.                             (
  1346.                                 --select
  1347.                                 --  Matter
  1348.                                 --, sum([BillAmt]) [Total_Invoiced]
  1349.                                 --from
  1350.                                 --[TE_3E_PROD_Clone].[dbo].[TimeBill] TB
  1351.                                 --JOIN
  1352.                                 --[TE_3E_PROD_Clone].[dbo].[Timecard] TC on tc.TimeIndex = TB.TimeCard  and TC.IsActive = 1 and LoadSource != 'Recon'
  1353.                                 --group by
  1354.                                 --  Matter
  1355.                                 SELECT Number,BilledSplit Total_Invoiced,[MinYear]
  1356.                                 FROM
  1357.                                 [FP&A].BDM.BDMasterMatterBilledCollected
  1358.                             ) ortb on ortb.Number = m.Number COLLATE SQL_Latin1_General_CP1_CI_AS and ortb.[MinYear] = ph.MinTaxYear
  1359.                         --left join
  1360.                         --  (
  1361.                         --      select [leadmatter], sum(orgfee) IMFee
  1362.                         --      , MAX(timestamp) [TimeStamp]
  1363.                         --      from [TE_3E_PROD_Clone].[dbo].[InvMaster]
  1364.                         --      where [IsReversed] = 0
  1365.                         --      group by [leadmatter]
  1366.                         --  ) im on im.LeadMatter = m.MattIndex
  1367.                         left join
  1368.                             [TE_3E_PROD_Clone].dbo.[BillingGroupMatter] bg on bg.Matter = m.MattIndex
  1369.                         left join
  1370.                             (
  1371.                                 select
  1372.                                     [Matter]
  1373.                                 ,   coalesce(sum(case when [ARAmt] > 0 and [IsReversed] = 0 then [ARFee] end),0) [ARFee]
  1374.                                 ,   coalesce(sum(case when [IsCollection] = 1 then -[ARfee] end),0) [Reciept]
  1375.                                 , MAX(timestamp) [TimeStamp]
  1376.                                 from
  1377.                                     [TE_3E_PROD_Clone].dbo.[ARMaster]
  1378.                                 group by
  1379.                                     [Matter]
  1380.                             ) ar on ar.Matter = m.MattIndex
  1381.                         left join
  1382.                             (
  1383.                                 select [leadmatter], coalesce(sum([TotAmt]),0) [Pending_Invoices]
  1384.                                 , MAX(pm.timestamp) [Timestamp]
  1385.                                 from [TE_3E_PROD_Clone].[dbo].[ProfMaster] pm
  1386.                                 join [TE_3E_PROD_Clone].[dbo].[Matter] m on m.[MattIndex] = pm.[LeadMatter]
  1387.                                 where [invmaster] is null and [profstatus] = 'Current'
  1388.                                 group by [leadmatter]
  1389.                             ) MP on MP.[leadmatter] = M.[MattIndex]
  1390.                         left join
  1391.                             (
  1392.                                 select f.[fileExtLinkID], count(al.[AlStatus]) [SignedByGECnt]
  1393.                                 from [MS_LIVE_Clone].[dbo].[udAllocationLetter] al
  1394.                                 join [MS_LIVE_Clone].[config].[dbfile] f on f.fileID = al.fileID
  1395.                                 where al.[AlStatus] = 6
  1396.                                 group by f.[fileExtLinkID]
  1397.                             ) al on al.[fileExtLinkID] = m.[MattIndex]
  1398.                     --where LEFT(m.Number,6) = '313717'
  1399.                         --coalesce(o.[Engagement_Letter_Signed_Date__c], m.[EngSignedDate_CCC], o.[CloseDate]) >= '1/1/2020'
  1400.                 ) ma)ma
  1401.         ) m
  1402.         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  
  1403.         Left JOIN Rubix.dim.Employee bd1 on bd1.EmployeeId = m.BD1_ID
  1404.         Left JOIN Rubix.dim.Employee bd2 on bd2.EmployeeId = m.BD2_ID
  1405.         Left JOIN Rubix.dim.Employee SOE1 on SOE1.EmployeeId = m.SOE_1_ID
  1406.         Left JOIN Rubix.dim.Employee SOE2 on SOE2.EmployeeId = m.SOE_2_ID
  1407.         Left JOIN Rubix.dim.Employee PM on PM.EmployeeId = m.PM_ID
  1408.     ) a
  1409.  
  1410. order by
  1411.     a.[OriginalSignedDate]
  1412.  
  1413.  
  1414. --select * from #bdmMatterInfo
  1415. --where Number = '009810.0011'
  1416.  
  1417.  
  1418. IF EXISTS (select count(*) from #bdmMatterInfo)
  1419. BEGIN
  1420.     truncate table  BDM.BDMasterMatterDataFrom3E
  1421.  
  1422.     Insert into BDM.BDMasterMatterDataFrom3E (
  1423.     [OpportunityID_CCC] ,
  1424.     [Number] ,
  1425.     [MattIndex] ,
  1426.     [AltNumber] ,
  1427.     [DisplayName] ,
  1428.     [Description] ,
  1429.     [Client] ,
  1430.     [ClientId] ,
  1431.     [CloseDate] ,
  1432.     [Currency] ,
  1433.     [IsEvergreenCCC] ,
  1434.     [ServiceLine] ,
  1435.     [State] ,
  1436.     [EngSignedDateCCC] ,
  1437.     [BD1ID] ,
  1438.     [BD2ID] ,
  1439.     [BD3ID] ,
  1440.     [SOE1ID] ,
  1441.     [SOE2ID] ,
  1442.     [QCID] ,
  1443.     [TDID] ,
  1444.     [PMID] ,
  1445.     [PBD] ,
  1446.     [SBD] ,
  1447.     [PRD] ,
  1448.     [SRD] ,
  1449.     [PM] ,
  1450.     [OriginalWIP] ,
  1451.     [Collected] ,
  1452.     [Credit] ,
  1453.     [Billed] ,
  1454.     [WorkedWIP] ,
  1455.     [PendingInvoices] ,
  1456.     [TotalWIP] ,
  1457.     [Hours_Worked] ,
  1458.     [RemainingWIP] ,
  1459.     [AdjustedWIP] ,
  1460.     [UpdatedWIP],
  1461.     [UnbilledWIP] ,
  1462.     [UnbilledWorkedWIP] ,
  1463.     [Balance] ,
  1464.     [UnworkedUnbilled] ,
  1465.     [BD1Allocation] ,
  1466.     [BD2Allocation] ,
  1467.     [BD3Allocation] ,
  1468.     [RD1Allocation] ,
  1469.     [RD2Allocation] ,
  1470.     [BD1OrgWIPAlloc] ,
  1471.     [BD2OrgWIPAlloc] ,
  1472.     [BD3OrgWIPAlloc] ,
  1473.     [RD1OrgWIPAlloc] ,
  1474.     [RD2OrgWIPAlloc] ,
  1475.     [BD1AdjWIPAlloc] ,
  1476.     [BD2AdjWIPAlloc] ,
  1477.     [BD3AdjWIPAlloc] ,
  1478.     [RD1AdjWIPAlloc] ,
  1479.     [RD2AdjWIPAlloc] ,
  1480.     [BD1FeesBilled] ,
  1481.     [BD2FeesBilled] ,
  1482.     [BD3FeesBilled] ,
  1483.     [RD1FeesBilled] ,
  1484.     [RD2FeesBilled] ,
  1485.     [BD1FeesCollected] ,
  1486.     [BD2FeesCollected] ,
  1487.     [BD3FeesCollected] ,
  1488.     [RD1FeesCollected] ,
  1489.     [RD2FeesCollected] ,
  1490.     [OriginalSignedDate] ,
  1491.     [VAERFNDeliveredCnt] ,
  1492.     [StudyYears] ,
  1493.     [MajorIndustry] ,
  1494.     [Code] ,
  1495.     [MattStatus] ,
  1496.     [MattCategory] ,
  1497.     [EngTypeCCC] ,
  1498.     [EngStatusCCC],
  1499.     [MinYear],
  1500.     [MaxYear],
  1501.      [1TimeAdj],
  1502.      [StudyYear],
  1503.     [RecordForUpdate],
  1504.     IsCloned_CCC)
  1505.     (SELECT DISTINCT [OpportunityID_CCC] ,
  1506.     [Number] ,
  1507.     [MattIndex] ,
  1508.     [AltNumber] ,
  1509.     [DisplayName] ,
  1510.     [Description] ,
  1511.     [Client] ,
  1512.     [ClientId] ,
  1513.     [CloseDate] ,
  1514.     [Currency] ,
  1515.     [IsEvergreenCCC] ,
  1516.     [ServiceLine] ,
  1517.     [State] ,
  1518.     [EngSignedDateCCC] ,
  1519.     [BD1ID] ,
  1520.     [BD2ID] ,
  1521.     [BD3ID] ,
  1522.     [SOE1ID] ,
  1523.     [SOE2ID] ,
  1524.     [QCID] ,
  1525.     [TDID] ,
  1526.     [PMID] ,
  1527.     [PBD] ,
  1528.     [SBD] ,
  1529.     [PRD] ,
  1530.     [SRD] ,
  1531.     [PM] ,
  1532.     [OriginalWIP] ,
  1533.     [Collected] ,
  1534.     [Credit] ,
  1535.     [Billed] ,
  1536.     [WorkedWIP] ,
  1537.     [PendingInvoices] ,
  1538.     [TotalWIP] ,
  1539.     [HoursWorked] ,
  1540.     [RemainingWIP] ,
  1541.     [AdjustedWIP] ,
  1542.     [UpdatedWIP],
  1543.     [UnbilledWIP] ,
  1544.     [UnbilledWorkedWIP] ,
  1545.     [Balance] ,
  1546.     [UnworkedUnbilled] ,
  1547.     [BD1Allocation] ,
  1548.     [BD2Allocation] ,
  1549.     [BD3Allocation] ,
  1550.     [RD1Allocation] ,
  1551.     [RD2Allocation] ,
  1552.     [BD1OrgWIPAlloc] ,
  1553.     [BD2OrgWIPAlloc] ,
  1554.     [BD3OrgWIPAlloc] ,
  1555.     [RD1OrgWIPAlloc] ,
  1556.     [RD2OrgWIPAlloc] ,
  1557.     [BD1AdjWIPAlloc] ,
  1558.     [BD2AdjWIPAlloc] ,
  1559.     [BD3AdjWIPAlloc] ,
  1560.     [RD1AdjWIPAlloc] ,
  1561.     [RD2AdjWIPAlloc] ,
  1562.     [BD1FeesBilled] ,
  1563.     [BD2FeesBilled] ,
  1564.     [BD3FeesBilled] ,
  1565.     [RD1FeesBilled] ,
  1566.     [RD2FeesBilled] ,
  1567.     [BD1FeesCollected] ,
  1568.     [BD2FeesCollected] ,
  1569.     [BD3FeesCollected] ,
  1570.     [RD1FeesCollected] ,
  1571.     [RD2FeesCollected] ,
  1572.     [OriginalSignedDate] ,
  1573.     [VAERFNDeliveredCnt] ,
  1574.     [StudyYears] ,
  1575.     [MajorIndustry] ,
  1576.     [Code] ,
  1577.     [MattStatus] ,
  1578.     [MattCategory] ,
  1579.     [EngTypeCCC] ,
  1580.     [EngStatusCCC],
  1581.     [MinTaxYear],
  1582.     [MaxTaxYear],
  1583.     [1TimeAdj],
  1584.     [StudyYear],
  1585.     [RecordForUpdate],
  1586.     IsCloned_CCC
  1587.     from #bdmMatterInfo)
  1588. END
  1589. END
  1590. GO
  1591.  
  1592.  
  1593. --Step 4
  1594.  
  1595.  
  1596. USE [FP&A]
  1597. GO
  1598.  
  1599. /****** Object:  StoredProcedure [BDM].[GETBDMasterSource]    Script Date: 2/6/2025 10:25:49 AM ******/
  1600. SET ANSI_NULLS ON
  1601. GO
  1602.  
  1603. SET QUOTED_IDENTIFIER ON
  1604. GO
  1605.  
  1606.  
  1607. CREATE PROCEDURE [BDM].[GETBDMasterSource]
  1608. AS BEGIN
  1609. --SET NOCOUNT ON
  1610.  -- Getting the latest logId from Log table
  1611.     Declare @LogId int, @LogSql nvarchar(100)
  1612.     SET @LogSql = 'SELECT TOP 1 @LogId = Id from [bdm].[BDMasterSource_Log] order by StartTime desc'
  1613.     EXEC sp_executesql @LogSql, N'@LogId int OUTPUT', @LogId = @LogId OUTPUT
  1614.     if(@LogId is null)
  1615.     begin
  1616.         SET @LogId = 0
  1617.     end
  1618.     SET @LogId = @LogId + 1;           
  1619.     exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'ETL process starts'
  1620.  
  1621. --Getting the Opportunities from Salesforce which are Closed
  1622. if object_id('tempdb.dbo.#bdmoppstg','U') is not null
  1623. drop table #bdmoppstg;
  1624.  
  1625. select
  1626.         o.[Id]
  1627.     ,   o.[Name]
  1628.     ,   o.[StageName]
  1629.     ,   o.[CloseDate]
  1630.     ,   o.[Project_Name__c]
  1631.     ,   o.[Amount]
  1632.     ,   o.[Type]
  1633.     ,   o.[Service_Type__c]
  1634.     ,   case
  1635.             when o.[Service_Type__c] in ('R&D','179D') and o.[StageName] in ('Closed - Study in Process') then 1
  1636.             else 0
  1637.             end [Splitflag]
  1638.     ,   cast(o.[Engagement_Letter_Signed_Date__c] as date) [ELSignedDate]
  1639.     ,   o.[Years_Under_Study_Federal__c]
  1640.     ,   o.[Years_Under_Study_State__c]
  1641.     ,   o.[States__c]
  1642.     ,   o.[Fiscal_Year_End_2__c]
  1643.     into #bdmoppstg
  1644.     from
  1645.         [SalesforceClone].[dbo].[Opportunity] o
  1646.     where id <> '0064000000FtxLnAAJ'
  1647.     and (([Final_Intake_Created_By__c] is not null  and [Final_Intake_Created_By__c] not like '%Bhavesh Zaveri%') or Stagename like 'Closed%')
  1648.         --o.[StageName] like 'Closed%' and id <> '0064000000FtxLnAAJ'
  1649.         --and  (o.Years_Under_Study_Federal__c like '%?%' OR o.Years_Under_Study_State__c like '%?%')
  1650.         --and o.CloseDate >= '01/01/2020'
  1651.        
  1652. --Evaluating Federal or State year to get the Year for Opportunity
  1653. if object_id('tempdb.dbo.#bdmoppyearsstg','U') is not null
  1654. drop table #bdmoppyearsstg;
  1655.  
  1656. select
  1657.         o.[Id]
  1658.     ,   a.data [Year]
  1659.     into #bdmoppyearsstg
  1660.     from
  1661.         #bdmoppstg o
  1662.     cross apply
  1663.         [SalesforceClone].[dbo].[fStrtoTable]
  1664.         (
  1665.             case
  1666.                 when o.[Years_Under_Study_Federal__c] is null then o.[Years_Under_Study_State__c]
  1667.                 when o.[Years_Under_Study_State__c] is null then o.[Years_Under_Study_Federal__c]
  1668.                 else concat(o.[Years_Under_Study_Federal__c],';',o.[Years_Under_Study_State__c])
  1669.                 end
  1670.         , ';') a
  1671.     where
  1672.         [Splitflag] = 1
  1673.     group by
  1674.         o.[Id]
  1675.     ,   a.data
  1676.  
  1677. --Getting Federal Year only
  1678. if object_id('tempdb.dbo.#bdmoppFEDYears','U') is not null
  1679. drop table #bdmoppFEDYears;
  1680. select
  1681.         o.[Id]
  1682.     ,   a.Data [FEDYear]
  1683.     into #bdmoppFEDYears
  1684.     from
  1685.         #bdmoppstg o
  1686.     cross apply
  1687.         [SalesforceClone].[dbo].[fStrtoTable]([Years_Under_Study_Federal__c], ';') a
  1688.     where
  1689.         [Splitflag] = 1
  1690.  
  1691. --Getting State year only
  1692. if object_id('tempdb.dbo.#bdmoppStateYears','U') is not null
  1693. drop table #bdmoppStateYears;
  1694.  
  1695.     select
  1696.         o.[Id]
  1697.     ,   a.[Data] [StateYear]
  1698.     into #bdmoppStateYears
  1699.     from
  1700.         #bdmoppstg o
  1701.     cross apply
  1702.         [SalesforceClone].[dbo].[fStrtoTable]([Years_Under_Study_State__c], ';') a
  1703.     where
  1704.         [Splitflag] = 1
  1705. ;
  1706.  
  1707. --Getting final year based on Federal year or State year.
  1708. if object_id('tempdb.dbo.#bdmoppyears','U') is not null
  1709. drop table #bdmoppyears;
  1710.  
  1711.     select
  1712.         o.[Id]
  1713.     ,   o.[Name]
  1714.     ,   o.[StageName]
  1715.     ,   o.[CloseDate]
  1716.     ,   o.[Project_Name__c]
  1717.     ,   o.[Amount]
  1718.     ,   opp.[Year]
  1719.     ,   ofy.[FEDYear]
  1720.     ,   osy.[StateYear]
  1721.     ,   o.[Service_Type__c]
  1722.     ,   o.[Type]
  1723.     ,   o.[Splitflag]
  1724.     ,   o.[ELSignedDate]
  1725.     ,   o.[Years_Under_Study_Federal__c]
  1726.     ,   o.[Years_Under_Study_State__c]
  1727.     ,   o.[States__c]
  1728.     --, case
  1729.     --      when opp.[Year] < year(o.[ELSignedDate]) then 1
  1730.     --      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
  1731.     --      end [OppRn]
  1732.     --, case
  1733.     --      when opp.[Year] < year(o.[ELSignedDate]) -1 then 1
  1734.     --      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
  1735.     --      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
  1736.     --      else row_number() over(partition by o.[Id]
  1737.     --              , case when opp.[Year] >= year(o.[ELSignedDate])  then 2
  1738.     --                          when opp.[Year] >= year(o.[ELSignedDate]) then 3 else 1 end order by opp.[Year]) + 2
  1739.     --      end [OppRn]
  1740.     , case when o.Fiscal_Year_End_2__c is null
  1741.             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
  1742.         when CAST (COALESCE(LEFT(o.Fiscal_Year_End_2__c,CHARINDEX('/',o.Fiscal_Year_End_2__c)-1),12) as INT) = 12
  1743.         THEN
  1744.             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)
  1745.         else 1 END  
  1746.         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)
  1747.         --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)
  1748.         else 1 END END [OppRn]
  1749.     ,   row_number() over(partition by o.[Id] order by opp.[Year]) [OppYearRn]
  1750.     into #bdmoppyears
  1751.     from
  1752.         #bdmoppstg o
  1753.     left join
  1754.         #bdmoppyearsstg opp on opp.[Id] = o.[Id]
  1755.     left join
  1756.         #bdmoppFEDYears ofy on ofy.[Id] = o.[Id] and ofy.[FEDYear] = opp.[Year]
  1757.     left join
  1758.         #bdmoppStateYears osy on osy.[Id] = o.[Id] and osy.[StateYear] = opp.[Year]
  1759. ;
  1760.  
  1761. --Finalizing data
  1762. if object_id('tempdb.dbo.#bdmoppfinalstg','U') is not null
  1763. drop table #bdmoppfinalstg;
  1764.  
  1765.     select
  1766.         o.[Id]
  1767.     ,   o.[Name]
  1768.     ,   o.[StageName]
  1769.     ,   o.[CloseDate]
  1770.     ,   o.[Project_Name__c]
  1771.     ,   o.[Amount]
  1772.     ,   o.[Service_Type__c]
  1773.     ,   o.[Type]
  1774.     ,   o.[Splitflag]
  1775.     ,   o.[ELSignedDate]
  1776.     ,   o.[Years_Under_Study_Federal__c]
  1777.     ,   o.[Years_Under_Study_State__c]
  1778.     ,   o.[States__c]
  1779.     ,   o.[OppRn]
  1780.     ,   substring
  1781.         (
  1782.             (
  1783.                 select ';' + ob.[FEDYear] [text()]
  1784.                 from #bdmoppyears ob
  1785.                 where ob.[Id] = o.[Id] and ob.[OppRn] = o.[OppRn]
  1786.                 order by ob.[Id], ob.[OppRn]
  1787.                 for xml path ('')
  1788.             ), 2, 1000
  1789.         ) [FEDYear]
  1790.     ,   substring
  1791.         (
  1792.             (
  1793.                 select ';' + ob.[StateYear] [text()]
  1794.                 from #bdmoppyears ob
  1795.                 where ob.[Id] = o.[Id] and ob.[OppRn] = o.[OppRn]
  1796.                 order by ob.[Id], ob.[OppRn]
  1797.                 for xml path ('')
  1798.             ), 2, 1000
  1799.         ) [StateYear]
  1800.     into #bdmoppfinalstg
  1801.     from
  1802.         #bdmoppyears o
  1803.     group by
  1804.         o.[Id]
  1805.     ,   o.[Name]
  1806.     ,   o.[StageName]
  1807.     ,   o.[CloseDate]
  1808.     ,   o.[Project_Name__c]
  1809.     ,   o.[Amount]
  1810.     ,   o.[Service_Type__c]
  1811.     ,   o.[Type]
  1812.     ,   o.[Splitflag]
  1813.     ,   o.[ELSignedDate]
  1814.     ,   o.[Years_Under_Study_Federal__c]
  1815.     ,   o.[Years_Under_Study_State__c]
  1816.     ,   o.[States__c]
  1817.     ,   o.[OppRn]
  1818.  
  1819.  
  1820. --Finalize Opportunity data  
  1821. if object_id('tempdb.dbo.#bdmoppfinal','U') is not null
  1822. drop table #bdmoppfinal;
  1823.  
  1824.     select
  1825.         [Id]
  1826.     ,   [Name]
  1827.     ,   [StageName]
  1828.     ,   [CloseDate]
  1829.     ,   [Project_Name__c]
  1830.     ,   [Amount]
  1831.     ,   [Service_Type__c]
  1832.     ,   [Type]
  1833.     ,   [Splitflag]
  1834.     ,   [ELSignedDate]
  1835.     ,   [Years_Under_Study_Federal__c]
  1836.     ,   [Years_Under_Study_State__c]
  1837.     ,   [States__c]
  1838.     ,   [OppRn]
  1839.     ,      NULLIF(coalesce(case when [FEDYear] = '' AND COUNT(Id)OVER(Partition By Id) = 1 then null else [FEDYear] end, [Years_Under_Study_Federal__c]),'') [FEDYear]
  1840.     ,      NULLIF(coalesce(case when [StateYear]  = '' AND COUNT(Id)OVER(Partition By Id) = 1 then null else [StateYear] end, [Years_Under_Study_State__c]),'') [StateYear]
  1841.  
  1842.     into #bdmoppfinal
  1843.     from
  1844.         #bdmoppfinalstg
  1845.  
  1846. if object_id('tempdb.dbo.#bdmopp','U') is not null
  1847. drop table #bdmopp;
  1848.  
  1849.     select
  1850.         [Id]
  1851.     ,   case
  1852.             when Rubix.dbo.ProjectName([FEDYear],[StateYear],[States__c]) = '' then replace([Service_Type__c],'Employee Retention Credit','ERC')
  1853.             when Service_Type__c = '179D' then concat(Rubix.dbo.ProjectName([FEDYear],null,null),' ', [Service_Type__c])
  1854.             else concat(Rubix.dbo.ProjectName([FEDYear],[StateYear],[States__c]),' ', replace([Service_Type__c],'Employee Retention Credit','ERC'))
  1855.             end [RevProjectName]
  1856.     --, Service_Type__c as [RevProjectName]
  1857.     ,   case
  1858.             when opp.[Splitflag] = 0 then opp.[Amount]
  1859.             when opp.[OppRn] = 1 then opp.[Amount]
  1860.             else 0
  1861.             end [RevAmount]
  1862.     , opp.FEDYear
  1863.     , opp.StateYear
  1864.     into #bdmopp
  1865.     from
  1866.         #bdmoppfinal opp
  1867.    
  1868. ;
  1869.  
  1870. --Getting Non CPA Referral Source Info
  1871. if object_id('tempdb.dbo.#bdmoncrsstg','U') is not null
  1872. drop table #bdmoncrsstg;
  1873.  
  1874.     select
  1875.         [Opportunity__c]
  1876.     ,   [Referral_Information__c]
  1877.     , age1.Name [OpRefSourceEmployee1]
  1878.     , age2.Name [OpRefSourceEmployee2]
  1879.     , age3.Name [OpRefSourceEmployee3]
  1880.     into #bdmoncrsstg
  1881.     from
  1882.     [SalesforceClone].[dbo].[Opportunity_Non_CPA_Referral_Source__c] oncrs
  1883.     LEFT JOIN [SalesforceClone].[dbo].[AG_Employee__c] age1 on age1.id = oncrs.ag_Employee_1__c
  1884.     LEFT JOIN [SalesforceClone].[dbo].[AG_Employee__c] age2 on age2.id = oncrs.ag_Employee_2__c
  1885.     LEFT JOIN [SalesforceClone].[dbo].[AG_Employee__c] age3 on age3.id = oncrs.ag_Employee_3__c
  1886.     where
  1887.         oncrs.IsDeleted = 0
  1888.     group by
  1889.         [Opportunity__c]
  1890.     ,   [Referral_Information__c]
  1891.     , age1.Name
  1892.     , age2.Name
  1893.     , age3.Name
  1894. ;
  1895.  
  1896. if object_id('tempdb.dbo.#bdmoncrs','U') is not null
  1897. drop table #bdmoncrs;
  1898.  
  1899.     select
  1900.         [Opportunity__c]
  1901.         ,   trim(replace(substring
  1902.         (
  1903.             (
  1904.                 select
  1905.                     '; ' + oncrsb.[OpRefSourceEmployee1] [text()]
  1906.                 from
  1907.                     #bdmoncrsstg oncrsb
  1908.                 where
  1909.                     oncrsb.[Opportunity__c] = oncrs.[Opportunity__c] and oncrsb.OpRefSourceEmployee1 IS NOT NULL
  1910.                 order by
  1911.                     oncrsb.[Opportunity__c]
  1912.                 for xml path ('')
  1913.             ), 2, 1000
  1914.         ),'&amp;','&')) [OpRefSourceEmployee1]
  1915.         ,trim(replace(substring
  1916.         (
  1917.             (
  1918.                 select
  1919.                     '; ' + oncrsb.[OpRefSourceEmployee2] [text()]
  1920.                 from
  1921.                     #bdmoncrsstg oncrsb
  1922.                 where
  1923.                     oncrsb.[Opportunity__c] = oncrs.[Opportunity__c] and oncrsb.OpRefSourceEmployee2 IS NOT NULL
  1924.                 order by
  1925.                     oncrsb.[Opportunity__c]
  1926.                 for xml path ('')
  1927.             ), 2, 1000
  1928.         ),'&amp;','&')) [OpRefSourceEmployee2]
  1929.         ,trim(replace(substring
  1930.         (
  1931.             (
  1932.                 select
  1933.                     '; ' + oncrsb.[OpRefSourceEmployee3] [text()]
  1934.                 from
  1935.                     #bdmoncrsstg oncrsb
  1936.                 where
  1937.                     oncrsb.[Opportunity__c] = oncrs.[Opportunity__c] and oncrsb.OpRefSourceEmployee3 IS NOT NULL
  1938.                 order by
  1939.                     oncrsb.[Opportunity__c]
  1940.                 for xml path ('')
  1941.             ), 2, 1000
  1942.         ),'&amp;','&')) [OpRefSourceEmployee3]
  1943.     ,   trim(replace(substring
  1944.         (
  1945.             (
  1946.                 select
  1947.                     '; ' + oncrsb.[Referral_Information__c] [text()]
  1948.                 from
  1949.                     #bdmoncrsstg oncrsb
  1950.                 where
  1951.                     oncrsb.[Opportunity__c] = oncrs.[Opportunity__c]
  1952.                 order by
  1953.                     oncrsb.[Opportunity__c]
  1954.                 for xml path ('')
  1955.             ), 2, 1000
  1956.         ),'&amp;','&')) [Referral_Information__c]
  1957.     into #bdmoncrs
  1958.     from
  1959.         #bdmoncrsstg oncrs
  1960.     group by
  1961.         [Opportunity__c]
  1962. ;
  1963.  
  1964.  
  1965. if object_id('tempdb.dbo.#OldbdMasterOpportunity','U') is not null
  1966. drop table #OldbdMasterOpportunity;
  1967.  
  1968. select distinct OpportunityID_CCC_3E into #OldbdMasterOpportunity from [FP&A].dbo.BD_Master
  1969.  
  1970.  
  1971. --Getting Opportunity data
  1972. if object_id('tempdb..#bdmoppResults') is not null
  1973. drop table #bdmoppResults;
  1974.  
  1975. select Date, Region, Company, WIP, Fee, PBD, PBdPerc, SBD, SBDPerc, CPA, CPAID, CPAPerc, Description, SOE,[OtherRefSource]
  1976. , [CPAAlliance], [State], [CPAContact], [Industry], [SIC],  [YearEnd], [FeeType_Remove], [FeeCap],
  1977. [FUSoe]
  1978.         , [SF_Case_Intake_ID]
  1979.         ,   [SF_Account_ID]
  1980.         ,   [SF_Parent_Account_ID]
  1981.         ,    [SF_Opportunity_ID]
  1982.         ,    [RunDt]
  1983.         ,   [CPA_Referral_Firm_Account_Ref__c]
  1984.         ,    [Amending_CPA_s_Firm_Account_Ref__c]
  1985.         ,   [NAICS_Code__c]
  1986.         ,    [IndustryIntake]
  1987.         , [Percentage]
  1988.         , [ADDeg]
  1989.         ,   [System_Integrators_Group__C]
  1990.         , [SF_CHILD_NAME]
  1991.         , [SF_CHILD_ID]
  1992.         ,    [Immediate_Parent__c] --PAR.Name [Immediate_Parent__c]
  1993.         ,   [Immediate_Parent_ID__c] --PAR.ID [Immediate_Parent_ID__c]
  1994.         ,   [Parent_Account_Alliance__c]
  1995.         ,   [Associations]
  1996.         ,   [Type]
  1997.         ,   [Evergreen]
  1998.         ,   [Relationship_Director_1]
  1999.         ,   [Relationship_Director_2]
  2000.         ,    [BD_Assist] [BDAssist]
  2001.         ,    [BD_Assist_Other]
  2002.         ,   [Number_of_Employees]
  2003.         ,   [Final_Intake_Created_By__c]
  2004.         ,   [Fee_Cap_Percentage_Type]
  2005.         ,    [SL]
  2006.         ,    [PBDAllocationPerc]
  2007.         ,    [SBDAllocationPerc]
  2008.         ,   [SOE1AllocationPerc]
  2009.         ,   [SOE2AllocationPerc]
  2010.         ,    [Contingent_Converted]
  2011.         ,  FEDYear
  2012.         , StateYear
  2013.         ,  [ServiceType]
  2014.         ,  [HistoricalAlliance]
  2015.         ,  [CPANewExistingNewAgain]
  2016.         , [CPAOrignalSignedDate]
  2017.         ,  [AnnualRevenue]
  2018.         , [OpRefSourceRavingFan]
  2019.         ,   [OpRefSourceCPA]
  2020.         ,   [OpRefSourceConference]
  2021.         ,   [OpRefSourceNonConference]
  2022.         ,   [OpRefSourceDirect]
  2023.         ,   [OpRefSourceEA]
  2024.         , [OpRefSourceWebinar]
  2025.         , [OpRefSourceWebsite]
  2026.         , [OpRefSourceReferralSource]
  2027.         ,   [OpRefSourceEmployee1]
  2028.         ,   [OpRefSourceEmployee2]
  2029.         ,   [OpRefSourceEmployee3]
  2030.         ,  [EgmtLetterSignedDate]
  2031.         , CloseDate
  2032.         , [RecordForUpdate]
  2033.         , CASE WHEN b.OpportunityID_CCC_3E IS NULL THEN 1 ELSE 0 END [RecordNotInOldBDMaster]
  2034. into #bdmoppResults from (
  2035.  
  2036. select  distinct
  2037.             coalesce(case
  2038.                         when charindex('@',o.[Final_Intake_Created_By__c]) = 0 then null
  2039.                         when ow.[LocaleSidKey] = 'en_GB' then
  2040.                         cast(convert(datetime,RIGHT(o.[Final_Intake_Created_By__c],charindex('@',reverse(o.[Final_Intake_Created_By__c]))-2),103) as date)
  2041.                         else cast(RIGHT(o.[Final_Intake_Created_By__c],charindex('@',reverse(o.[Final_Intake_Created_By__c]))-2) as date)
  2042.                         end,o.[Final_Intake_Created_Date__c]) [Date]
  2043.         ,   o.[State_by_Region_Mapping__c] [Region]
  2044.         ,   a.[Name] [Company]
  2045.         ,   coalesce(opp.[RevAmount], o.[Amount]) [WIP]
  2046.         ,   o.[Fee_Type__c] [Fee]
  2047.         ,   ow.[Name] [PBD]
  2048.         ,   null [PBDPerc]
  2049.         ,   coalesce(SBD.[Name],'N/A') [SBD]
  2050.         ,   null [SBDPerc]
  2051.         , CASE WHEN CPAAccount.Name IS NOT NULL  then CPAAccount.Name
  2052.                 WHEN PAR.Name  IS NOT NULL THEN PAR.NAME
  2053.                 WHEN AAR.NAME IS NOT NULL THEN AAR.NAME
  2054.                 WHEN CAR.Name IS NOT NULL THEN CAR.Name
  2055.                 ELSE 'Direct' END [CPA]
  2056.         , CASE WHEN a.CPA_Account__c IS NOT NULL  then a.CPA_Account__c
  2057.                 WHEN a.ParentID iS NOT NULL THEN a.ParentId
  2058.                 WHEN o.Amending_CPA_Firm_ID__c IS NOT NULL THEN o.Amending_CPA_Firm_ID__c
  2059.                 WHEN CAR.ID IS NOT NULL THEN CAR.ID
  2060.                 ELSE 'Direct' END [CPAID]
  2061.         ,   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]
  2062.         ,   concat(coalesce(opp.[RevProjectName], replace(o.[Project_Name__c],' Employee Retention Credit','ERC'))
  2063.                 ,   case when o.[Service_Type__c] != 'Employee Retention Credit' and o.[Type] = 'Follow-Up' then ' FU' end
  2064.                 ,   case when o.[Service_Type__c] != 'Employee Retention Credit' and o.[Type] = 'Continuation' then ' Add-On' end
  2065.                 ,   case when o.[Service_Type__c] != 'Employee Retention Credit' and o.Evergreen_2__c = 'Yes' then ' EG' end
  2066.                 ) [Description]
  2067.         ,   soe.[Name] [SOE]
  2068.         ,   coalesce(case when cir.[Referral_Information__c] = '' then 'Direct' else cir.[Referral_Information__c] end, 'Direct') [OtherRefSource]
  2069.         ,   o.[Amending_CPA_Alliance__c] [CPAAlliance]
  2070.         ,   case when len(a.[BillingState]) = 2 then a.[BillingState] else null end [State]
  2071.         ,   CPAContact.[Name] [CPAContact]
  2072.         ,   n.Name [Industry]--n.Major_Industry__c [Industry]
  2073.         ,   n.NAICS_Code__c [SIC] --a.[SIC]
  2074.         ,   o.[Fiscal_Year_End_2__c] [YearEnd]
  2075.         ,   null [FeeType_Remove]
  2076.         ,   try_convert(decimal(5,4),
  2077.             (CASE
  2078.                 WHEN o.[Fee_Cap_Percentage__c] is not null then o.[Fee_Cap_Percentage__c]
  2079.                 WHEN o.[Fee_Cap_Percentage_Gross__c] is not null then o.[Fee_Cap_Percentage_Gross__c]
  2080.                 ELSE o.[Fee_Cap_Percentage_Input__c]
  2081.                 END) / 100) [FeeCap]
  2082.         ,   o.[Follow_Up_Source_of_Engagement_FU_STUDY__c] [FUSoe]
  2083.         ,   o.[Id] [SF_Case_Intake_ID]
  2084.         ,   a.[Id] [SF_Account_ID]
  2085.         ,   a.ParentId [SF_Parent_Account_ID]
  2086.         ,   o.[Id] [SF_Opportunity_ID]
  2087.         ,   getdate() [RunDt]
  2088.         ,   CAR.[Account_Ref__c] [CPA_Referral_Firm_Account_Ref__c]
  2089.         ,   AAR.[Account_Ref__c] [Amending_CPA_s_Firm_Account_Ref__c]
  2090.         ,   N.[NAICS_Code__c]
  2091.         ,   N.Major_Industry__c [IndustryIntake]
  2092.         , (CASE
  2093.               WHEN o.[Fee_Cap_Percentage__c] is not null then o.[Fee_Cap_Percentage__c]
  2094.               WHEN o.[Fee_Cap_Percentage_Gross__c] is not null then o.[Fee_Cap_Percentage_Gross__c]
  2095.               ELSE o.[Fee_Cap_Percentage_Input__c]
  2096.               END) / 100 [Percentage]
  2097.         , CASE WHEN coalesce(o.Evergreen_2__c,'No') = 'No' THEN 0 ELSE 1 END [ADDeg]
  2098.         ,   A.[System_Integrators_Group__C]
  2099.         , CASE WHEN CPAAccount.Name IS NOT NULL  then CPAAccount.Name
  2100.                 WHEN PAR.Name  IS NOT NULL THEN PAR.NAME
  2101.                 WHEN AAR.NAME IS NOT NULL THEN AAR.NAME
  2102.                 WHEN CAR.Name IS NOT NULL THEN CAR.Name
  2103.                 ELSE NULL END [SF_CHILD_NAME]
  2104.         , CASE WHEN a.CPA_Account__c IS NOT NULL  then a.CPA_Account__c
  2105.                 WHEN a.ParentID iS NOT NULL THEN a.ParentId
  2106.                 WHEN o.Amending_CPA_Firm_ID__c IS NOT NULL THEN o.Amending_CPA_Firm_ID__c
  2107.                 WHEN CAR.ID IS NOT NULL THEN CAR.ID
  2108.                 ELSE NULL END [SF_CHILD_ID]
  2109.         ,   coalesce(cpa4.[Name], cpa3.[Name], cpa2.[Name], parentAcc.[Name], 'Direct') [Immediate_Parent__c] --PAR.Name [Immediate_Parent__c]
  2110.         ,   coalesce(cpa4.[Id], cpa3.[Id], cpa2.[Id], parentAcc.[Id]) [Immediate_Parent_ID__c] --PAR.ID [Immediate_Parent_ID__c]
  2111.         ,   A.[Parent_Account_Alliance__c]
  2112.         ,   A.[affiliations__c] [Associations]
  2113.         ,   replace(replace(o.[Type],'New Business','New'),'Follow-Up','FU') [Type]
  2114.         ,   coalesce(o.Evergreen_2__c,'No') [Evergreen]
  2115.         ,   rd1.[Name] [Relationship_Director_1]
  2116.         ,   rd2.[Name] [Relationship_Director_2]
  2117.         ,   bda.[Name] [BD_Assist]
  2118.         ,   bdao.[Name] [BD_Assist_Other]
  2119.         ,   o.Number_of_Employees__c [Number_of_Employees]
  2120.         ,   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]
  2121.         ,   o.[Fee_Cap_Percentage_Type__c] [Fee_Cap_Percentage_Type]
  2122.         ,   replace(o.[Service_Type__c],'Employee Retention Credit','ERC') [SL]
  2123.         ,   oa.BD1_Allocation__c / 100 [PBDAllocationPerc]
  2124.         ,   oa.BD2_Allocation__c / 100 [SBDAllocationPerc]
  2125.         ,   oa.RD1_Allocation__c / 100 [SOE1AllocationPerc]
  2126.         ,   oa.RD2_Allocation__c / 100 [SOE2AllocationPerc]
  2127.         ,   o.[Contingent_Converted__c] [Contingent_Converted]
  2128.         ,  opp.FEDYear
  2129.         , opp.StateYear
  2130.         --, row_number() over(partition by o.id, opp.FEDYear, opp.StateYear order by
  2131.         --  coalesce(case
  2132.         --              when charindex('@',o.[Final_Intake_Created_By__c]) = 0 then null
  2133.         --              when ow.[LocaleSidKey] = 'en_GB' then
  2134.         --              cast(convert(datetime,RIGHT(o.[Final_Intake_Created_By__c],charindex('@',reverse(o.[Final_Intake_Created_By__c]))-2),103) as date)
  2135.         --              else cast(RIGHT(o.[Final_Intake_Created_By__c],charindex('@',reverse(o.[Final_Intake_Created_By__c]))-2) as date)
  2136.         --              end,o.[Final_Intake_Created_Date__c])) Rn
  2137.         , CASE
  2138.                                  WHEN o.[Service_Type__c] = '179D' THEN 130
  2139.                                  WHEN o.[Service_Type__c] ='DPD' THEN 140
  2140.                                  WHEN o.[Service_Type__c] ='HCI' THEN 170
  2141.                                  WHEN o.[Service_Type__c] ='IC-DISC' THEN 160
  2142.                                  WHEN o.[Service_Type__c] ='ITC' THEN 180
  2143.                                  WHEN o.[Service_Type__c] ='LDTC' THEN 180
  2144.                                  WHEN o.[Service_Type__c] ='MDET' THEN 180
  2145.                                  WHEN o.[Service_Type__c] ='QTDP' THEN 180
  2146.                                  WHEN o.[Service_Type__c] ='R&D' THEN 110
  2147.                                  WHEN o.[Service_Type__c] ='SALT' THEN 110
  2148.                                  WHEN o.[Service_Type__c] ='SUT' THEN 120
  2149.                                  WHEN o.[Service_Type__c] ='TCS' THEN  150
  2150.                                  WHEN o.[Service_Type__c] ='Cybersecurity' Then 175
  2151.                                  WHEN o.[Service_Type__c] ='SRED' THEN 230
  2152.                                  WHEN o.[Service_Type__c] ='SR&ED' THEN 230
  2153.                                  WHEN o.[Service_Type__c] ='Employee Retention Credit' THEN 225
  2154.                                  WHEN o.[Service_Type__c] ='ERC Services' THEN 225
  2155.                                  WHEN o.[Service_Type__c] ='Tax Services' THEN 200
  2156.                                  WHEN o.[Service_Type__c] ='Business Advisory' THEN 235
  2157.                                  WHEN o.[Service_Type__c] ='Business Services' THEN 240
  2158.                                  WHEN o.[Service_Type__c] ='External Audit' THEN 250
  2159.  
  2160.                                  WHEN o.[Service_Type__c] ='ERC' THEN 225
  2161.                                  ELSE NULL --150
  2162.                                  END [ServiceType]
  2163.         , oa.Alliance_Historical__c [HistoricalAlliance]
  2164.         , oa.CPA_Status_YTD__c [CPANewExistingNewAgain]
  2165.         , oa.CPA_First_Assigned_Date__c [CPAOrignalSignedDate]
  2166.         , a.AnnualRevenue [AnnualRevenue]
  2167.         , ref.[OpRefSourceRavingFan]
  2168.         ,   ref.[OpRefSourceCPA]
  2169.         ,   ref.[OpRefSourceConference]
  2170.         ,   ref.[OpRefSourceNonConference]
  2171.         ,   ref.[OpRefSourceDirect]
  2172.         ,   ref.[OpRefSourceEA]
  2173.         , ref.[OpRefSourceWebinar]
  2174.         , ref.[OpRefSourceWebsite]
  2175.         , ref.[OpRefSourceReferralSource]
  2176.         ,   ref.[OpRefSourceEmployee1]
  2177.         ,   ref.[OpRefSourceEmployee2]
  2178.         ,   ref.[OpRefSourceEmployee3]
  2179.         , o.Engagement_Letter_Signed_Date__c [EgmtLetterSignedDate]
  2180.         , o.CloseDate
  2181.         , CASE WHEN s.OpportunityIDCCC is NOT NULL and o.LastModifiedDate > GETDATE()-1 THEN 1
  2182.                 WHEN s.OpportunityIDCCC is NOT NULL and A.Last_Modified_Date__c > GETDATE()-1 THEN 1
  2183.                 WHEN s.OpportunityIDCCC is NOT NULL and CPAContact.LastModifiedDate > GETDATE()-1 THEN 1
  2184.                 WHEN s.OpportunityIDCCC is NOT NULL and N.LastModifiedDate > GETDATE() -1 THEN 1
  2185.                 WHEN s.OpportunityIDCCC is NOT NULL and CAR.LastModifiedDate > GETDATE() -1 THEN 1
  2186.                 WHEN s.OpportunityIDCCC is NOT NULL and AAR.LastModifiedDate > GETDATE() -1 THEN 1
  2187.                 WHEN s.OpportunityIDCCC is NOT NULL and PAR.LastModifiedDate > GETDATE() -1 THEN 1
  2188.                 WHEN s.OpportunityIDCCC is NOT NULL and RD1.LastModifiedDate > GETDATE() -1 THEN 1
  2189.                 WHEN s.OpportunityIDCCC is NOT NULL and RD2.LastModifiedDate > GETDATE() -1 THEN 1
  2190.                 WHEN s.OpportunityIDCCC is NOT NULL and OA.LastModifiedDate > GETDATE() -1 THEN 1
  2191.                 WHEN s.OpportunityIDCCC is NOT NULL and CPAAccount.LastModifiedDate > GETDATE() -1 THEN 1
  2192.                 WHEN ref.RecordForUpdate =1 THEN 1
  2193.                 ELSE 0 END [RecordForUpdate]
  2194.         --into #bdmoppResults
  2195.         from
  2196.             [SalesforceClone].[dbo].[Opportunity] o --on bd.OpportunityID_CCC_3E = o.id
  2197.         left join
  2198.             bdm.BDMasterOppReferralInfo ref on ref.Opportunity__c = o.id
  2199.         left join
  2200.             #bdmopp opp on opp.[Id] = o.[Id]
  2201.         left join
  2202.             [SalesforceClone].[dbo].[Account] A on O.[AccountId] = A.[Id]
  2203.         left join
  2204.             [SalesforceClone].[dbo].[User] ow on ow.[Id] = O.[OwnerId]
  2205.         left join
  2206.             [SalesforceClone].[dbo].[User] SBD on SBD.Id = O.[Primary_Director_Name__c]
  2207.         left join
  2208.             [SalesforceClone].[dbo].[User] soe on soe.[Id] = O.[Source_of_Engagement__c]
  2209.         left join
  2210.             [SalesforceClone].[dbo].[Contact] CPAContact on CPAContact.Id = O.Amending_CPA_Contact__c
  2211.         left join
  2212.             [SalesforceClone].[dbo].[NAICS_List__c] N on A.[NAICS_Lookup__c] = N.[Id]
  2213.         left join
  2214.             #bdmoncrs CIR on cir.[Opportunity__c] = O.[id]
  2215.         left join
  2216.             [SalesforceClone].[dbo].[Account] CAR on CAR.[Id] = O.[Referring_CPA_Firm_ID__C]
  2217.         left join
  2218.             [SalesforceClone].[dbo].[Account] AAR on AAR.[Id] = O.[Amending_CPA_Firm_ID__c]
  2219.         left join
  2220.             [SalesforceClone].[dbo].[Account] PAR on PAR.[Id] = A.[ParentId]
  2221.         left join
  2222.             [SalesforceClone].[dbo].[User] rd1 on rd1.Id = o.Primary_Relationship_Director__c
  2223.         left join
  2224.             [SalesforceClone].[dbo].[User] rd2 on rd2.Id = o.X2nd_Relationship_Director__c
  2225.         left join
  2226.             [SalesforceClone].[dbo].[AG_Employee__c] bda on bda.Id = o.BD_Assist__c
  2227.         left join
  2228.             [SalesforceClone].[dbo].[AG_Employee__c] bdao on bdao.Id = o.BD_Assist_Other_1__c
  2229.         left join
  2230.             [SalesforceClone].[dbo].[Opportunity_Analytics__c] oa on oa.Opportunity__c = o.id
  2231.         left join
  2232.             [SalesforceClone].[dbo].[Account] CPAAccount on CPAAccount.id = a.CPA_Account__c
  2233.         left join
  2234.             [SalesForceClone].dbo.Account parentAcc on parentAcc.id = COALESCE(a.CPA_Account__c,o.Amending_CPA_Firm_ID__c, [Referring_CPA_Firm_ID__C])
  2235.         left join
  2236.             SalesForceClone.dbo.Account cpa2 on cpa2.[Id] = parentAcc.[ParentId]
  2237.         left join
  2238.             SalesForceClone.dbo.Account cpa3 on cpa3.[Id] = cpa2.[ParentId]
  2239.         left join
  2240.             SalesForceClone.dbo.Account cpa4 on cpa4.id = cpa3.ParentId                    
  2241.         outer apply
  2242.             (select top 1 OpportunityIDCCC from BDM.BDMasterSource s where s.OpportunityIDCCC = o.id ) s
  2243.         where --o.CloseDate > '01/01/2020' and
  2244.  
  2245.             (([Final_Intake_Created_By__c] is not null  and [Final_Intake_Created_By__c] not like '%Bhavesh Zaveri%') or Stagename like 'Closed%')
  2246.        
  2247.         UNION
  2248.  
  2249.         select distinct
  2250.             cast(C.[CreatedDate] as date) [Date]
  2251.         ,   C.[State_by_Region_Mapping__c] [Region]
  2252.         ,   C.[Account_Name__c] [Company]
  2253.         ,   C.[Book_to_WIP__c] [WIP]
  2254.         ,   C.[Fee_Type__c] [Fee]
  2255.         ,   U.[Name] [PBD]
  2256.         ,   NULL [PBDPerc]
  2257.         ,   U1.[Name] [SBD]
  2258.         ,   NULL [SBDPerc]
  2259.         ,   C.[Amending_CPA_s_Firm__c] [CPA]
  2260.         ,   NULL [CPAID]
  2261.         ,   NULL [CPAPerc]
  2262.         ,   replace(C.[Project_Name__c],'Fed','FED') [Description]
  2263.         ,   U2.[Name] [SOE]
  2264.         ,   ciro.[Referral_Information__c] [OtherRefSource]
  2265.         ,   C.[Alliance__c] [CPAAlliance]
  2266.         ,   case
  2267.                 when len(C.[Client_Billing_State__c]) = 2
  2268.                 then C.[Client_Billing_state__c]
  2269.                 else NULL
  2270.                 end [State]
  2271.         ,   Con.[Name] [CPAContact]
  2272.         ,   C.[Client_s_Industry__c] [Industry]
  2273.         ,   C.[SIC_Code__c] [SIC]
  2274.         ,   C.[Year_End__c] [YearEnd]
  2275.         ,   NULL [FeeType_Remove]
  2276.         ,   try_convert(decimal(5,4), C.[Fee_CAP__c]) [FeeCap]  -- C.[Fee_CAP__c] [FeeCap]
  2277.         ,   C.[Follow_Up_Source_of_Engagement_FU_STUDY__c] [FUSoe]
  2278.         ,   C.[Id] [SF_Case_Intake_ID]
  2279.         ,   C.[Account_ID__c] [SF_Account_ID]
  2280.         ,   NULL AS [SF_Parent_Account_ID]
  2281.         ,   C.Opportunity_ID__c [SF_Opportunity_ID]
  2282.         ,   getdate() [RunDt]
  2283.         ,   C.[CPA_Referral_Firm_Account_Ref__c]
  2284.         ,   C.[Amending_CPA_s_Firm_Account_Ref__c]
  2285.         ,   C.[NAICS_Code__c]
  2286.         ,   Null as IndustryIntake
  2287.         ,   0 as Percencetage
  2288.         ,   0 [ADDeg]
  2289.         ,   A.[System_Integrators_Group__C]
  2290.         ,   NULL [SF_CHILD_NAME]
  2291.         ,   NULL [SF_CHILD_ID]
  2292.         ,   PAR.[Name] [Immediate_Parent__c]
  2293.         ,   PAR.ID [Immediate_Parent_ID__c]
  2294.         ,   A.[Parent_Account_Alliance__c]
  2295.         ,   A.[affiliations__c] [Associations]
  2296.         ,   null [Type]
  2297.         ,   null [Evergreen]
  2298.         ,   null [Relationship_Director_1]
  2299.         ,   null [Relationship_Director_2]
  2300.         ,   null [BD_Assist]
  2301.         ,   null [BD_Assist_Other]
  2302.         ,   null [Number_of_Employees]
  2303.         ,   null [Final_Intake_Created_By__c]
  2304.         ,   null [Fee_Cap_Percentage_Type]
  2305.         ,   null [SL]
  2306.         ,   null [PBDAllocationPerc]
  2307.         ,   null [SBDAllocationPerc]
  2308.         ,   null [SOE1AllocationPerc]
  2309.         ,   null [SOE2AllocationPerc]
  2310.         ,   null [Contingent_Converted]
  2311.         , null as [FedYear]
  2312.         , null as [StateYear]
  2313.         , null as [ServiceType]
  2314.         , NULL as [HistoricalAlliance]
  2315.         , NULL as [CPANewExistingNewAgain]
  2316.         , NULL as [CPAOrignalSignedDate]
  2317.         , Null as [AnnualRevenue]
  2318.         , NUll [OpRefSourceRavingFan]
  2319.         ,   NUll [OpRefSourceCPA]
  2320.         ,   NUll [OpRefSourceConference]
  2321.         ,NUll [OpRefSourceNonConference]
  2322.         ,NUll [OpRefSourceDirect]
  2323.         ,NUll [OpRefSourceEA]
  2324.         , NUll [OpRefSourceWebinar]
  2325.         , NUll [OpRefSourceWebsite]
  2326.         , NUll [OpRefSourceReferralSource]
  2327.         ,NUll [OpRefSourceEmployee1]
  2328.         ,NUll [OpRefSourceEmployee2]
  2329.         ,NUll [OpRefSourceEmployee3]
  2330.         , NULL [EgmtLetterSignedDate]
  2331.         , NULL CloseDate
  2332.         , 0 [RecordForUpdate]
  2333.         from
  2334.             [SalesforceClone].[dbo].[Case] c
  2335.         left outer join
  2336.             [SalesforceClone].[dbo].[User] u on c.[Primary_BD_Director__c] = u.[Id]
  2337.         left outer join
  2338.             [SalesforceClone].[dbo].[Case_Intake_Referral_Source__c] cir on cir.[Case_Intake_Referral_Source__c] = c.[Id]
  2339.         left outer join
  2340.             [SalesforceClone].[dbo].[User] U1 on c.[x2nd_BD_Director_If_any__c] = U1.[Id]
  2341.         left outer join
  2342.             [SalesforceClone].[dbo].[User] U2 on c.[Source_of_Engagement__c] = U2.[Id]
  2343.         left outer join
  2344.             [SalesforceClone].[dbo].[Contact] con on C.[CPA_Amending_Prepping_Returns__c] = con.[Id]
  2345.         left join
  2346.             [SalesforceClone].[dbo].[Account] a on a.[Id] = c.[AccountId]
  2347.         left join
  2348.             [SalesforceClone].[dbo].[Account] par on par.Id = a.ParentId
  2349.         left outer join
  2350.             [SalesforceClone].[dbo].[Opportunity_Non_CPA_Referral_Source__c] ciro on ciro.[Opportunity__c] = c.[Opportunity_ID__c]
  2351.         where
  2352.             c.[RecordType_Name__c] in ('New Client Intake R&D, QETC and DPD','New Client Intake-179D')
  2353.             and c.[CreatedDate] >= '2015-05-20'
  2354.             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%')
  2355.             --and o.[CloseDate]>= '01/01/2020'
  2356.  
  2357.     )
  2358. LEFT JOin #OldbdMasterOpportunity b on b.OpportunityID_CCC_3E = a.SF_Opportunity_ID
  2359.  
  2360. --Logging in Log table
  2361. exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'Data retrived from Salesforce for Opportunity'
  2362.  
  2363. if object_id('tempdb..#bdmResults') is not null
  2364. drop table #bdmResults;
  2365.  
  2366. --Pulling data from 3E based on Opportunity Id, Service Line and Year of Study
  2367. select distinct
  2368. m.MattIndex, m.Number, m.AltNumber, m.DisplayName
  2369. , b.Description [Description_SF]
  2370. , m.Description [Description_3E]
  2371. , COALESCE(b.Description, m.Description) [Description]
  2372. , b.Company [Client_SF]
  2373. , m.Client [Client_3E]
  2374. , COALESCE(b.Company,m.Client) [Client]
  2375. , m.ClientId
  2376. , CASE WHEN m.MattStatus IN ('KO','CANCELDUP','Cancel_NOEL','TERM','TERM_EG','TERM_ERCLIVE') THEN 'Suspended'
  2377.         WHEN m.MattStatus IN ('COMP_ERCLIVE','COMP','CLOSING','CLOSING_ERCLIVE') THEN 'Completed'
  2378.         WHEN m.MattStatus IN ('HOLDAR','HOLDUTL','HOLDREP','HOLDFYR','LINKED','PEND','HOLDAUD','PENDEG','INPROC'
  2379.             ,'HOLDRESELL','HOLDFYE','HOLDCLI','EGREADYTOASSIGN','NO_EL','HOLDBD','HOLDFF','HOLDAYE','PENDCOMP','HOLDARREP'
  2380.             ,'HOLDAMR', 'HOLDARREP', 'HOLDERC', 'HOLDIRS', 'HOLDREF', 'HOLDUR')
  2381.             THEN 'In-Process'
  2382.         ELSE m.MattStatus END [MattStatus]
  2383. , m.Currency
  2384. , m.MattCategory
  2385. , COALESCE(m.IsEvergreenCCC,0) IsEvergreenCCC
  2386. , b.Type [EngTypeCCC_SF]
  2387. , m.EngTypeCCC [EngTypeCCC_3E]
  2388. , 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]
  2389. , m.EngStatusCCC
  2390. , b.[EgmtLetterSignedDate] [EngSignedDateCCC_SF]
  2391. , m.EngSignedDateCCC [EngSignedDateCCC_3E]
  2392. , COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC) [EngSignedDateCCC]
  2393. , b.SL [ServiceLine_SF]
  2394. , m.ServiceLine [ServiceLine_3E]
  2395. , COALESCE(b.SL,m.ServiceLine) ServiceLine
  2396. , b.State [State_SF]
  2397. , m.State [State_3E]
  2398. , COALESCE(b.State, m.State) [State]
  2399. , b.WIP [OriginalWIP_SF]
  2400. , m.OriginalWIP [OriginalWIP_3E]
  2401. , 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
  2402. THEN m.OriginalWIP
  2403. WHEN COUNT(m.Mattindex)OVER(Partition BY m.[1TimeAdj],b.SF_Opportunity_ID)>1 THEN m.OriginalWIP
  2404.  ELSE COALESCE(NULLIF(b.WIP,0), m.OriginalWIP) END [OriginalWIP]
  2405. , /*Case when m.[MattStatus] in ('COMP','CLOSING','CLOSING_ERCLIVE') then bc.BilledSplit else*/ m.AdjustedWIP /*end*/ AdjustedWIP
  2406. , b.[IndustryIntake] [MajorIndustry_SF]
  2407. , m.MajorIndustry [MajorIndustry_3E]
  2408. , COALESCE(b.[IndustryIntake], m.MajorIndustry) MajorIndustry
  2409. , COALESCE(m.MinYear,YEAR(m.EngSignedDateCCC),YEAR(b.Date), '9999') [MinTaxYear]
  2410. , m.MaxYear [MaxTaxYear]
  2411. , m.Code
  2412. , StudyYears
  2413. , m.UpdatedWIP
  2414. , CASE WHEN m.OriginalWIP <> m.UpdatedWIP THEN UpdatedWIP ELSE OriginalWIP END [ComboWIP]
  2415. , COALESCE(bc.BilledSplit,0) [Billed]
  2416. , ISNULL(bc.CollectedSplit,0) [Collected]
  2417. , ISNULL(bc.BilledSplit - bc.CollectedSplit,0) [AccountReceivable]
  2418. , COALESCE(m.PBD, b.PBD) PBD
  2419. , CASE WHEN ISNULL(COALESCE(m.SBD, b.SBD), 'Unknown') = 'Unknown' THEN 'N/A' ELSE COALESCE(m.SBD, b.SBD) END SBD
  2420. , COALESCE(m.PRD, b.Relationship_Director_1) PRD
  2421. , CASE WHEN ISNULL(COALESCE(m.SRD, b.Relationship_Director_2), 'Unknown') = 'Unknown' THEN 'N/A'
  2422.             ELSE COALESCE(m.SRD, b.Relationship_Director_2) END SRD
  2423. , NULL as [PM] --m.PM
  2424. , m.Credit [EstimatedCredits]
  2425. , m.WorkedWIP
  2426. , m.PendingInvoices
  2427. , m.TotalWIP
  2428. , m.RemainingWIP [RemainingWIPbasedonhoursworked]
  2429. , m.UnbilledWIP
  2430. , m.UnbilledWorkedWIP
  2431. , m.Balance
  2432. , COALESCE(m.BD1Allocation,b.PBDAllocationPerc) [PBDAllocationPercent]
  2433. , COALESCE(m.BD2Allocation,b.SBDAllocationPerc) [SBDAllocationPercent]
  2434. , COALESCE(m.RD1Allocation,b.SOE1AllocationPerc) [PRDAllocationPercent]
  2435. , COALESCE(m.RD2Allocation,b.SOE2AllocationPerc) [SRDAllocationPercent]
  2436. , 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]
  2437. , 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]
  2438. , 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]
  2439. , 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]
  2440. , m.BD1AdjWIPAlloc [PBDWIPAllocation]
  2441. , m.BD2AdjWIPAlloc [SBDWIPAllocation]
  2442. , m.RD1AdjWIPAlloc [SOE1WIPAllocation]
  2443. , m.RD2AdjWIPAlloc [SOE2WIPAllocation]
  2444. ,  m.BD1FeesBilled [PBDBilledAllocation]
  2445. ,  m.BD2FeesBilled [SBDBilledAllocation]
  2446. ,  m.RD1FeesBilled [SOE1BilledAllocation]
  2447. ,  m.RD2FeesBilled [SOE2BilledAllocation]
  2448. ,  m.BD1FeesCollected [PBDCollections]
  2449. ,  m.BD2FeesCollected [SBDCollections]
  2450. ,  m.RD1FeesCollected [SOE1Collections]
  2451. ,  m.RD2FeesCollected [SOE2Collections]
  2452. , COALESCE(m.[1TimeAdj],0) [OneTimeAdj]
  2453. , b.SF_Opportunity_ID [OpportunityIDCCC]
  2454. --, b.PBD, b.SBD, b.SOE [PRD], b.Relationship_Director_2 [SRD],
  2455. --ISNULL(b.[PBDAllocationPerc],0) [PBDPercent], ISNULL(b.SBDAllocationPerc,0) [SBDPercent]
  2456. --, ISNULL(b.SOE1AllocationPerc,0) [PRDPercent], ISNULL(b.SOE2AllocationPerc,0) [SRDPercent],
  2457. ,b.CPA, b.CPAPerc [CPAPercent], b.OtherRefSource [ReferralSource], b.CPAAlliance [CPAAlliance],
  2458. 0 as [Manufacturing], 0 as [Architecture], 0 as [Construction] , 0 as [Engineering], 0 as [SystemIntegrator],
  2459. b.[SF_Account_ID] as [SFAccountId]
  2460. , b.[Immediate_Parent__c] [SFParentAccount]  --b.SF_Parent_Account_ID [SFParentAccount]
  2461. , b.SF_CHILD_ID [SFChildId]
  2462. , b.SF_CHILD_NAME [SFChildAccount],
  2463. b.CPAID as CPAID, NULL as [EAReferral], NULL as [EATeam], NULL as [EAIndustry], NULL as [EAParentName], NULL as [EAYearAttended], NULL as [EAEventDate],
  2464. 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
  2465. , b.HistoricalAlliance
  2466. , b.[REGION]
  2467. , b.CPAContact 
  2468. , NULL as CPANewExisting --b.CPANewExistingNewAgain
  2469. ,   NULL as [CPAOrignalSignedDate] --b.CPAOrignalSignedDate [CPAOrignalSignedDate]
  2470. ,-1 as RefNo
  2471. , b.[AnnualRevenue]
  2472. , b.[OpRefSourceRavingFan]
  2473.         ,   b.[OpRefSourceCPA]
  2474.         ,   b.[OpRefSourceConference]
  2475.         ,   b.[OpRefSourceNonConference]
  2476.         ,   b.[OpRefSourceDirect]
  2477.         ,   b.[OpRefSourceEA]
  2478.         , b.[OpRefSourceWebsite]
  2479.         , b.[OpRefSourceWebinar]
  2480.         , b.[OpRefSourceReferralSource]
  2481.         ,   b.[OpRefSourceEmployee1]
  2482.         ,   b.[OpRefSourceEmployee2]
  2483.         ,   b.[OpRefSourceEmployee3]
  2484. , b.[IndustryIntake] [IndustryIntake]
  2485. , b.Percentage [Percentage]
  2486. , b.ADDeg [AddEG]
  2487. , b.Associations [Associations]
  2488. , NULL As [ReferralCategory] --b.OtherRefSource [ReferralCategory]
  2489. , b.YearEnd
  2490. ,b.Fee_Cap_Percentage_Type [FeeCapPercentageType]
  2491. , CASE WHEN DATEDIFF(day, b.CloseDate, GETDATE() ) <= 365 and COALESCE(b.CPA, 'Direct') <> 'Direct' THEN 'New'
  2492.         WHEN DATEDIFF(day, b.CloseDate, GETDATE()) >= 365
  2493.             and DATEDIFF(day, b.CloseDate, GETDATE()) <= 1460 and COALESCE(b.CPA, 'Direct') <> 'Direct'
  2494.              THEN 'Existing'
  2495.         WHEN DATEDIFF(day, b.CloseDate, GETDATE()) > 1460 and COALESCE(b.CPA, 'Direct') <> 'Direct'
  2496.              THEN 'New'
  2497.         ELSE 'Direct' END [CPANewExistingNewAgain]
  2498. , 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)
  2499.            
  2500.            
  2501.             THEN TRY_CAST(NULLIF(CONCAT('01/01/',
  2502.             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
  2503.             , NULLIF(m.MinYear,9999)+1
  2504.             ,  YEAR(COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC,b.Date))+1)),'01/01/') as datetime)
  2505.            
  2506.             ELSE CAST(COALESCE(b.[EgmtLetterSignedDate], m.EngSignedDateCCC,b.Date) as varchar(50)) END [OriginalDate]--[CloseDate]
  2507. , COALESCE(b.Date, m.EngSignedDateCCC) [CloseDate]--[OriginalDate]
  2508. , CASE WHEN COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC) IS NOT NULL THEN YEAR(COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC)) ELSE 0 END [Year]
  2509. , CASE WHEN COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC) IS NOT NULL THEN DATEPART(Quarter, COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC)) ELSE 0 END [Quarter]
  2510. , CASE WHEN COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC) IS NOT NULL THEN DATEPART(Month, COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC)) ELSE 0 END [Month]
  2511. , CASE WHEN COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC) IS NOT NULL THEN DATEPART(Week, COALESCE(b.[EgmtLetterSignedDate],m.EngSignedDateCCC)) ELSE 0 END [Week]
  2512. , CASE WHEN b.Type = 'Continuation' THEN 1 ELSE 0 END [FO]
  2513. , b.BDAssist
  2514. , b.RecordNotInOldBDMaster
  2515. , CASE WHEN b.RecordForUpdate =1 OR m.RecordForUpdate = 1 OR COALESCE(bc.BilledSplit,bc.CollectedSplit) is not null THEN 1 ELSE 0 END [RecordForUpdate]
  2516. ,m.IsCloned_CCC
  2517. into #bdmResults
  2518. from #bdmoppResults b
  2519. FULL OUTER JOIN Bdm.BDMasterMatterDataFrom3E m
  2520.  on m.[OpportunityID_CCC] = b.SF_Opportunity_ID COLLATE SQL_Latin1_General_CP1_CI_AS
  2521.     and m.Code = ISNULL(b.ServiceType , m.code)
  2522.     and ((CHARINDEX(CAST(m.MinYear AS varchar), b.fedyear) >0  OR CHARINDEX(CAST(m.MinYear AS varchar), b.StateYear)>0)
  2523.         OR (b.FEDYear is null and b.StateYear is null)
  2524.     )
  2525. LEFT JOIN BDM.BDMasterMatterBilledCollected bc on bc.Number = m.Number and bc.MinYear = m.MinYear
  2526. LEFT JOIN BDM.BDMasterCommissionPerc pbd on pbd.Employee = COALESCE(m.PBD, b.PBD) and pbd.[Role] = 'PBD'
  2527. LEFT JOIN BDM.BDMasterCommissionPerc prd on prd.Employee = COALESCE(m.PRD, b.Relationship_Director_1) and prd.[Role] = 'PRD'
  2528. LEFT JOIN BDM.BDMasterCommissionPerc sbd on sbd.Employee = COALESCE(m.SBD, b.SBD) and sbd.[Role] = 'SBD'
  2529. LEFT JOIN BDM.BDMasterCommissionPerc srd on srd.Employee = COALESCE(m.SRD, b.Relationship_Director_2) and srd.[Role] = 'SRD'
  2530. LEFT JOIN TE_3E_PROD_Clone..Matter m2 on m2.mattindex = m.Mattindex
  2531. 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
  2532. --and m.Number IN ('012825.0006')
  2533.  
  2534. exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'Data retrived from 3E based on Opportunity'
  2535.  
  2536. --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
  2537. if object_id('tempdb..#bdmFinalResults') is not null
  2538. drop table #bdmFinalResults;
  2539. select b.* , CASE WHEN COALESCE(s.Number, s.[OpportunityIDCCC]) IS NULL THEN 'I' ELSE NULL END [RecordActionFlag]
  2540. into  #bdmFinalResults
  2541. from
  2542. #bdmResults b
  2543. LEFT JOIN bdm.BDMasterSource s
  2544.     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
  2545.     and b.MinTaxYear = s.MinTaxYear
  2546.  
  2547. --Insert data in BDMasterSource table based on RecordActionFlag
  2548. Declare @InsertResultCount varchar(100)
  2549. Set @InsertResultCount = (select try_convert(varchar(10),count(*)) + ' to be inserted' from #bdmFinalResults where RecordActionFlag = 'I')
  2550. exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = @InsertResultCount
  2551.  
  2552. --Insert Data in Source Table
  2553. INSERT INTO [bdm].[BDMasterSource]
  2554.            ([MattIndex]
  2555.            ,[Number]
  2556.            ,[AltNumber]
  2557.            ,[DisplayName]
  2558.            ,[Description]
  2559.            ,[ClientID]
  2560.            ,[Client]
  2561.            ,[MattStatus]
  2562.            ,[CloseDate]
  2563.            ,[Currency]
  2564.            ,[MattCategory]
  2565.            ,[IsEvergreenCCC]
  2566.            ,[EngTypeCCC]
  2567.            ,[EngStatusCCC]
  2568.            ,[EngSignedDateCCC]
  2569.            ,[OpportunityIDCCC]
  2570.            ,[ServiceLine]
  2571.            ,[State]
  2572.            ,[OriginalWIP]
  2573.            ,[AdjustedWIP]
  2574.            ,[MajorIndustry]
  2575.            ,[PBD]
  2576.            ,[SBD]
  2577.            ,[PRD]
  2578.            ,[SRD]
  2579.            ,[PBDAllocationPercent]
  2580.            ,[SBDAllocationPercent]
  2581.            ,[PRDAllocationPercent]
  2582.            ,[SRDAllocationPercent]
  2583.            ,[CPA]
  2584.            ,[CPAPercent]
  2585.            ,[ReferralSource]
  2586.            ,[CPAAlliance]
  2587.            ,[Manufacturing]
  2588.            ,[Architecture]
  2589.            ,[Construction]
  2590.            ,[Engineering]
  2591.            ,[SystemIntegrator]
  2592.            ,[SFAccountID]
  2593.            ,[SFParentAccount]
  2594.            ,[SFChildID]
  2595.            ,[SFChildAccount]
  2596.            ,[CPAID]
  2597.            ,[EAReferral]
  2598.            ,[EATeam]
  2599.            ,[EAIndustry]
  2600.            ,[EAParentName]
  2601.            ,[EAYearAttended]
  2602.            ,[EAEventDate]
  2603.            ,[WebinarIPA]
  2604.            ,[EASpeaker]
  2605.            ,[FeeCap]
  2606.            ,[FeeType]
  2607.            ,[NumberOfEmployees]
  2608.            ,[WIP]
  2609.            ,[Industry]
  2610.            ,[SIC]
  2611.            , [LastUpdatedDate]
  2612.            , [HistoricalAlliance]
  2613.            , [REGION]
  2614.            , [Year]
  2615.         , [Quarter]
  2616.         , [Month]
  2617.         , [Week]
  2618.         , [CPAContact]
  2619.         , [CPANewExistingNewAgain]
  2620.         , [CPAOrignalSignedDate]
  2621.         , [StudyYears]
  2622.         , RefNo
  2623.         , UpdatedWIP
  2624.         , ComboWIP
  2625.         , Billed
  2626.         , Collected
  2627.         , AccountReceivable
  2628.         , [EstimatedCredits]
  2629.         , [AnnualRevenue]
  2630.         , [WorkedWIP]
  2631.         , [PendingInvoices]
  2632.         , [RemainingWIPbasedonhoursworked]
  2633.         , [UnbilledWIP]
  2634.         , [UnbilledWorkedWIP]
  2635.         , [Balance]
  2636.         , [PBDWIPAllocation]
  2637.         , [SBDWIPAllocation]
  2638.         , [SOE1WIPAllocation]
  2639.         , [SOE2WIPAllocation]
  2640.         , [PBDBilledAllocation]
  2641.         , [SBDBilledAllocation]
  2642.         , [SOE1BilledAllocation]
  2643.         , [SOE2BilledAllocation]
  2644.         , [PBDCollections]
  2645.         , [SBDCollections]
  2646.         , [SOE1Collections]
  2647.         , [SOE2Collections]
  2648.         , [OneTimeAdj]
  2649.         , [OpRefSourceRavingFan]
  2650.         ,   [OpRefSourceCPA]
  2651.         ,   [OpRefSourceConference]
  2652.         ,   [OpRefSourceNonConference]
  2653.         ,   [OpRefSourceDirect]
  2654.         ,   [OpRefSourceEA]
  2655.         ,   [OpRefSourceEmployee1]
  2656.         ,   [OpRefSourceEmployee2]
  2657.         ,   [OpRefSourceEmployee3]
  2658.         ,   [OpRefSourceWebsite]
  2659.         ,   [OpRefSourceWebinar]
  2660.         ,   [OpRefSourceReferralSource]
  2661.         , [PM]
  2662.         , [IndustryIntake]
  2663.         , [Percentage]
  2664.         , [AddEG]
  2665.         , [Associations]
  2666.         , [ReferralCategory]
  2667.         , [YearEnd]
  2668.         , [FeeCapPercentageType]
  2669.         ,[Description_SF]
  2670.         ,[Description_3E]
  2671.         ,[Client_SF]
  2672.         ,[Client_3E]
  2673.         ,[EngTypeCCC_SF]
  2674.         ,[EngTypeCCC_3E]
  2675.         ,[EngSignedDateCCC_SF]
  2676.         ,[EngSignedDateCCC_3E]
  2677.         ,[ServiceLine_SF]
  2678.         ,[ServiceLine_3E]
  2679.         ,[State_SF]
  2680.         ,[State_3E]
  2681.         ,[OriginalWIP_SF]
  2682.         ,[OriginalWIP_3E]
  2683.         ,[MajorIndustry_SF]
  2684.         ,[MajorIndustry_3E]
  2685.         ,[CPANewExisting]
  2686.         --,[BDMasterOppId]
  2687.         ,[OriginalDate]
  2688.         ,[FO]
  2689.         ,[BDAssist]
  2690.         ,[PBDComPercent]
  2691.         ,[PRDComPercent]
  2692.         ,[SBDComPercent]
  2693.         ,[SRDComPercent]
  2694.         ,[MinTaxYear]
  2695.         , [RecordNotInOldBDMaster]
  2696.         ,[Source]
  2697.         ,IsCloned_CCC
  2698.         ,MaxTaxYear
  2699.        )
  2700.      (select [MattIndex]
  2701.            ,[Number]
  2702.            ,[AltNumber]
  2703.            ,[DisplayName]
  2704.            ,[Description]
  2705.            ,[ClientID]
  2706.            ,[Client]
  2707.            ,[MattStatus]
  2708.            ,[CloseDate]
  2709.            ,[Currency]
  2710.            ,[MattCategory]
  2711.            ,[IsEvergreenCCC]
  2712.            ,[EngTypeCCC]
  2713.            ,[EngStatusCCC]
  2714.            ,[EngSignedDateCCC]
  2715.            ,[OpportunityIDCCC]
  2716.            ,[ServiceLine]
  2717.            ,[State]
  2718.            ,[OriginalWIP]
  2719.            ,[AdjustedWIP]
  2720.            ,[MajorIndustry]
  2721.            ,[PBD]
  2722.            ,[SBD]
  2723.            ,[PRD]
  2724.            ,[SRD]
  2725.            ,[PBDAllocationPercent]
  2726.            ,[SBDAllocationPercent]
  2727.            ,[PRDAllocationPercent]
  2728.            ,[SRDAllocationPercent]
  2729.            ,[CPA]
  2730.            ,[CPAPercent]
  2731.            ,[ReferralSource]
  2732.            ,[CPAAlliance]
  2733.            ,[Manufacturing]
  2734.            ,[Architecture]
  2735.            ,[Construction]
  2736.            ,[Engineering]
  2737.            ,[SystemIntegrator]
  2738.            ,[SFAccountID]
  2739.            ,[SFParentAccount]
  2740.            ,[SFChildID]
  2741.            ,[SFChildAccount]
  2742.            ,[CPAID]
  2743.            ,[EAReferral]
  2744.            ,[EATeam]
  2745.            ,[EAIndustry]
  2746.            ,[EAParentName]
  2747.            ,[EAYearattended]
  2748.            ,[EAEventDate]
  2749.            ,[WebinarIPA]
  2750.            ,[EASpeaker]
  2751.            ,try_convert(decimal(5,4),[FeeCap])
  2752.            ,[FeeType]
  2753.            ,[NumberOfEmployees]
  2754.            ,[WIP]
  2755.            ,[Industry]
  2756.            ,[SIC]
  2757.            , convert(datetime, convert(char(35),GETDATE(), 120))
  2758.            ,[HistoricalAlliance]
  2759.            ,[REGION]
  2760.            , [Year]
  2761.            , [Quarter]
  2762.            , [Month]
  2763.            , [Week]
  2764.            , [CPAContact]
  2765.            , [CPANewExistingNewAgain]
  2766.            , [CPAOrignalSignedDate]
  2767.            , [StudyYears]
  2768.            , [RefNo]
  2769.            , [UpdatedWIP]
  2770.            , [ComboWIP]
  2771.            , [Billed]
  2772.            , [Collected]
  2773.            , [AccountReceivable]
  2774.            , [EstimatedCredits]
  2775.            , [AnnualRevenue]
  2776.            , [WorkedWIP]
  2777.         , [PendingInvoices]
  2778.         , [RemainingWIPbasedonhoursworked]
  2779.         , [UnbilledWIP]
  2780.         , [UnbilledWorkedWIP]
  2781.         , [Balance]
  2782.         , [PBDWIPAllocation]
  2783.         , [SBDWIPAllocation]
  2784.         , [SOE1WIPAllocation]
  2785.         , [SOE2WIPAllocation]
  2786.         , [PBDBilledAllocation]
  2787.         , [SBDBilledAllocation]
  2788.         , [SOE1BilledAllocation]
  2789.         , [SOE2BilledAllocation]
  2790.         , [PBDCollections]
  2791.         , [SBDCollections]
  2792.         , [SOE1Collections]
  2793.         , [SOE2Collections]
  2794.         , [OneTimeAdj]
  2795.         , [OpRefSourceRavingFan]
  2796.         ,   [OpRefSourceCPA]
  2797.         ,   [OpRefSourceConference]
  2798.         ,   [OpRefSourceNonConference]
  2799.         ,   [OpRefSourceDirect]
  2800.         ,   [OpRefSourceEA]
  2801.         ,   [OpRefSourceEmployee1]
  2802.         ,   [OpRefSourceEmployee2]
  2803.         ,   [OpRefSourceEmployee3]
  2804.         ,   [OpRefSourceWebsite]
  2805.         ,   [OpRefSourceWebinar]
  2806.         ,   [OpRefSourceReferralSource]
  2807.         , [PM]
  2808.         , [IndustryIntake]
  2809.         , [Percentage]
  2810.         , [AddEG]
  2811.         , [Associations]
  2812.         , [ReferralCategory]
  2813.         , [YearEnd]
  2814.         , [FeeCapPercentageType]
  2815.         ,[Description_SF]
  2816.         ,[Description_3E]
  2817.         ,[Client_SF]
  2818.         ,[Client_3E]
  2819.         ,[EngTypeCCC_SF]
  2820.         ,[EngTypeCCC_3E]
  2821.         ,[EngSignedDateCCC_SF]
  2822.         ,[EngSignedDateCCC_3E]
  2823.         ,[ServiceLine_SF]
  2824.         ,[ServiceLine_3E]
  2825.         ,[State_SF]
  2826.         ,[State_3E]
  2827.         ,[OriginalWIP_SF]
  2828.         ,[OriginalWIP_3E]
  2829.         ,[MajorIndustry_SF]
  2830.         ,[MajorIndustry_3E]
  2831.         ,[CPANewExisting]
  2832.         --,'-1' --[BDMasterOppId]
  2833.         ,[OriginalDate]
  2834.         ,[FO]
  2835.         ,[BDAssist]
  2836.         ,[PBDComPercent]
  2837.         ,[PRDComPercent]
  2838.         ,[SBDComPercent]
  2839.         ,[SRDComPercent]
  2840.         ,[MinTaxYear]
  2841.         ,[RecordNotInOldBDMaster]
  2842.         ,'SF'
  2843.         ,IsCloned_CCC
  2844.         ,MaxTaxYear
  2845.            from #bdmFinalResults where RecordActionFlag = 'I'
  2846. )
  2847.  
  2848. --Logging record insert
  2849. exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'Records Inserted'
  2850.  
  2851. --Getting the data for Update
  2852. --if object_id('tempdb..#bdmMatterToUpdate','U') is not null
  2853. --drop table #bdmMatterToUpdate;
  2854.  
  2855. --if object_id('tempdb..#bdmFinalResultsStr','U') is not null
  2856. --drop table #bdmFinalResultsStr;
  2857.  
  2858. -- --Converting Final Results to varchar
  2859. --select Number, OpportunityIDCCC , AltNumber, DisplayName , Description
  2860. --,try_convert(nvarchar(1000), ClientID) ClientID
  2861. --,try_convert(nvarchar(1000), Client) Client
  2862. --, MattStatus
  2863. --,try_convert(nvarchar(1000), CloseDate) CloseDate
  2864. --, Currency, MattCategory
  2865. --,try_convert(nvarchar(1000), IsEvergreenCCC) IsEvergreenCCC
  2866. --, EngTypeCCC, EngStatusCCC
  2867. --,try_convert(nvarchar(1000), EngSignedDateCCC) EngSignedDateCCC
  2868. --, ServiceLine, State
  2869. --,try_convert(nvarchar(1000), OriginalWIP) OriginalWIP
  2870. --,try_convert(nvarchar(1000), AdjustedWIP) AdjustedWIP
  2871. --,try_convert(nvarchar(1000), UpdatedWIP) UpdatedWIP
  2872. --,try_convert(nvarchar(1000), ComboWIP) ComboWIP
  2873. --,try_convert(nvarchar(1000), Billed) Billed
  2874. --,try_convert(nvarchar(1000), Collected) Collected
  2875. --,try_convert(nvarchar(1000), AccountReceivable) AccountReceivable
  2876. --,try_convert(nvarchar(1000), AnnualRevenue) AnnualRevenue
  2877. --, MajorIndustry, PBD, SBD, PRD, SRD
  2878. --,try_convert(nvarchar(1000), PBDPercent) PBDPercent
  2879. --,try_convert(nvarchar(1000), SBDPercent) SBDPercent
  2880. --,try_convert(nvarchar(1000), PRDPercent) PRDPercent
  2881. --,try_convert(nvarchar(1000), SRDPercent) SRDPercent
  2882. --, CPA
  2883. --,try_convert(nvarchar(1000), CPAPercent) CPAPercent
  2884. --, ReferralSource, CPAAlliance
  2885. --,try_convert(nvarchar(1000), Manufacturing) Manufacturing
  2886. --,try_convert(nvarchar(1000), Architecture) Architecture
  2887. --,try_convert(nvarchar(1000), Construction) Construction
  2888. --,try_convert(nvarchar(1000), Engineering) Engineering
  2889. --,try_convert(nvarchar(1000), SystemIntegrator) SystemIntegrator
  2890. --, SFAccountID, SFParentAccount, SFChildID, SFChildAccount
  2891. --, CPAID
  2892. --, EAReferral, EATeam, EAIndustry, EAParentName, EAYearAttended, EAEventDate, WebinarIPA, EASpeaker
  2893. --,try_convert(nvarchar(1000), FeeCap) FeeCap
  2894. --, FeeType
  2895. --,try_convert(nvarchar(1000), NumberOfEmployees) NumberOfEmployees
  2896. --,try_convert(nvarchar(1000), WIP) WIP
  2897. --, Industry
  2898. --,try_convert(nvarchar(1000), SIC) SIC
  2899. --, HistoricalAlliance
  2900. --, REGION
  2901. --,RecordActionFlag
  2902. --,try_convert(nvarchar(1000), [Year]) [Year]
  2903. --,try_convert(nvarchar(1000), [Quarter]) [Quarter]
  2904. --,try_convert(nvarchar(1000), [Month]) [Month]
  2905. --,try_convert(nvarchar(1000), [Week]) [Week]
  2906. --, CPAContact
  2907. --, CPANewExistingNewAgain
  2908. --, try_convert(nvarchar(1000),CPAOrignalSignedDate) [CPAOrignalSignedDate]
  2909. --, StudyYears
  2910. --, [OpRefSourceRavingFan]
  2911. --, [OpRefSourceCPA]
  2912. --, [OpRefSourceConference]
  2913. --, [OpRefSourceNonConference]
  2914. --, [OpRefSourceDirect]
  2915. --, [OpRefSourceEA]
  2916. --, [OpRefSourceEmployee1]
  2917. --, [OpRefSourceEmployee2]
  2918. --, [OpRefSourceEmployee3]
  2919. --, [OpRefSourceWebsite]
  2920. --, [OpRefSourceWebinar]
  2921. --, [OpRefSourceReferralSource]
  2922. --, try_convert(nvarchar(1), [OneTimeAdj]) [OneTimeAdj]
  2923. --, [PM]
  2924. --, [IndustryIntake]
  2925. --, [Percentage]
  2926. --, [AddEG]
  2927. --, [Associations]
  2928. --, [ReferralCategory]
  2929. --into #bdmFinalResultsStr
  2930. --from #bdmFinalResults where RecordActionFlag is null
  2931.  
  2932. --if object_id('tempdb..#BDMasterSourceStr','U') is not null
  2933. --drop table #BDMasterSourceStr;
  2934. -- --Converting Final Results to varchar
  2935. --select Number, OpportunityIDCCC , AltNumber, DisplayName , Description
  2936. --,try_convert(nvarchar(1000), ClientID) ClientID
  2937. --,try_convert(nvarchar(1000), Client) Client
  2938. --, MattStatus
  2939. --,try_convert(nvarchar(1000), CloseDate) CloseDate
  2940. --, Currency, MattCategory
  2941. --,try_convert(nvarchar(1000), IsEvergreenCCC) IsEvergreenCCC
  2942. --, EngTypeCCC, EngStatusCCC
  2943. --,try_convert(nvarchar(1000), EngSignedDateCCC) EngSignedDateCCC
  2944. --, ServiceLine, State
  2945. --,try_convert(nvarchar(1000), OriginalWIP) OriginalWIP
  2946. --,try_convert(nvarchar(1000), AdjustedWIP) AdjustedWIP
  2947. --,try_convert(nvarchar(1000), UpdatedWIP) UpdatedWIP
  2948. --,try_convert(nvarchar(1000), ComboWIP) ComboWIP
  2949. --,try_convert(nvarchar(1000), Billed) Billed
  2950. --,try_convert(nvarchar(1000), Collected) Collected
  2951. --,try_convert(nvarchar(1000), AccountReceivable)  AccountReceivable
  2952. --,try_convert(nvarchar(1000), AnnualRevenue) AnnualRevenue
  2953. --, MajorIndustry, PBD, SBD, PRD, SRD
  2954. --,try_convert(nvarchar(1000), PBDPercent) PBDPercent
  2955. --,try_convert(nvarchar(1000), SBDPercent) SBDPercent
  2956. --,try_convert(nvarchar(1000), PRDPercent) PRDPercent
  2957. --,try_convert(nvarchar(1000), SRDPercent) SRDPercent
  2958. --, CPA
  2959. --,try_convert(nvarchar(1000), CPAPercent) CPAPercent
  2960. --, ReferralSource, CPAAlliance
  2961. --,try_convert(nvarchar(1000), Manufacturing) Manufacturing
  2962. --,try_convert(nvarchar(1000), Architecture) Architecture
  2963. --,try_convert(nvarchar(1000), Construction) Construction
  2964. --,try_convert(nvarchar(1000), Engineering) Engineering
  2965. --,try_convert(nvarchar(1000), SystemIntegrator) SystemIntegrator
  2966. --, SFAccountID, SFParentAccount, SFChildID, SFChildAccount
  2967. --, CPAID
  2968. --, EAReferral, EATeam, EAIndustry, EAParentName, EAYearAttended, EAEventDate, WebinarIPA, EASpeaker
  2969. --,try_convert(nvarchar(1000), FeeCap) FeeCap
  2970. --, FeeType
  2971. --,try_convert(nvarchar(1000), NumberOfEmployees) NumberOfEmployees
  2972. --,try_convert(nvarchar(1000), WIP) WIP
  2973. --, Industry
  2974. --,try_convert(nvarchar(1000), SIC) SIC
  2975. --, HistoricalAlliance
  2976. --, REGION
  2977. --,try_convert(nvarchar(1000), [Year]) [Year]
  2978. --,try_convert(nvarchar(1000), [Quarter]) [Quarter]
  2979. --,try_convert(nvarchar(1000), [Month]) [Month]
  2980. --,try_convert(nvarchar(1000), [Week]) [Week]
  2981. --, CPAContact
  2982. --, CPANewExistingNewAgain
  2983. --, try_convert(nvarchar(1000),CPAOrignalSignedDate) [CPAOrignalSignedDate]
  2984. --, StudyYears
  2985. --, [OpRefSourceRavingFan]
  2986. --, [OpRefSourceCPA]
  2987. --, [OpRefSourceConference]
  2988. --, [OpRefSourceNonConference]
  2989. --, [OpRefSourceDirect]
  2990. --, [OpRefSourceEA]
  2991. --, [OpRefSourceEmployee1]
  2992. --, [OpRefSourceEmployee2]
  2993. --, [OpRefSourceEmployee3]
  2994. --, [OpRefSourceWebsite]
  2995. --, [OpRefSourceWebinar]
  2996. --, [OpRefSourceReferralSource]
  2997. --, try_convert(nvarchar(1), [OneTimeAdj]) [OneTimeAdj]
  2998. --, [PM]
  2999. --, [IndustryIntake]
  3000. --, [Percentage]
  3001. --, [AddEG]
  3002. --, [Associations]
  3003. --, [ReferralCategory]
  3004. --into #BDMasterSourceStr
  3005. --from BDM.BDMasterSource
  3006.  
  3007. ----Update record exist in BD Master Source Table
  3008. --;WITH TEMPSOURCE AS (
  3009. --  select Number, OpportunityIDCCC, /*[1TimeAdj],*/ colName, value FROM #bdmFinalResultsStr
  3010. --         CROSS APPLY (VALUES (AltNumber, 'AltNumber'), (DisplayName, 'DisplayName'), (Description, 'Description'),(ClientID, 'ClientID'),(Client, 'Client'),(MattStatus, 'MattStatus'),(CloseDate, 'CloseDate'),
  3011. --              (Currency, 'Currency'),(MattCategory, 'MattCategory'),(IsEvergreenCCC, 'IsEvergreenCCC'),(EngTypeCCC, 'EngTypeCCC'),(EngStatusCCC, 'EngStatusCCC'),(EngSignedDateCCC, 'EngSignedDateCCC'),
  3012. --              (OpportunityIDCCC, 'OpportunityIDCCC'),(ServiceLine,'ServiceLine'),(State,'State'),(OriginalWIP,'OriginalWIP'),(AdjustedWIP, 'AdjustedWIP'),(MajorIndustry, 'MajorIndustry'),(PBD,'PBD'),
  3013. --              (SBD,'SBD'),(PRD,'PRD'),(SRD,'SRD'),(PBDPercent,'PBDPercent'),(SBDPercent,'SBDPercent'),(PRDPercent,'PRDPercent'),(SRDPercent,'SRDPercent'),(CPA,'CPA'),(CPAPercent,'CPAPercent'),
  3014. --              (ReferralSource,'ReferralSource'),(CPAAlliance,'CPAAlliance'),(Manufacturing,'Manufacturing'),(Architecture,'Architecture'),(Construction,'Construction'),(Engineering,'Engineering'),
  3015. --              (SystemIntegrator,'SystemIntegrator'),(SFAccountID,'SFAccountID'),(SFParentAccount,'SFParentAccount'),(SFChildID,'SFChildD'),(SFChildAccount,'SFChildAccount'),(CPAID,'CPAID'),(EAReferral,'EAReferral'),
  3016. --              (EATeam,'EATeam'),(EAIndustry,'EAIndustry'),(EAParentName,'EAParentName'),(EAYearAttended,'EAYearAttended'),(EAEventDate,'EAEventDate'),(WebinarIPA,'WebinarIPA'),(EASpeaker,'EASpeaker')
  3017. --              ,(FeeCap,'FeeCap'),(FeeType,'FeeType'),(NumberOfEmployees,'NumberOfEmployees'),(WIP,'WIP'), (Industry,'Industry'), (SIC,'SIC')
  3018. --              ,(HistoricalAlliance,'HistoricalAlliance'),(Region,'Region'), (CPAContact, 'CPAContact'), (CPANewExistingNewAgain,'CPANewExistingNewAgain')
  3019. --              ,(CPAOrignalSignedDate,'CPAOrignalSignedDate'), (StudyYears, 'StudyYears'),(UpdatedWIP, 'UpdatedWIP'),(ComboWIP, 'ComboWIP'),(Billed, 'Billed'),(Collected, 'Collected')
  3020. --              , (AnnualRevenue,'AnnualRevenue')
  3021. --              , (OpRefSourceRavingFan, 'OpRefSourceRavingFan'),(OpRefSourceCPA,'OpRefSourceCPA'),(OpRefSourceConference,'OpRefSourceConference'),(OpRefSourceNonConference,'OpRefSourceNonConference')
  3022. --              ,(OpRefSourceDirect,'OpRefSourceDirect'),(OpRefSourceEA,'OpRefSourceEA'),(OpRefSourceEmployee1,'OpRefSourceEmployee1'),(OpRefSourceEmployee2,'OpRefSourceEmployee2'),(OpRefSourceEmployee3,'OpRefSourceEmployee3')
  3023. --              ,(OpRefSourceWebsite,'OpRefSourceWebsite'),(OpRefSourceWebinar,'OpRefSourceWebinar'),(OpRefSourceReferralSource,'OpRefSourceReferralSource')
  3024. --              ,(OneTimeAdj,'OneTimeAdj'),(PM,'PM'), (IndustryIntake,'IndustryIntake'), (Percentage, 'Percentage'),(AddEG,'AddEG'), (Associations,'Associations'),(ReferralCategory,'ReferralCategory'))
  3025.        
  3026. --              cs (value, colName) WHERE RecordActionFlag IS NULL)
  3027.  
  3028. --,BDMSOURCE AS (
  3029. --  select Number, OpportunityIDCCC,/*[1TimeAdj],*/ colName, value FROM #BDMasterSourceStr
  3030. --         CROSS APPLY ( VALUES (AltNumber, 'AltNumber'), (DisplayName, 'DisplayName'), (Description, 'Description'),(ClientID, 'ClientID'),(Client, 'Client'),(MattStatus, 'MattStatus'),(CloseDate, 'CloseDate'),
  3031. --              (Currency, 'Currency'),(MattCategory, 'MattCategory'),(IsEvergreenCCC, 'IsEvergreenCCC'),(EngTypeCCC, 'EngTypeCCC'),(EngStatusCCC, 'EngStatusCCC'),(EngSignedDateCCC, 'EngSignedDateCCC'),
  3032. --              (OpportunityIDCCC, 'OpportunityIDCCC'),(ServiceLine,'ServiceLine'),(State,'State'),(OriginalWIP,'OriginalWIP'),(AdjustedWIP, 'AdjustedWIP'),(MajorIndustry, 'MajorIndustry'),(PBD,'PBD'),
  3033. --              (SBD,'SBD'),(PRD,'PRD'),(SRD,'SRD'),(PBDPercent,'PBDPercent'),(SBDPercent,'SBDPercent'),(PRDPercent,'PRDPercent'),(SRDPercent,'SRDPercent'),(CPA,'CPA'),(CPAPercent,'CPAPercent'),
  3034. --              (ReferralSource,'ReferralSource'),(CPAAlliance,'CPAAlliance'),(Manufacturing,'Manufacturing'),(Architecture,'Architecture'),(Construction,'Construction'),(Engineering,'Engineering'),
  3035. --              (SystemIntegrator,'SystemIntegrator'),(SFAccountID,'SFAccountID'),(SFParentAccount,'SFParentAccount'),(SFChildID,'SFChildD'),(SFChildAccount,'SFChildAccount'),(CPAID,'CPAID'),(EAReferral,'EAReferral'),
  3036. --              (EATeam,'EATeam'),(EAIndustry,'EAIndustry'),(EAParentName,'EAParentName'),(EAYearAttended,'EAYearAttended'),(EAEventDate,'EAEventDate'),(WebinarIPA,'WebinarIPA'),(EASpeaker,'EASpeaker')
  3037. --              ,(FeeCap,'FeeCap'),(FeeType,'FeeType'),(NumberOfEmployees,'NumberOfEmployees'),(WIP,'WIP'), (Industry,'Industry'), (SIC,'SIC')
  3038. --              ,(HistoricalAlliance,'HistoricalAlliance'),(Region,'Region'), (CPAContact, 'CPAContact'),(CPANewExistingNewAgain,'CPANewExistingNewAgain')
  3039. --              ,(CPAOrignalSignedDate,'CPAOrignalSignedDate'), (StudyYears, 'StudyYears'),(UpdatedWIP, 'UpdatedWIP'), (ComboWIP, 'ComboWIP'),(Billed, 'Billed'),(Collected, 'Collected')
  3040. --              , (AnnualRevenue, 'AnnualRevenue')
  3041. --              , (OpRefSourceRavingFan, 'OpRefSourceRavingFan'),(OpRefSourceCPA,'OpRefSourceCPA'),(OpRefSourceConference,'OpRefSourceConference'),(OpRefSourceNonConference,'OpRefSourceNonConference')
  3042. --              ,(OpRefSourceDirect,'OpRefSourceDirect'),(OpRefSourceEA,'OpRefSourceEA'),(OpRefSourceEmployee1,'OpRefSourceEmployee1'),(OpRefSourceEmployee2,'OpRefSourceEmployee2'),(OpRefSourceEmployee3,'OpRefSourceEmployee3')
  3043. --              ,(OpRefSourceWebsite,'OpRefSourceWebsite'),(OpRefSourceWebinar,'OpRefSourceWebinar'),(OpRefSourceReferralSource,'OpRefSourceReferralSource')
  3044. --              ,(OneTimeAdj,'OneTimeAdj'),(PM,'PM'), (IndustryIntake,'IndustryIntake'), (Percentage, 'Percentage'),(AddEG,'AddEG'), (Associations,'Associations'),(ReferralCategory,'ReferralCategory'))
  3045. --              cs (value, colName))
  3046.  
  3047.  
  3048. --SELECT DISTINCT Number, OpportunityIDCCC--, [1TimeAdj]
  3049. --into #bdmMatterToUpdate
  3050. --from (
  3051. --  SELECT ts.Number, ts.OpportunityIDCCC/*, ts.[1TimeAdj]*/, ts.colName, ts.value as TempValue, bd.value AS BDMValue
  3052. --  FROM TEMPSOURCE ts
  3053. --  INNER JOIN BDMSource bd
  3054. --      on COALESCE(ts.Number,ts.opportunityIdccc) = COALESCE(bd.Number,bd.opportunityidccc) /*and ts.opportunityIdccc = bd.opportunityidccc*/
  3055. --      --and ts.[1TimeAdj] = bd.[1TimeAdj]
  3056. --      and ts.colName = bd.colName and ISnull(ts.value,'') <> Isnull(bd.value, ''))a
  3057.  
  3058. --Update #bdmFinalResults set RecordActionFlag = 'U'
  3059. --FROM #bdmFinalResults b
  3060. --JOIN #bdmMatterToUpdate u
  3061. --on COALESCE(b.Number,b.OpportunityIDCCC) = COALESCE(u.Number,u.OpportunityIDCCC) --and b.OpportunityIDCCC = u.OpportunityIDCCC
  3062. ----and b.[1TimeAdj] = u.[1TimeAdj]
  3063. --WHERE b.RecordActionFlag IS NULL
  3064.  
  3065. Update #bdmFinalResults set RecordActionFlag = 'U'
  3066. where RecordActionFlag IS NULL and RecordForUpdate = 1
  3067.  
  3068. --Update record in BDMasterSource table
  3069. Declare @UpdateResultCount varchar(100);
  3070. SET @UpdateResultCount = (SELECT try_convert(varchar(10),count(*)) + ' to be updated' from #bdmFinalResults where RecordActionFlag = 'U')
  3071. exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = @UpdateResultCount
  3072.  
  3073.  
  3074. /*
  3075. DECLARE  @Number nvarchar(64), @AltNumber nvarchar(64), @DisplayName nvarchar(255), @Description nvarchar(255), @ClientID nvarchar(255),@Client nvarchar(128),@MattStatus nvarchar(64) ,
  3076.             @CloseDate dateTime ,@Currency nvarchar(8) ,@MattCategory nvarchar(16)
  3077.           ,  @IsEvergreenCCC tinyint,@EngTypeCCC nvarchar(64) ,@EngStatusCCC nvarchar(64) ,@EngSignedDateCCC dateTime ,@OpportunityIDCCC nvarchar(64)
  3078.           ,@ServiceLine nvarchar(64),@State nvarchar(64),@OriginalWIP decimal(16, 2),@AdjustedWIP decimal(16, 2)
  3079.           ,@MajorIndustry nvarchar(500), @PBD nvarchar(121) ,@SBD nvarchar(121),@PRD nvarchar(121),@SRD nvarchar(121)
  3080.           ,@PBDAllocationPercent float ,@SBDAllocationPercent float,@PRDAllocationPercent float,@SRDAllocationPercent float, @CPA nvarchar(255) ,@CPAPercent float ,@ReferralSource nvarchar(1500)
  3081.            ,@CPAAlliance nvarchar(121),@Manufacturing bit,@Architecture bit,@Construction bit ,@Engineering bit ,@SystemIntegrator bit
  3082.            , @SFAccountID nvarchar(18) ,@SFParentAccount nvarchar(1500), @SFChildID nvarchar(18), @SFChildAccount nvarchar(1500)
  3083.            , @CPAID nvarchar(18),@EAReferral varchar(1500), @EATeam varchar(1500) ,@EAIndustry varchar(1500),@EAParentName varchar(1500) ,@EAYearAttended varchar(1500)
  3084.            ,@EAEventDate varchar(1500) ,@WebinarIPA varchar(1500),@EASpeaker varchar(1500)
  3085.            ,@FeeCap decimal(5,4),@FeeType nvarchar(200),@NumberOfEmployees int,@WIP decimal(16,2), @Industry nvarchar(1000), @SIC varchar(1500)
  3086.            ,@HistoricalAlliance varchar(1500), @Region varchar(1500), @Year int, @Quarter int, @Month int, @Week int
  3087.            ,@CPAContact varchar(1500), @CPANewExistingNewAgain varchar(200), @CPAOrignalSignedDate DateTime, @StudyYears varchar(10)
  3088.            ,@OpRefSourceEmployee1 varchar(500),@OpRefSourceEmployee2 varchar(500),@OpRefSourceEmployee3 varchar(500)
  3089.            ,@RefNo int, @UpdatedWIP decimal(20,2), @ComboWIP decimal(20,2), @Billed decimal(20,2), @Collected decimal(20,2), @AccountReceivable decimal(20,2)
  3090.            , @EstimatedCredits decimal(20,2), @AnnualRevenue decimal(20,2)
  3091.            ,@WorkedWIP decimal(20,2),@PendingInvoices decimal(20,2), @RemainingWIPbasedonhoursworked decimal(20,2), @UnbilledWIP decimal(20,2)
  3092.            ,@UnbilledWorkedWIP decimal(20,2), @Balance decimal(20,2), @PBDWIPAllocation decimal(20,2), @SBDWIPAllocation decimal(20,2)
  3093.            ,@SOE1WIPAllocation decimal(20,2), @SOE2WIPAllocation decimal(20,2), @PBDBilledAllocation decimal(20,2), @SBDBilledAllocation decimal(20,2)
  3094.            , @SOE1BilledAllocation decimal(20,2), @SOE2BilledAllocation decimal(20,2) , @PBDCollections decimal(20,2), @SBDCollections decimal(20,2)
  3095.            , @SOE1Collections decimal(20,2), @SOE2Collections decimal(20,2)
  3096.            , @OpRefSourceRavingFan varchar(1500),   @OpRefSourceCPA varchar(1500),  @OpRefSourceConference varchar(1500),   @OpRefSourceNonConference varchar(1500)
  3097.             , @OpRefSourceDirect varchar(1500), @OpRefSourceEA varchar(1500),  @OpRefSourceWebsite varchar(1500), @OpRefSourceWebinar varchar(1500), @OpRefSourceReferralSource varchar(1500),
  3098.             @OneTimeAdj varchar(1), @PM varchar(1500), @IndustryIntake varchar(1500), @Percentage varchar(1500), @AddEG int, @Associations varchar(1500), @ReferralCategory varchar(1500)
  3099.             , @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)
  3100.             ,@EngTypeCCC_3E nvarchar(64), @EngSignedDateCCC_SF DateTime, @EngSignedDateCCC_3E DateTime, @ServiceLine_SF nvarchar(64), @ServiceLine_3E nvarchar(64)
  3101.         ,@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)
  3102.         ,@CPANewExisting varchar(1500), @OriginalDate datetime, @FO varchar(1500), @BDAssist nvarchar(1500), @MinTaxYear int
  3103.         ,@PBDComPercent decimal(18,4) ,@SBDComPercent decimal(18,4),@PRDComPercent decimal(18,4),@SRDComPercent decimal(18,4);
  3104.        
  3105. DECLARE @ChangeId int , @FieldName varchar(100), @OrigValue varchar(1500), @ChangeValue varchar(1500), @Flag nvarchar(1500), @ModifiedDate dateTime;
  3106. DECLARE @SQL nvarchar(1000);
  3107. DECLARE @SOURCEVALUE nvarchar(1500);
  3108.  
  3109. DECLARE UpdateSource CURSOR FOR
  3110.     SELECT
  3111.         [Number], [AltNumber],  [DisplayName]   ,   [Description]  ,    [ClientID]  ,   [Client]   ,    [MattStatus]   ,    [CloseDate]  ,  [Currency]   ,
  3112.         [MattCategory]  ,   [IsEvergreenCCC]  , [EngTypeCCC]  , [EngStatusCCC]  ,   [EngSignedDateCCC]  ,   [OpportunityIDCCC]  ,
  3113.         [ServiceLine]  ,    [State]  ,  [OriginalWIP]  ,    [AdjustedWIP]  ,    [MajorIndustry]  ,  [PBD]  ,    [SBD]  ,    [PRD]  ,
  3114.         [SRD]  ,    [PBDAllocationPercent]  ,   [SBDAllocationPercent]  ,   [PRDAllocationPercent]  ,   [SRDAllocationPercent]  ,   [CPA]  ,    [CPAPercent]  ,
  3115.         [ReferralSource]  , [CPAAlliance]  ,    [Manufacturing]  ,  [Architecture]  ,   [Construction]  ,   [Engineering]  ,    [SystemIntegrator]  ,   [SFAccountID]  ,    [SFParentAccount]  ,    [SFChildID]  ,  [SFChildAccount]  , [CPAID]  ,
  3116.         [EAReferral]  , [EATeam]  , [EAIndustry]  , [EAParentName]  ,   [EAYearattended]  , [EAEventDate]  ,
  3117.         [WebinarIPA]  , [EASpeaker], [FeeCap], [FeeType] ,[NumberOfEmployees], [WIP], [Industry], [SIC]
  3118.         , [HistoricalAlliance], [REGION], [Year],[Quarter], [Month], [Week], [CPAContact],[CPANewExistingNewAgain]
  3119.         , [CPAOrignalSignedDate], [StudyYears], [OpRefSourceEmployee1], [OpRefSourceEmployee2], [OpRefSourceEmployee3]
  3120.         , [RefNo],[UpdatedWIP], [ComboWIP], [Billed],[Collected],[AccountReceivable], [EstimatedCredits], [AnnualRevenue]
  3121.         , [WorkedWIP], [PendingInvoices], [RemainingWIPbasedonhoursworked], [UnbilledWIP]
  3122.            ,[UnbilledWorkedWIP], [Balance], [PBDWIPAllocation], [SBDWIPAllocation]
  3123.            ,[SOE1WIPAllocation], [SOE2WIPAllocation], [PBDBilledAllocation] , [SBDBilledAllocation]
  3124.            , [SOE1BilledAllocation], [SOE2BilledAllocation] , [PBDCollections], [SBDCollections]
  3125.            , [SOE1Collections], [SOE2Collections]
  3126.         , [OpRefSourceRavingFan],   [OpRefSourceCPA],   [OpRefSourceConference],    [OpRefSourceNonConference]
  3127.             , [OpRefSourceDirect],  [OpRefSourceEA], [OpRefSourceWebsite], [OpRefSourceWebinar], [OpRefSourceReferralSource]
  3128.             ,[OneTimeAdj], [PM], [IndustryIntake], [Percentage], [AddEG], [Associations], [ReferralCategory], [YearEnd],[FeeCapPercentageType]
  3129.             ,[Description_SF]   ,[Description_3E]   ,[Client_SF]    ,[Client_3E]    ,[EngTypeCCC_SF]    ,[EngTypeCCC_3E]    ,[EngSignedDateCCC_SF]
  3130.         ,[EngSignedDateCCC_3E]  ,[ServiceLine_SF]       ,[ServiceLine_3E]       ,[State_SF]     ,[State_3E]     ,[OriginalWIP_SF]       ,[OriginalWIP_3E]
  3131.         ,[MajorIndustry_SF]     ,[MajorIndustry_3E], [CPANewExisting], [OriginalDate],[FO], [BDAssist],[MinTaxYear],[PBDComPercent],[SBDComPercent],[PRDComPercent],[SRDComPercent]
  3132.     FROM #bdmFinalResults where RecordActionFlag = 'U'
  3133.  
  3134. OPEN UpdateSource
  3135.  
  3136. FETCH NEXT FROM UpdateSource INTO
  3137.         @Number, @AltNumber , @DisplayName , @Description , @ClientID ,@Client ,@MattStatus ,
  3138.             @CloseDate  ,@Currency ,@MattCategory ,  @IsEvergreenCCC ,@EngTypeCCC  ,@EngStatusCCC  ,@EngSignedDateCCC ,@OpportunityIDCCC
  3139.           ,@ServiceLine ,@State ,@OriginalWIP ,@AdjustedWIP  ,@MajorIndustry , @PBD  ,@SBD ,@PRD ,@SRD
  3140.           ,@PBDAllocationPercent  ,@SBDAllocationPercent ,@PRDAllocationPercent ,@SRDAllocationPercent , @CPA  ,@CPAPercent  ,@ReferralSource
  3141.            ,@CPAAlliance ,@Manufacturing ,@Architecture ,@Construction  ,@Engineering  ,@SystemIntegrator  
  3142.            , @SFAccountID  ,@SFParentAccount , @SFChildID , @SFChildAccount , @CPAID ,@EAReferral , @EATeam ,@EAIndustry ,@EAParentName  ,
  3143.            @EAYearAttended ,@EAEventDate  ,@WebinarIPA ,@EASpeaker , @FeeCap, @FeeType ,@NumberOfEmployees, @WIP, @Industry, @SIC
  3144.            , @HistoricalAlliance, @Region, @Year, @Quarter, @Month, @Week, @CPAContact, @CPANewExistingNewAgain,@CPAOrignalSignedDate, @StudyYears
  3145.            , @OpRefSourceEmployee1, @OpRefSourceEmployee2, @OpRefSourceEmployee3
  3146.            , @RefNo, @UpdatedWIP, @ComboWIP, @Billed, @Collected, @AccountReceivable
  3147.            , @EstimatedCredits, @AnnualRevenue
  3148.            , @WorkedWIP ,@PendingInvoices , @RemainingWIPbasedonhoursworked , @UnbilledWIP
  3149.            ,@UnbilledWorkedWIP , @Balance , @PBDWIPAllocation , @SBDWIPAllocation
  3150.            ,@SOE1WIPAllocation , @SOE2WIPAllocation , @PBDBilledAllocation , @SBDBilledAllocation
  3151.            , @SOE1BilledAllocation , @SOE2BilledAllocation , @PBDCollections , @SBDCollections
  3152.            , @SOE1Collections , @SOE2Collections
  3153.            , @OpRefSourceRavingFan ,    @OpRefSourceCPA ,   @OpRefSourceConference ,    @OpRefSourceNonConference  
  3154.             , @OpRefSourceDirect ,  @OpRefSourceEA ,@OpRefSourceWebsite, @OpRefSourceWebinar, @OpRefSourceReferralSource, @OneTimeAdj, @PM
  3155.             , @IndustryIntake , @Percentage , @AddEG , @Associations , @ReferralCategory, @YearEnd, @FeeCapPercentageType
  3156.             , @Description_SF, @Description_3E , @Client_SF, @Client_3E, @EngTypeCCC_SF,
  3157.             @EngTypeCCC_3E, @EngSignedDateCCC_SF, @EngSignedDateCCC_3E, @ServiceLine_SF, @ServiceLine_3E
  3158.         ,@State_SF , @State_3E , @OriginalWIP_SF , @OriginalWIP_3E , @MajorIndustry_SF , @MajorIndustry_3E , @CPANewExisting, @OriginalDate
  3159.         ,@FO, @BDAssist, @MinTaxYear, @PBDComPercent, @SBDComPercent, @PRDComPercent, @SRDComPercent
  3160. WHILE @@FETCH_STATUS = 0
  3161. BEGIN
  3162.     BEGIN TRY
  3163.    
  3164.     exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'Updating results in Source table'
  3165.     Update [bdm].[BDMasterSource] set
  3166.          [AltNumber] = @AltNumber,  [DisplayName] = @DisplayName  , [Description] = @Description , [ClientID] = @ClientID  
  3167.         , [Client]  = @Client  ,    [MattStatus] =  @MattStatus  ,  [CloseDate] =  @CloseDate , [Currency] = @Currency   , [MattCategory] =@MattCategory
  3168.         ,   [IsEvergreenCCC] = @IsEvergreenCCC  ,   [EngTypeCCC] =  @EngTypeCCC ,   [EngStatusCCC]  = @EngStatusCCC ,   [EngSignedDateCCC] = @EngSignedDateCCC
  3169.         ,   [OpportunityIDCCC] =  @OpportunityIDCCC,    [ServiceLine] =  @ServiceLine , [State]  = @State,  [OriginalWIP] =  @OriginalWIP,  [AdjustedWIP]  = @AdjustedWIP
  3170.         ,   [MajorIndustry] =  @MajorIndustry,  [PBD] = @PBD  , [SBD] = @SBD ,  [PRD]  = @PRD,      [SRD] = @SRD ,  [PBDAllocationPercent]  = @PBDAllocationPercent
  3171.         ,   [SBDAllocationPercent] = @SBDAllocationPercent ,    [PRDAllocationPercent]  = @PRDAllocationPercent,    [SRDAllocationPercent]  = @SRDAllocationPercent,    [CPA] = @CPA ,  [CPAPercent]  = @CPAPercent
  3172.         ,   [ReferralSource] =@ReferralSource  ,    [CPAAlliance] = @CPAAlliance ,  [Manufacturing] = @Manufacturing  , [Architecture] = @Architecture
  3173.         ,   [Construction] = @Construction ,    [Engineering] = @Engineering  , [SystemIntegrator] = @SystemIntegrator ,    [SFAccountID]  = @SFAccountID  
  3174.         , [SFParentAccount]  = @SFParentAccount ,   [SFChildID] = @SFChildID ,  [SFChildAccount]  = @SFChildAccount,    [CPAID] = @CPAID
  3175.         , [EAReferral]  = @EAReferral,  [EATeam] = @EATeam ,    [EAIndustry] = @EAIndustry ,    [EAParentName]  = @EAParentName,   
  3176.         [EAYearAttended] = @EAYearAttended ,    [EAEventDate] = @EAEventDate , [WebinarIPA]   =     @WebinarIPA
  3177.         ,   [EASpeaker] = @EASpeaker, [FeeCap] = @FeeCap, [FeeType] = @FeeType , [NumberOfEmployees] = @NumberOfEmployees
  3178.         , [WIP] = @WIP, [Industry] = @Industry, [SIC] = @SIC , LastUpdatedDate = convert(datetime, convert(char(35),GETDATE(), 120)) --GETDATE()
  3179.         , [HistoricalAlliance] = @HistoricalAlliance, [REGION] = @Region, [Year] = @Year, [Quarter]= @Quarter, [Month] = @Month, [Week] = @Week
  3180.         , [CPAContact] = @CPAContact, [CPANewExistingNewAgain] = @CPANewExistingNewAgain, [CPAOrignalSignedDate] = @CPAOrignalSignedDate
  3181.         , [StudyYears] = @StudyYears, [OpRefSourceEmployee1] = @OpRefSourceEmployee1 , [OpRefSourceEmployee2] = @OpRefSourceEmployee2, [OpRefSourceEmployee3] = @OpRefSourceEmployee3
  3182.         , [RefNo] = @RefNo,[UpdatedWIP] =@UpdatedWIP, [ComboWIP] = @ComboWIP, [Billed] = @Billed, [Collected] = @Collected, [AccountReceivable] = @AccountReceivable
  3183.         , [EstimatedCredits] = @EstimatedCredits, [AnnualRevenue] = @AnnualRevenue
  3184.         , [WorkedWIP] = @WorkedWIP , [PendingInvoices] = @PendingInvoices , [RemainingWIPbasedonhoursworked] = @RemainingWIPbasedonhoursworked , [UnbilledWIP] = @UnbilledWIP
  3185.            ,[UnbilledWorkedWIP] =  @UnbilledWorkedWIP , [Balance] = @Balance , [PBDWIPAllocation] = @PBDWIPAllocation , [SBDWIPAllocation] = @SBDWIPAllocation
  3186.            ,[SOE1WIPAllocation] = @SOE1WIPAllocation , [SOE2WIPAllocation] = @SOE2WIPAllocation , [PBDBilledAllocation] =  @PBDBilledAllocation , [SBDBilledAllocation] =  @SBDBilledAllocation
  3187.            , [SOE1BilledAllocation] = @SOE1BilledAllocation , [SOE2BilledAllocation] = @SOE2BilledAllocation , [PBDCollections] = @PBDCollections , [SBDCollections] = @SBDCollections
  3188.            , [SOE1Collections] = @SOE1Collections , [SOE2Collections] = @SOE2Collections
  3189.            , [OneTimeAdj] = @OneTimeAdj, [PM] = @PM, [OpRefSourceWebsite] = @OpRefSourceWebsite, [OpRefSourceWebinar] = @OpRefSourceWebinar, [OpRefSourceReferralSource] = @OpRefSourceReferralSource
  3190.            , [IndustryIntake] = @IndustryIntake, [Percentage] = @Percentage, [AddEG] = @AddEG, [Associations] = @Associations, [ReferralCategory] = @ReferralCategory
  3191.            , [YearEnd] = @YearEnd, [FeeCapPercentageType] = @FeeCapPercentageType
  3192.            ,[Description_SF]    = @Description_SF,[Description_3E]  = @Description_3E ,[Client_SF] = @Client_SF ,[Client_3E] = @Client_3E
  3193.            ,[EngTypeCCC_SF]  = @EngTypeCCC_SF ,[EngTypeCCC_3E]  = @EngTypeCCC_3E,[EngSignedDateCCC_SF] = @EngSignedDateCCC_SF
  3194.         ,[EngSignedDateCCC_3E]  = @EngSignedDateCCC_3E ,[ServiceLine_SF] = @ServiceLine_SF  ,[ServiceLine_3E] = @ServiceLine_3E
  3195.         ,[State_SF] = @State_SF ,[State_3E] = @State_3E ,[OriginalWIP_SF] = @OriginalWIP_SF     ,[OriginalWIP_3E] = @OriginalWIP_3E
  3196.         ,[MajorIndustry_SF]  = @MajorIndustry_SF    ,[MajorIndustry_3E] = @MajorIndustry_3E, [CPANewExisting] = @CPANewExisting
  3197.         ,[OriginalDate] = @OriginalDate, [FO] = @FO, [BDAssist] = @BDAssist, [PBDComPercent] = @PBDComPercent, [SBDComPercent] = @SBDComPercent, [PRDComPercent] = @PRDComPercent, [SRDComPercent] = @SRDComPercent
  3198.  
  3199.         where COALESCE(Number,OpportunityIDCCC) = COALESCE(@Number,@OpportunityIDCCC) --and OpportunityIDCCC = @OpportunityIDCCC --and [1TImeAdj] = @1TimeAdj
  3200.         and MinTaxYear = @MinTaxYear
  3201.  
  3202.         DECLARE INNER_CURSOR CURSOR FOR SELECT ChangeId, FieldName, OrigValue, ChangeValue, Flag, ModifiedDate
  3203.                                         from (SELECT ChangeId, FieldName, OrigValue, ChangeValue, Flag, ModifiedDate,
  3204.                                         ROW_NUMBER() OVER(PARTITION BY MatterNumber, OpportunityID, FieldName order by ModifiedDate DESC) rn
  3205.                                         from [bdm].BDMasterChange where COALESCE(MatterNumber,OpportunityID) = COALESCE(@Number,@OpportunityIDCCC) /*and OpportunityID = @OpportunityIDCCC*/)rec where rn = 1 and flag in ('Edit From App', 'Match')
  3206.            
  3207.             OPEN INNER_CURSOR
  3208.             FETCH NEXT FROM INNER_CURSOR INTO @ChangeId, @FieldName, @OrigValue, @ChangeValue, @Flag, @ModifiedDate
  3209.             WHILE @@FETCH_STATUS = 0
  3210.             BEGIN
  3211.                
  3212.                 SET @SQL = 'SELECT TOP 1 @SourceValue=' + REPLACE(@FieldName,'SFChildD','SFChildID') + ' from [bdm].[BDMasterSource] where COALESCE(Number,OpportunityIDCCC)  = COALESCE(''' + @Number + ''' , ''' + @OpportunityIDCCC + ''')'
  3213.                 PRINT @SQL;
  3214.                 EXEC sp_executesql @SQL, N'@FieldName nvarchar(1500), @SourceValue nvarchar(1500) OUTPUT', @FieldName = @FieldName, @SourceValue = @SourceValue OUTPUT
  3215.                
  3216.                 --Compare if value are matching and set flag to
  3217.                 IF( @Flag = 'Edit From App' and @SourceValue = @ChangeValue)
  3218.                     BEGIN
  3219.                     --Update query and set flag to 'Match'
  3220.                         UPDATE [bdm].BDMasterChange set Flag = 'Match', MatchFlagSetDate = GETDATE()  where ChangeId = @ChangeId --MatterNumber = @Number
  3221.                             --and OpportunityID = @OpportunityID_CCC and Flag = 'Edit From App' and FieldName = @FieldName and ModifiedDate = @ModifiedDate
  3222.                     END
  3223.                 ELSE IF (@Flag = 'Match' and @SourceValue <> @ChangeValue)
  3224.                     BEGIN
  3225.                     --Update query and set flag to 'Source'
  3226.                         UPDATE [bdm].BDMasterChange set Flag = 'Source' where ChangeId = @ChangeId -- MatterNumber = @Number
  3227.                             --and OpportunityID = @OpportunityID_CCC and Flag = 'Match' and FieldName = @FieldName and ModifiedDate = @ModifiedDate
  3228.                     END
  3229.                
  3230.                 FETCH NEXT FROM INNER_CURSOR INTO @ChangeId, @FieldName, @OrigValue, @ChangeValue, @Flag, @ModifiedDate
  3231.             END
  3232.             CLOSE INNER_CURSOR
  3233.             DEALLOCATE INNER_CURSOR
  3234.     END TRY
  3235.  
  3236.     BEGIN CATCH
  3237.         exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'ERROR', @Details = 'Error Processing Records. Please check.'
  3238.     END CATCH
  3239.  
  3240.     FETCH NEXT FROM UpdateSource INTO
  3241.         @Number, @AltNumber , @DisplayName , @Description , @ClientID ,@Client ,@MattStatus ,
  3242.             @CloseDate  ,@Currency ,@MattCategory ,  @IsEvergreenCCC ,@EngTypeCCC  ,@EngStatusCCC  ,@EngSignedDateCCC ,@OpportunityIDCCC
  3243.           ,@ServiceLine ,@State ,@OriginalWIP ,@AdjustedWIP  ,@MajorIndustry , @PBD  ,@SBD ,@PRD ,@SRD
  3244.           ,@PBDAllocationPercent  ,@SBDAllocationPercent ,@PRDAllocationPercent ,@SRDAllocationPercent , @CPA  ,@CPAPercent  ,@ReferralSource
  3245.            ,@CPAAlliance ,@Manufacturing ,@Architecture ,@Construction  ,@Engineering  ,@SystemIntegrator  
  3246.            , @SFAccountID  ,@SFParentAccount , @SFChildID , @SFChildAccount , @CPAID ,@EAReferral , @EATeam ,@EAIndustry ,@EAParentName  ,
  3247.            @EAYearAttended ,@EAEventDate  ,@WebinarIPA ,@EASpeaker, @FeeCap, @FeeType ,@NumberOfEmployees, @WIP, @Industry , @SIC
  3248.         , @HistoricalAlliance, @Region, @Year, @Quarter, @Month, @Week, @CPAContact, @CPANewExistingNewAgain, @CPAOrignalSignedDate
  3249.         , @StudyYears, @OpRefSourceEmployee1,@OpRefSourceEmployee2,@OpRefSourceEmployee3
  3250.         , @RefNo, @UpdatedWIP, @ComboWIP, @Billed, @Collected, @AccountReceivable
  3251.         , @EstimatedCredits, @AnnualRevenue
  3252.         , @WorkedWIP ,@PendingInvoices , @RemainingWIPbasedonhoursworked , @UnbilledWIP
  3253.            ,@UnbilledWorkedWIP , @Balance , @PBDWIPAllocation , @SBDWIPAllocation
  3254.            ,@SOE1WIPAllocation , @SOE2WIPAllocation , @PBDBilledAllocation , @SBDBilledAllocation
  3255.            , @SOE1BilledAllocation , @SOE2BilledAllocation , @PBDCollections , @SBDCollections
  3256.            , @SOE1Collections , @SOE2Collections
  3257.            , @OpRefSourceRavingFan ,    @OpRefSourceCPA ,   @OpRefSourceConference ,    @OpRefSourceNonConference  
  3258.             , @OpRefSourceDirect ,  @OpRefSourceEA ,@OpRefSourceWebsite, @OpRefSourceWebinar, @OpRefSourceReferralSource, @OneTimeAdj, @PM
  3259.             , @IndustryIntake , @Percentage , @AddEG , @Associations , @ReferralCategory, @YearEnd, @FeeCapPercentageType
  3260.             , @Description_SF, @Description_3E , @Client_SF, @Client_3E, @EngTypeCCC_SF,
  3261.             @EngTypeCCC_3E, @EngSignedDateCCC_SF, @EngSignedDateCCC_3E, @ServiceLine_SF, @ServiceLine_3E
  3262.         ,@State_SF , @State_3E , @OriginalWIP_SF , @OriginalWIP_3E , @MajorIndustry_SF , @MajorIndustry_3E, @CPANewExisting
  3263.         ,@OriginalDate, @FO, @BDAssist, @MinTaxYear, @PBDComPercent, @SBDComPercent, @PRDComPercent, @SRDComPercent
  3264. END
  3265.  
  3266. CLOSE UpdateSource
  3267. DEALLOCATE UpdateSource
  3268. */
  3269. -----CURSOR Replacement------
  3270.  
  3271.     Update BMS set
  3272.          [AltNumber] = BFR.AltNumber,   [DisplayName] = BFR.DisplayName  ,  [Description] = BFR.Description , [ClientID] = BFR.ClientID  
  3273.         , [Client]  = BFR.Client  , [MattStatus] =  BFR.MattStatus  ,   [CloseDate] =  BFR.CloseDate[Currency] = BFR.Currency   , [MattCategory] =BFR.MattCategory
  3274.         ,   [IsEvergreenCCC] = BFR.IsEvergreenCCC  ,    [EngTypeCCC] =  BFR.EngTypeCCC ,    [EngStatusCCC]  = BFR.EngStatusCCC ,    [EngSignedDateCCC] = BFR.EngSignedDateCCC
  3275.         ,   [OpportunityIDCCC] =  BFR.OpportunityIDCCC, [ServiceLine] =  BFR.ServiceLine[State]  = BFR.State,   [OriginalWIP] =  BFR.OriginalWIP,   [AdjustedWIP]  = BFR.AdjustedWIP
  3276.         ,   [MajorIndustry] =  BFR.MajorIndustry,   [PBD] = BFR.PBD  ,  [SBD] = BFR.SBD ,   [PRD]  = BFR.PRD,       [SRD] = BFR.SRD ,   [PBDAllocationPercent]  = BFR.PBDAllocationPercent
  3277.         ,   [SBDAllocationPercent] = BFR.SBDAllocationPercent , [PRDAllocationPercent]  = BFR.PRDAllocationPercent, [SRDAllocationPercent]  = BFR.SRDAllocationPercent, [CPA] = BFR.CPA ,   [CPAPercent]  = BFR.CPAPercent
  3278.         ,   [ReferralSource] =BFR.ReferralSource  , [CPAAlliance] = BFR.CPAAlliance ,   [Manufacturing] = BFR.Manufacturing  ,  [Architecture] = BFR.Architecture
  3279.         ,   [Construction] = BFR.Construction , [Engineering] = BFR.Engineering  ,  [SystemIntegrator] = BFR.SystemIntegrator , [SFAccountID]  = BFR.SFAccountID   
  3280.         , [SFParentAccount]  = BFR.SFParentAccount ,    [SFChildID] = BFR.SFChildID ,   [SFChildAccount]  = BFR.SFChildAccount, [CPAID] = BFR.CPAID
  3281.         , [EAReferral]  = BFR.EAReferral,   [EATeam] = BFR.EATeam , [EAIndustry] = BFR.EAIndustry , [EAParentName]  = BFR.EAParentName,
  3282.         [EAYearAttended] = BFR.EAYearAttended , [EAEventDate] = BFR.EAEventDate , [WebinarIPA]   =  BFR.WebinarIPA
  3283.         ,   [EASpeaker] = BFR.EASpeaker, [FeeCap] = BFR.FeeCap, [FeeType] = BFR.FeeType , [NumberOfEmployees] = BFR.NumberOfEmployees
  3284.         , [WIP] = BFR.WIP, [Industry] = BFR.Industry, [SIC] = BFR.SIC , LastUpdatedDate = convert(datetime, convert(char(35),GETDATE(), 120)) --GETDATE()
  3285.         , [HistoricalAlliance] = BFR.HistoricalAlliance, [REGION] = BFR.Region, [Year] = BFR.Year, [Quarter]= BFR.Quarter, [Month] = BFR.Month, [Week] = BFR.Week
  3286.         , [CPAContact] = BFR.CPAContact, [CPANewExistingNewAgain] = BFR.CPANewExistingNewAgain, [CPAOrignalSignedDate] = BFR.CPAOrignalSignedDate
  3287.         , [StudyYears] = BFR.StudyYears, [OpRefSourceEmployee1] = BFR.OpRefSourceEmployee1 , [OpRefSourceEmployee2] = BFR.OpRefSourceEmployee2, [OpRefSourceEmployee3] = BFR.OpRefSourceEmployee3
  3288.         , [RefNo] = BFR.RefNo,[UpdatedWIP] =BFR.UpdatedWIP, [ComboWIP] = BFR.ComboWIP, [Billed] = BFR.Billed, [Collected] = BFR.Collected, [AccountReceivable] = BFR.AccountReceivable
  3289.         , [EstimatedCredits] = BFR.EstimatedCredits, [AnnualRevenue] = BFR.AnnualRevenue
  3290.         , [WorkedWIP] = BFR.WorkedWIP , [PendingInvoices] = BFR.PendingInvoices , [RemainingWIPbasedonhoursworked] = BFR.RemainingWIPbasedonhoursworked , [UnbilledWIP] = BFR.UnbilledWIP
  3291.            ,[UnbilledWorkedWIP] =  BFR.UnbilledWorkedWIP , [Balance] = BFR.Balance , [PBDWIPAllocation] = BFR.PBDWIPAllocation , [SBDWIPAllocation] = BFR.SBDWIPAllocation
  3292.            ,[SOE1WIPAllocation] = BFR.SOE1WIPAllocation , [SOE2WIPAllocation] = BFR.SOE2WIPAllocation , [PBDBilledAllocation] =  BFR.PBDBilledAllocation , [SBDBilledAllocation] =  BFR.SBDBilledAllocation
  3293.            , [SOE1BilledAllocation] = BFR.SOE1BilledAllocation , [SOE2BilledAllocation] = BFR.SOE2BilledAllocation , [PBDCollections] = BFR.PBDCollections , [SBDCollections] = BFR.SBDCollections
  3294.            , [SOE1Collections] = BFR.SOE1Collections , [SOE2Collections] = BFR.SOE2Collections
  3295.            , [OneTimeAdj] = BFR.OneTimeAdj, [PM] = BFR.PM, [OpRefSourceWebsite] = BFR.OpRefSourceWebsite, [OpRefSourceWebinar] = BFR.OpRefSourceWebinar, [OpRefSourceReferralSource] = BFR.OpRefSourceReferralSource
  3296.            , [IndustryIntake] = BFR.IndustryIntake, [Percentage] = BFR.Percentage, [AddEG] = BFR.AddEG, [Associations] = BFR.Associations, [ReferralCategory] = BFR.ReferralCategory
  3297.            , [YearEnd] = BFR.YearEnd, [FeeCapPercentageType] = BFR.FeeCapPercentageType
  3298.            ,[Description_SF]    = BFR.Description_SF,[Description_3E]   = BFR.Description_3E ,[Client_SF] = BFR.Client_SF   ,[Client_3E] = BFR.Client_3E
  3299.            ,[EngTypeCCC_SF]  = BFR.EngTypeCCC_SF ,[EngTypeCCC_3E]   = BFR.EngTypeCCC_3E,[EngSignedDateCCC_SF] = BFR.EngSignedDateCCC_SF
  3300.         ,[EngSignedDateCCC_3E]  = BFR.EngSignedDateCCC_3E ,[ServiceLine_SF] = BFR.ServiceLine_SF    ,[ServiceLine_3E] = BFR.ServiceLine_3E
  3301.         ,[State_SF] = BFR.State_SF  ,[State_3E] = BFR.State_3E  ,[OriginalWIP_SF] = BFR.OriginalWIP_SF      ,[OriginalWIP_3E] = BFR.OriginalWIP_3E
  3302.         ,[MajorIndustry_SF]  = BFR.MajorIndustry_SF ,[MajorIndustry_3E] = BFR.MajorIndustry_3E, [CPANewExisting] = BFR.CPANewExisting
  3303.         ,[OriginalDate] = BFR.OriginalDate, [FO] = BFR.FO, [BDAssist] = BFR.BDAssist, [PBDComPercent] = BFR.PBDComPercent, [SBDComPercent] = BFR.SBDComPercent, [PRDComPercent] = BFR.PRDComPercent, [SRDComPercent] = BFR.SRDComPercent
  3304.         ,IsCloned_CCC = BFR.IsCloned_CCC
  3305.         ,MaxTaxYear = BFR.MaxTaxYear
  3306.  
  3307.         FROM
  3308.         [bdm].[BDMasterSource] BMS
  3309.         JOIN
  3310.         #bdmFinalResults BFR on BFR.RecordActionFlag = 'U'
  3311.         AND COALESCE(BMS.Number,BMS.OpportunityIDCCC) = COALESCE(BFR.Number,BFR.OpportunityIDCCC)
  3312.         and BMS.MinTaxYear = BFR.MinTaxYear
  3313.  
  3314.  
  3315.  
  3316. if object_id('tempdb.dbo.#FlagChanges','U') is not null
  3317. drop table #FlagChanges;
  3318. SELECT ChangeId
  3319. ,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
  3320. ,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
  3321. INTO #FlagChanges
  3322. FROM
  3323. (
  3324. SELECT [ID]
  3325.       ,[MattIndex]
  3326.       ,[Number]
  3327.       ,      [OpportunityIDCCC]
  3328.       ,CAST([AltNumber] as nvarchar(4000)) [AltNumber]
  3329. ,CAST(      [DisplayName] as nvarchar(4000))       [DisplayName]
  3330. ,CAST(      [Description] as nvarchar(4000))       [Description]
  3331. ,CAST(      [ClientID] as nvarchar(4000))       [ClientID]
  3332. ,CAST(      [Client] as nvarchar(4000))       [Client]
  3333. ,CAST(      [MattStatus] as nvarchar(4000))       [MattStatus]
  3334. ,CAST(      [CloseDate] as nvarchar(4000))       [CloseDate]
  3335. ,CAST(      [Currency] as nvarchar(4000))       [Currency]
  3336. ,CAST(      [MattCategory] as nvarchar(4000))       [MattCategory]
  3337. ,CAST(      [IsEvergreenCCC] as nvarchar(4000))       [IsEvergreenCCC]
  3338. ,CAST(      [EngTypeCCC] as nvarchar(4000))       [EngTypeCCC]
  3339. ,CAST(      [EngStatusCCC] as nvarchar(4000))       [EngStatusCCC]
  3340. ,CAST(      [EngSignedDateCCC] as nvarchar(4000))       [EngSignedDateCCC]
  3341.  
  3342. ,CAST(      [ServiceLine] as nvarchar(4000))       [ServiceLine]
  3343. ,CAST(      [State] as nvarchar(4000))       [State]
  3344. ,CAST(      [OriginalWIP] as nvarchar(4000))       [OriginalWIP]
  3345. ,CAST(      [AdjustedWIP] as nvarchar(4000))       [AdjustedWIP]
  3346. ,CAST(      [MajorIndustry] as nvarchar(4000))       [MajorIndustry]
  3347. ,CAST(      [PBD] as nvarchar(4000))       [PBD]
  3348. ,CAST(      [SBD] as nvarchar(4000))       [SBD]
  3349. ,CAST(      [PRD] as nvarchar(4000))       [PRD]
  3350. ,CAST(      [SRD] as nvarchar(4000))       [SRD]
  3351. ,CAST(      [CPA] as nvarchar(4000))       [CPA]
  3352. ,CAST(      [CPAPercent] as nvarchar(4000))       [CPAPercent]
  3353. ,CAST(      [ReferralSource] as nvarchar(4000))       [ReferralSource]
  3354. ,CAST(      [CPAAlliance] as nvarchar(4000))       [CPAAlliance]
  3355. ,CAST(      [Manufacturing] as nvarchar(4000))       [Manufacturing]
  3356. ,CAST(      [Architecture] as nvarchar(4000))       [Architecture]
  3357. ,CAST(      [Construction] as nvarchar(4000))       [Construction]
  3358. ,CAST(      [Engineering] as nvarchar(4000))       [Engineering]
  3359. ,CAST(      [SystemIntegrator] as nvarchar(4000))       [SystemIntegrator]
  3360. ,CAST(      [SFAccountID] as nvarchar(4000))       [SFAccountID]
  3361. ,CAST(      [SFParentAccount] as nvarchar(4000))       [SFParentAccount]
  3362. ,CAST(      [SFChildID] as nvarchar(4000))       [SFChildID]
  3363. ,CAST(      [SFChildAccount] as nvarchar(4000))       [SFChildAccount]
  3364. ,CAST(      [EAReferral] as nvarchar(4000))       [EAReferral]
  3365. ,CAST(      [EATeam] as nvarchar(4000))       [EATeam]
  3366. ,CAST(      [EAIndustry] as nvarchar(4000))       [EAIndustry]
  3367. ,CAST(      [EAParentName] as nvarchar(4000))       [EAParentName]
  3368. ,CAST(      [EAYearAttended] as nvarchar(4000))       [EAYearAttended]
  3369. ,CAST(      [EAEventDate] as nvarchar(4000))       [EAEventDate]
  3370. ,CAST(      [WebinarIPA] as nvarchar(4000))       [WebinarIPA]
  3371. ,CAST(      [EASpeaker] as nvarchar(4000))       [EASpeaker]
  3372. ,CAST(      [FeeType] as nvarchar(4000))       [FeeType]
  3373. ,CAST(      [WIP] as nvarchar(4000))       [WIP]
  3374. ,CAST(      [Industry] as nvarchar(4000))       [Industry]
  3375. ,CAST(      [NumberOfEmployees] as nvarchar(4000))       [NumberOfEmployees]
  3376. ,CAST(      [FeeCap] as nvarchar(4000))       [FeeCap]
  3377. ,CAST(      [SIC] as nvarchar(4000))       [SIC]
  3378. ,CAST(      [RefNo] as nvarchar(4000))       [RefNo]
  3379. ,CAST(      [Year] as nvarchar(4000))       [Year]
  3380. ,CAST(      [NewCount] as nvarchar(4000))       [NewCount]
  3381. ,CAST(      [UpdatedWIP] as nvarchar(4000))       [UpdatedWIP]
  3382. ,CAST(      [ComboWIP] as nvarchar(4000))       [ComboWIP]
  3383. ,CAST(      [Billed] as nvarchar(4000))       [Billed]
  3384. ,CAST(      [Collected] as nvarchar(4000))       [Collected]
  3385. ,CAST(      [AccountReceivable] as nvarchar(4000))       [AccountReceivable]
  3386. ,CAST(      [Variance] as nvarchar(4000))       [Variance]
  3387. ,CAST(      [CPAContact] as nvarchar(4000))       [CPAContact]
  3388. ,CAST(      [IndustryIntake] as nvarchar(4000))       [IndustryIntake]
  3389. ,CAST(      [TypeMG] as nvarchar(4000))       [TypeMG]
  3390. ,CAST(      [Percentage] as nvarchar(4000))       [Percentage]
  3391. ,CAST(      [EstimatedCredits] as nvarchar(4000))       [EstimatedCredits]
  3392. ,CAST(      [Other1] as nvarchar(4000))       [Other1]
  3393. ,CAST(      [O1] as nvarchar(4000))       [O1]
  3394. ,CAST(      [O2] as nvarchar(4000))       [O2]
  3395. ,CAST(      [O3] as nvarchar(4000))       [O3]
  3396. ,CAST(      [CPANewExisting] as nvarchar(4000))       [CPANewExisting]
  3397. ,CAST(      [CPACoding] as nvarchar(4000))       [CPACoding]
  3398. ,CAST(      [PBDWIPAllocation] as nvarchar(4000))       [PBDWIPAllocation]
  3399. ,CAST(      [SBDWIPAllocation] as nvarchar(4000))       [SBDWIPAllocation]
  3400. ,CAST(      [PBDBilledAllocation] as nvarchar(4000))       [PBDBilledAllocation]
  3401. ,CAST(      [SBDBilledAllocation] as nvarchar(4000))       [SBDBilledAllocation]
  3402. ,CAST(      [PBDCollections] as nvarchar(4000))       [PBDCollections]
  3403. ,CAST(      [SBDCollections] as nvarchar(4000))       [SBDCollections]
  3404. ,CAST(      [RevisedPBDWIPAllocation] as nvarchar(4000))       [RevisedPBDWIPAllocation]
  3405. ,CAST(      [RevisedSBDWIPAllocation] as nvarchar(4000))       [RevisedSBDWIPAllocation]
  3406. ,CAST(      [SOE1WIPAllocation] as nvarchar(4000))       [SOE1WIPAllocation]
  3407. ,CAST(      [SOE2WIPAllocation] as nvarchar(4000))       [SOE2WIPAllocation]
  3408. ,CAST(      [SOE1BilledAllocation] as nvarchar(4000))       [SOE1BilledAllocation]
  3409. ,CAST(      [SOE2BilledAllocation] as nvarchar(4000))       [SOE2BilledAllocation]
  3410. ,CAST(      [SOE1Collections] as nvarchar(4000))       [SOE1Collections]
  3411. ,CAST(      [SOE2Collections] as nvarchar(4000))       [SOE2Collections]
  3412. ,CAST(      [RevisedSOE1WIPAllocation] as nvarchar(4000))       [RevisedSOE1WIPAllocation]
  3413. ,CAST(      [RevisedSOE2WIPAllocation] as nvarchar(4000))       [RevisedSOE2WIPAllocation]
  3414. ,CAST(      [PBDAllocPct] as nvarchar(4000))       [PBDAllocPct]
  3415. ,CAST(      [SBDAllocPct] as nvarchar(4000))       [SBDAllocPct]
  3416. ,CAST(      [PRDPct] as nvarchar(4000))       [PRDPct]
  3417. ,CAST(      [SRDPct] as nvarchar(4000))       [SRDPct]
  3418. ,CAST(      [PBDAllocWIP] as nvarchar(4000))       [PBDAllocWIP]
  3419. ,CAST(      [SPBDAllocWIP] as nvarchar(4000))       [SPBDAllocWIP]
  3420. ,CAST(      [PRDAllocWIP] as nvarchar(4000))       [PRDAllocWIP]
  3421. ,CAST(      [SRDAllocWIP] as nvarchar(4000))       [SRDAllocWIP]
  3422. ,CAST(      [FwUpSSLSOE] as nvarchar(4000))       [FwUpSSLSOE]
  3423. ,CAST(      [FUSOEOther] as nvarchar(4000))       [FUSOEOther]
  3424. ,CAST(      [OtherSSLBD] as nvarchar(4000))       [OtherSSLBD]
  3425. ,CAST(      [179DNewvExisting] as nvarchar(4000))       [179DNewvExisting]
  3426. ,CAST(      [RemainingWIPbasedonhoursworked] as nvarchar(4000))       [RemainingWIPbasedonhoursworked]
  3427. ,CAST(      [UnbilledWIP] as nvarchar(4000))       [UnbilledWIP]
  3428. ,CAST(      [WorkedWIP] as nvarchar(4000))       [WorkedWIP]
  3429. ,CAST(      [BilledWorkedWIP] as nvarchar(4000))       [BilledWorkedWIP]
  3430. ,CAST(      [UnbilledWorkedWIP] as nvarchar(4000))       [UnbilledWorkedWIP]
  3431. ,CAST(      [PendingInvoices] as nvarchar(4000))       [PendingInvoices]
  3432. ,CAST(      [Balance] as nvarchar(4000))       [Balance]
  3433. ,CAST(      [OctoberHours] as nvarchar(4000))       [OctoberHours]
  3434. ,CAST(      [JulyWIP] as nvarchar(4000))       [JulyWIP]
  3435. ,CAST(      [PreCurrentMonthUnbilled] as nvarchar(4000))       [PreCurrentMonthUnbilled]
  3436. ,CAST(      [Comment] as nvarchar(4000))       [Comment]
  3437. ,CAST(      [Region] as nvarchar(4000))       [Region]
  3438. ,CAST(      [TrueWeek] as nvarchar(4000))       [TrueWeek]
  3439. ,CAST(      [DateCreated] as nvarchar(4000))       [DateCreated]
  3440. ,CAST(      [HistoricalAlliance] as nvarchar(4000))       [HistoricalAlliance]
  3441. ,CAST(      [AddEG] as nvarchar(4000))       [AddEG]
  3442. ,CAST(      [CPAYearSignedNewNA] as nvarchar(4000))       [CPAYearSignedNewNA]
  3443. ,CAST(      [CPANewNAExistingCount] as nvarchar(4000))       [CPANewNAExistingCount]
  3444. ,CAST(      [ReferralCategory] as nvarchar(4000))       [ReferralCategory]
  3445. ,CAST(      [FO] as nvarchar(4000))       [FO]
  3446. ,CAST(      [RegionalOffice] as nvarchar(4000))       [RegionalOffice]
  3447. ,CAST(      [Associations] as nvarchar(4000))       [Associations]
  3448. ,CAST(      [OriginalDate] as nvarchar(4000))       [OriginalDate]
  3449. ,CAST(      [WholesaleRetail] as nvarchar(4000))       [WholesaleRetail]
  3450. ,CAST(      [StudyYears] as nvarchar(4000))       [StudyYears]
  3451. ,CAST(      [ExcludeinDataMerge] as nvarchar(4000))       [ExcludeinDataMerge]
  3452. ,CAST(      [CommissionPM] as nvarchar(4000))       [CommissionPM]
  3453. ,CAST(      [PMPct] as nvarchar(4000))       [PMPct]
  3454. ,CAST(      [EGDB] as nvarchar(4000))       [EGDB]
  3455. ,CAST(      [OpRefSourceCPA] as nvarchar(4000))       [OpRefSourceCPA]
  3456. ,CAST(      [OpRefSourceConference] as nvarchar(4000))       [OpRefSourceConference]
  3457. ,CAST(      [OpRefSourceNonConference] as nvarchar(4000))       [OpRefSourceNonConference]
  3458. ,CAST(      [OpRefSourceDirect] as nvarchar(4000))       [OpRefSourceDirect]
  3459. ,CAST(      [OpRefSourceEA] as nvarchar(4000))       [OpRefSourceEA]
  3460. ,CAST(      [OpRefSourceWebinar] as nvarchar(4000))       [OpRefSourceWebinar]
  3461. ,CAST(      [OpRefSourceWebsite] as nvarchar(4000))       [OpRefSourceWebsite]
  3462. ,CAST(      [OpRefSourceReferralSource] as nvarchar(4000))       [OpRefSourceReferralSource]
  3463. ,CAST(      [PM] as nvarchar(4000))       [PM]
  3464. ,CAST(      [CR] as nvarchar(4000))       [CR]
  3465. ,CAST(      [LastUpdatedDate] as nvarchar(4000))       [LastUpdatedDate]
  3466. ,CAST(      [Quarter] as nvarchar(4000))       [Quarter]
  3467. ,CAST(      [Month] as nvarchar(4000))       [Month]
  3468. ,CAST(      [Week] as nvarchar(4000))       [Week]
  3469. ,CAST(      [CPANewExistingNewAgain] as nvarchar(4000))       [CPANewExistingNewAgain]
  3470. ,CAST(      [CPAOrignalSignedDate] as nvarchar(4000))       [CPAOrignalSignedDate]
  3471. ,CAST(      [OpRefSourceEmployee1] as nvarchar(4000))       [OpRefSourceEmployee1]
  3472. ,CAST(      [OpRefSourceEmployee2] as nvarchar(4000))       [OpRefSourceEmployee2]
  3473. ,CAST(      [OpRefSourceEmployee3] as nvarchar(4000))       [OpRefSourceEmployee3]
  3474. ,CAST(      [AnnualRevenue] as nvarchar(4000))       [AnnualRevenue]
  3475. ,CAST(      [OpRefSourceRavingFan] as nvarchar(4000))       [OpRefSourceRavingFan]
  3476. ,CAST(      [CPAID] as nvarchar(4000))       [CPAID]
  3477. ,CAST(      [YearEnd] as nvarchar(4000))       [YearEnd]
  3478. ,CAST(      [OneTimeAdj] as nvarchar(4000))       [OneTimeAdj]
  3479. ,CAST(      [Description_SF] as nvarchar(4000))       [Description_SF]
  3480. ,CAST(      [Description_3E] as nvarchar(4000))       [Description_3E]
  3481. ,CAST(      [Client_SF] as nvarchar(4000))       [Client_SF]
  3482. ,CAST(      [Client_3E] as nvarchar(4000))       [Client_3E]
  3483. ,CAST(      [EngSignedDateCCC_SF] as nvarchar(4000))       [EngSignedDateCCC_SF]
  3484. ,CAST(      [EngSignedDateCCC_3E] as nvarchar(4000))       [EngSignedDateCCC_3E]
  3485. ,CAST(      [ServiceLine_SF] as nvarchar(4000))       [ServiceLine_SF]
  3486. ,CAST(      [ServiceLine_3E] as nvarchar(4000))       [ServiceLine_3E]
  3487. ,CAST(      [State_SF] as nvarchar(4000))       [State_SF]
  3488. ,CAST(      [State_3E] as nvarchar(4000))       [State_3E]
  3489. ,CAST(      [OriginalWIP_SF] as nvarchar(4000))       [OriginalWIP_SF]
  3490. ,CAST(      [OriginalWIP_3E] as nvarchar(4000))       [OriginalWIP_3E]
  3491. ,CAST(      [MajorIndustry_SF] as nvarchar(4000))       [MajorIndustry_SF]
  3492. ,CAST(      [MajorIndustry_3E] as nvarchar(4000))       [MajorIndustry_3E]
  3493. ,CAST(      [EngTypeCCC_SF] as nvarchar(4000))       [EngTypeCCC_SF]
  3494. ,CAST(      [EngTypeCCC_3E] as nvarchar(4000))       [EngTypeCCC_3E]
  3495. ,CAST(      [PBDAllocationPercent] as nvarchar(4000))       [PBDAllocationPercent]
  3496. ,CAST(      [SBDAllocationPercent] as nvarchar(4000))       [SBDAllocationPercent]
  3497. ,CAST(      [PRDAllocationPercent] as nvarchar(4000))       [PRDAllocationPercent]
  3498. ,CAST(      [SRDAllocationPercent] as nvarchar(4000))       [SRDAllocationPercent]
  3499. ,CAST(      [FeeCapPercentageType] as nvarchar(4000))       [FeeCapPercentageType]
  3500. ,CAST(      [PBDComPercent] as nvarchar(4000))       [PBDComPercent]
  3501. ,CAST(      [SBDComPercent] as nvarchar(4000))       [SBDComPercent]
  3502. ,CAST(      [PRDComPercent] as nvarchar(4000))       [PRDComPercent]
  3503. ,CAST(      [SRDComPercent] as nvarchar(4000))       [SRDComPercent]
  3504. ,CAST(      [BDAssist] as nvarchar(4000))       [BDAssist]
  3505. ,CAST(      [MinTaxYear] as nvarchar(4000))       [MinTaxYear]
  3506. ,CAST(      [RecordNotInOldBDMaster] as nvarchar(4000))       [RecordNotInOldBDMaster]
  3507. ,CAST(      [Source] as nvarchar(4000))       [Source]
  3508. ,CAST(      [RelatedEntity] as nvarchar(4000))       [RelatedEntity]
  3509. ,CAST(      [RaveFanReferralSource] as nvarchar(4000))       [RaveFanReferralSource]
  3510. ,CAST(      [RaveFanReferralEmployee1] as nvarchar(4000))       [RaveFanReferralEmployee1]
  3511. ,CAST(      [RaveFanReferralEmployee2] as nvarchar(4000))       [RaveFanReferralEmployee2]
  3512. ,CAST(      [RaveFanReferralEmployee3] as nvarchar(4000))       [RaveFanReferralEmployee3]
  3513. ,CAST(      [RaveFanCampaign] as nvarchar(4000))       [RaveFanCampaign]
  3514. ,CAST(      [DirectReferral] as nvarchar(4000))       [DirectReferral]
  3515. ,CAST(      [CPAReferralFirm] as nvarchar(4000))       [CPAReferralFirm]
  3516. ,CAST(      [CPAReferralIPAAssociate] as nvarchar(4000))       [CPAReferralIPAAssociate]
  3517. ,CAST(      [CPAReferralCampaign] as nvarchar(4000))       [CPAReferralCampaign]
  3518. ,CAST(      [CPAReferralAccountList] as nvarchar(4000))       [CPAReferralAccountList]
  3519. ,CAST(      [EmployeeReferral] as nvarchar(4000))       [EmployeeReferral]
  3520. ,CAST(      [ReferralSourceSource] as nvarchar(4000))       [ReferralSourceSource]
  3521. ,CAST(      [ReferralSourceCampaign] as nvarchar(4000))       [ReferralSourceCampaign]
  3522. ,CAST(      [IPAReferralType] as nvarchar(4000))       [IPAReferralType]
  3523. ,CAST(      [IPAReferralSpeaker] as nvarchar(4000))       [IPAReferralSpeaker]
  3524. ,CAST(      [IPAReferralCampaign] as nvarchar(4000))       [IPAReferralCampaign]
  3525. ,CAST(      [IPAReferralAssociate] as nvarchar(4000))       [IPAReferralAssociate]
  3526. ,CAST(      [IPAReferralAccountList] as nvarchar(4000))       [IPAReferralAccountList]
  3527. ,CAST(      [EAReferralType] as nvarchar(4000))       [EAReferralType]
  3528. ,CAST(      [EAReferralSpeaker] as nvarchar(4000))       [EAReferralSpeaker]
  3529. ,CAST(      [EAReferralCampaign] as nvarchar(4000))       [EAReferralCampaign]
  3530. ,CAST(      [EAReferralLeadGenAssociate] as nvarchar(4000))       [EAReferralLeadGenAssociate]
  3531. ,CAST(      [IsCloned_CCC] as nvarchar(4000)) [IsCloned_CCC]
  3532.   FROM [BDM].[BDMasterSource])p
  3533. UNPIVOT
  3534. (Value FOR SourceField IN
  3535.     (
  3536.     [AltNumber]
  3537.       ,[DisplayName]
  3538.       ,[Description]
  3539.       ,[ClientID]
  3540.       ,[Client]
  3541.       ,[MattStatus]
  3542.       ,[CloseDate]
  3543.       ,[Currency]
  3544.       ,[MattCategory]
  3545.       ,[IsEvergreenCCC]
  3546.       ,[EngTypeCCC]
  3547.       ,[EngStatusCCC]
  3548.       ,[EngSignedDateCCC]
  3549.  
  3550.       ,[ServiceLine]
  3551.       ,[State]
  3552.       ,[OriginalWIP]
  3553.       ,[AdjustedWIP]
  3554.       ,[MajorIndustry]
  3555.       ,[PBD]
  3556.       ,[SBD]
  3557.       ,[PRD]
  3558.       ,[SRD]
  3559.       ,[CPA]
  3560.       ,[CPAPercent]
  3561.       ,[ReferralSource]
  3562.       ,[CPAAlliance]
  3563.       ,[Manufacturing]
  3564.       ,[Architecture]
  3565.       ,[Construction]
  3566.       ,[Engineering]
  3567.       ,[SystemIntegrator]
  3568.       ,[SFAccountID]
  3569.       ,[SFParentAccount]
  3570.       ,[SFChildID]
  3571.       ,[SFChildAccount]
  3572.       ,[EAReferral]
  3573.       ,[EATeam]
  3574.       ,[EAIndustry]
  3575.       ,[EAParentName]
  3576.       ,[EAYearAttended]
  3577.       ,[EAEventDate]
  3578.       ,[WebinarIPA]
  3579.       ,[EASpeaker]
  3580.       ,[FeeType]
  3581.       ,[WIP]
  3582.       ,[Industry]
  3583.       ,[NumberOfEmployees]
  3584.       ,[FeeCap]
  3585.       ,[SIC]
  3586.       ,[RefNo]
  3587.       ,[Year]
  3588.       ,[NewCount]
  3589.       ,[UpdatedWIP]
  3590.       ,[ComboWIP]
  3591.       ,[Billed]
  3592.       ,[Collected]
  3593.       ,[AccountReceivable]
  3594.       ,[Variance]
  3595.       ,[CPAContact]
  3596.       ,[IndustryIntake]
  3597.       ,[TypeMG]
  3598.       ,[Percentage]
  3599.       ,[EstimatedCredits]
  3600.       ,[Other1]
  3601.       ,[O1]
  3602.       ,[O2]
  3603.       ,[O3]
  3604.       ,[CPANewExisting]
  3605.       ,[CPACoding]
  3606.       ,[PBDWIPAllocation]
  3607.       ,[SBDWIPAllocation]
  3608.       ,[PBDBilledAllocation]
  3609.       ,[SBDBilledAllocation]
  3610.       ,[PBDCollections]
  3611.       ,[SBDCollections]
  3612.       ,[RevisedPBDWIPAllocation]
  3613.       ,[RevisedSBDWIPAllocation]
  3614.       ,[SOE1WIPAllocation]
  3615.       ,[SOE2WIPAllocation]
  3616.       ,[SOE1BilledAllocation]
  3617.       ,[SOE2BilledAllocation]
  3618.       ,[SOE1Collections]
  3619.       ,[SOE2Collections]
  3620.       ,[RevisedSOE1WIPAllocation]
  3621.       ,[RevisedSOE2WIPAllocation]
  3622.       ,[PBDAllocPct]
  3623.       ,[SBDAllocPct]
  3624.       ,[PRDPct]
  3625.       ,[SRDPct]
  3626.       ,[PBDAllocWIP]
  3627.       ,[SPBDAllocWIP]
  3628.       ,[PRDAllocWIP]
  3629.       ,[SRDAllocWIP]
  3630.       ,[FwUpSSLSOE]
  3631.       ,[FUSOEOther]
  3632.       ,[OtherSSLBD]
  3633.       ,[179DNewvExisting]
  3634.       ,[RemainingWIPbasedonhoursworked]
  3635.       ,[UnbilledWIP]
  3636.       ,[WorkedWIP]
  3637.       ,[BilledWorkedWIP]
  3638.       ,[UnbilledWorkedWIP]
  3639.       ,[PendingInvoices]
  3640.       ,[Balance]
  3641.       ,[OctoberHours]
  3642.       ,[JulyWIP]
  3643.       ,[PreCurrentMonthUnbilled]
  3644.       ,[Comment]
  3645.       ,[Region]
  3646.       ,[TrueWeek]
  3647.       ,[DateCreated]
  3648.       ,[HistoricalAlliance]
  3649.       ,[AddEG]
  3650.       ,[CPAYearSignedNewNA]
  3651.       ,[CPANewNAExistingCount]
  3652.       ,[ReferralCategory]
  3653.       ,[FO]
  3654.       ,[RegionalOffice]
  3655.       ,[Associations]
  3656.       ,[OriginalDate]
  3657.       ,[WholesaleRetail]
  3658.       ,[StudyYears]
  3659.       ,[ExcludeinDataMerge]
  3660.       ,[CommissionPM]
  3661.       ,[PMPct]
  3662.       ,[EGDB]
  3663.       ,[OpRefSourceCPA]
  3664.       ,[OpRefSourceConference]
  3665.       ,[OpRefSourceNonConference]
  3666.       ,[OpRefSourceDirect]
  3667.       ,[OpRefSourceEA]
  3668.       ,[OpRefSourceWebinar]
  3669.       ,[OpRefSourceWebsite]
  3670.       ,[OpRefSourceReferralSource]
  3671.       ,[PM]
  3672.       ,[CR]
  3673.       ,[LastUpdatedDate]
  3674.       ,[Quarter]
  3675.       ,[Month]
  3676.       ,[Week]
  3677.       ,[CPANewExistingNewAgain]
  3678.       ,[CPAOrignalSignedDate]
  3679.       ,[OpRefSourceEmployee1]
  3680.       ,[OpRefSourceEmployee2]
  3681.       ,[OpRefSourceEmployee3]
  3682.       ,[AnnualRevenue]
  3683.       ,[OpRefSourceRavingFan]
  3684.       ,[CPAID]
  3685.       ,[YearEnd]
  3686.       ,[OneTimeAdj]
  3687.       ,[Description_SF]
  3688.       ,[Description_3E]
  3689.       ,[Client_SF]
  3690.       ,[Client_3E]
  3691.       ,[EngSignedDateCCC_SF]
  3692.       ,[EngSignedDateCCC_3E]
  3693.       ,[ServiceLine_SF]
  3694.       ,[ServiceLine_3E]
  3695.       ,[State_SF]
  3696.       ,[State_3E]
  3697.       ,[OriginalWIP_SF]
  3698.       ,[OriginalWIP_3E]
  3699.       ,[MajorIndustry_SF]
  3700.       ,[MajorIndustry_3E]
  3701.       ,[EngTypeCCC_SF]
  3702.       ,[EngTypeCCC_3E]
  3703.       ,[PBDAllocationPercent]
  3704.       ,[SBDAllocationPercent]
  3705.       ,[PRDAllocationPercent]
  3706.       ,[SRDAllocationPercent]
  3707.       ,[FeeCapPercentageType]
  3708.       ,[PBDComPercent]
  3709.       ,[SBDComPercent]
  3710.       ,[PRDComPercent]
  3711.       ,[SRDComPercent]
  3712.       ,[BDAssist]
  3713.       ,[MinTaxYear]
  3714.       ,[RecordNotInOldBDMaster]
  3715.       ,[Source]
  3716.       ,[RelatedEntity]
  3717.       ,[RaveFanReferralSource]
  3718.       ,[RaveFanReferralEmployee1]
  3719.       ,[RaveFanReferralEmployee2]
  3720.       ,[RaveFanReferralEmployee3]
  3721.       ,[RaveFanCampaign]
  3722.       ,[DirectReferral]
  3723.       ,[CPAReferralFirm]
  3724.       ,[CPAReferralIPAAssociate]
  3725.       ,[CPAReferralCampaign]
  3726.       ,[CPAReferralAccountList]
  3727.       ,[EmployeeReferral]
  3728.       ,[ReferralSourceSource]
  3729.       ,[ReferralSourceCampaign]
  3730.       ,[IPAReferralType]
  3731.       ,[IPAReferralSpeaker]
  3732.       ,[IPAReferralCampaign]
  3733.       ,[IPAReferralAssociate]
  3734.       ,[IPAReferralAccountList]
  3735.       ,[EAReferralType]
  3736.       ,[EAReferralSpeaker]
  3737.       ,[EAReferralCampaign]
  3738.       ,[EAReferralLeadGenAssociate]
  3739.       ,[IsCloned_CCC]
  3740.     )
  3741. ) as up
  3742.  
  3743. JOIN
  3744. (
  3745. SELECT ChangeId, FieldName, OrigValue, ChangeValue, Flag, ModifiedDate,MatterNumber,OpportunityID,MatchFlagSetDate
  3746. ,ROW_NUMBER() OVER(PARTITION BY MatterNumber, OpportunityID, FieldName order by ModifiedDate DESC) rn
  3747. 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')
  3748.  
  3749.  
  3750. UPDATE BC
  3751. SET Flag = FC.FlagUpdate
  3752. ,MatchFlagSetDate = FC.MatchFlagSetDate
  3753. FROM
  3754. [bdm].BDMasterChange BC
  3755. JOIN
  3756. #FlagChanges FC on FC.ChangeId = BC.ChangeId
  3757.  
  3758. ----------
  3759. exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'Checking if there is any insert from app'
  3760. --Update AppInsert Table and set flag to 1. With this, going forward matter data will be pulled from Source table
  3761. Update i  set UseFromSource = 1, i. ModifiedBy = 'System' , i.LastUpdatedDate = convert(datetime, convert(char(35),GETDATE(), 120)) --GETDATE()
  3762. FROM [bdm].[BDMasterAppInsert] i
  3763. JOIN [bdm].[BDMasterSource] s on i.Number = s.Number
  3764. where ISNULL(i.UseFromSource ,0) = 0
  3765.  
  3766.  
  3767. --Get Mattindex gap
  3768. UPDATE BMS SET Mattindex = M.Mattindex
  3769. FROM
  3770. BDM.BDMasterSource BMS
  3771. JOIN
  3772. TE_3E_PROD_CLone..Matter M on M.Number COLLATE SQL_Latin1_General_CP1_CI_AS = BMS.Number
  3773. WHERE BMS.Mattindex is null
  3774. AND BMS.NUmber is not null
  3775.  
  3776.  
  3777. ---Matter number change correction
  3778. UPDATE BDU SET Number = M.Number
  3779. FROM
  3780. BDM.BDMasterSource BDU
  3781. JOIN
  3782. TE_3E_PROD_Clone..Matter M on M.MattIndex = BDU.MattIndex and M.NUmber COLLATE SQL_Latin1_General_CP1_CI_AS != BDU.Number
  3783.  
  3784.  
  3785.  
  3786.  
  3787. DELETE--Bad Original Records
  3788. FROM
  3789. BDM.BDMasterSource
  3790. WHERE
  3791. ID IN (
  3792. SELECT BMS.Id FROM
  3793. BDM.BDMasterSource BMS
  3794. JOIN
  3795. (
  3796. SELECT
  3797. Matterlkup
  3798. ,MIN(Year) MinTaxYear
  3799. FROM
  3800. TE_3E_PROD_Clone..PGDetHdr_CCC ph
  3801. JOIN
  3802. TE_3E_PROD_Clone..PGDetChild_CCC pc on pc.PGDetHdr = ph.PGDetHdr_CCCID
  3803. GROUP BY
  3804. Matterlkup
  3805. ) my on BMS.MattIndex = my.MatterLkUp and BMS.MinTaxYear != my.MinTaxYear
  3806. WHERE
  3807. Number IN (
  3808. SELECT
  3809. Number
  3810. FROM
  3811. BDM.BDMasterSource
  3812. WHERE
  3813. [OneTimeAdj] != 1
  3814. GROUP BY
  3815. Number
  3816. HAVING COUNT(Number)>1
  3817. ) and BMS.AdjustedWIP = 0
  3818. )
  3819.  
  3820. --NBI delay clean up
  3821.  
  3822. DELETE FROM
  3823.  
  3824. bdm.BDMasterSource
  3825. WHERE ID IN (
  3826. SELECT ID FROM (
  3827. SELECT s.ID,s2.Number
  3828. from
  3829. bdm.BDMasterSource s
  3830. LEFT JOIN #bdmResults b
  3831.     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
  3832.     and b.MinTaxYear = s.MinTaxYear
  3833. LEFT JOIN
  3834. 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
  3835. WHERE
  3836. s.Number = '314812.0005' and
  3837. s.Number is not null
  3838. and b.Number is null
  3839. ) a where
  3840. number is not null)
  3841.  
  3842.  
  3843. DELETE
  3844. FROM
  3845. [FP&A].BDM.BDMasterSource
  3846. WHERE
  3847. MattIndex IN (
  3848. SELECT Mattindex
  3849. FROM
  3850. [FP&A].BDM.BDMasterUnpublished
  3851. GROUP BY MattIndex
  3852. HAVING COUNT(Mattindex)>COUNT(OpportunityIDCCC) AND COUNT(OpportunityIDCCC)>0
  3853. )
  3854. AND OpportunityIDCCC is null
  3855.  
  3856.  
  3857. DELETE s
  3858. FROM
  3859. [FP&A].BDM.BDMasterSource s
  3860. JOIN
  3861. [FP&A].[BDM].[BDMasterMatterDataFrom3E] s3 on s.MattIndex = s3.MattIndex and s.MinTaxYear != s3.MinYear
  3862. JOIN
  3863. [FP&A].[BDM].[BDMasterMatterDataFrom3E] s3c on s.ClientID = s3c.ClientId and s.MinTaxYear = s3c.MinYear and s.MattIndex != s3c.MattIndex
  3864. WHERE
  3865. s.number not in
  3866.   (
  3867. '013775.0003',
  3868. '302081.0001',
  3869. '000283.0002',
  3870. '301682.0001')
  3871.  
  3872. exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'ETL Process Complete'
  3873. END
  3874. GO
  3875.  
  3876.  
  3877. --Step 5
  3878.  
  3879. USE [FP&A]
  3880. GO
  3881. /****** Object:  StoredProcedure [BDM].[ValidateBDMasterSourceData]    Script Date: 2/6/2025 10:53:43 AM ******/
  3882. SET ANSI_NULLS ON
  3883. GO
  3884. SET QUOTED_IDENTIFIER ON
  3885. GO
  3886.  
  3887. ALTER   PROCEDURE [BDM].[ValidateBDMasterSourceData]
  3888. AS BEGIN
  3889. SET NOCOUNT ON
  3890. --Getting the latest Log Id from Log Table.
  3891. Declare @LogId int, @LogSql nvarchar(100)
  3892. SET @LogSql = 'SELECT TOP 1 @LogId = Id from [bdm].[BDMasterSource_Log] order by StartTime desc'
  3893.    
  3894. EXEC sp_executesql @LogSql, N'@LogId int OUTPUT', @LogId = @LogId OUTPUT
  3895.            
  3896. exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'Validation process starts'
  3897.  
  3898. --Drop the temporary table to load the table again with exception data 
  3899. if object_id('tempdb.dbo.#BDMException','U') is not null
  3900. drop table #BDMException;
  3901.  
  3902. --Getting the records from source table which has exceptions and insert into temp table.  
  3903. --select * from bdm.BDMasterExceptionType
  3904. /*We have to add exceptions in this query and give a number in incremental order with a Prefix 'E'.
  3905. This incremental column to be add in the unpivot query*/
  3906.  
  3907. SELECT ID, ID [BDMasterSourceId] ,
  3908. --(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
  3909. --WHEN FeeType IS NULL THEN 1  
  3910. --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
  3911. --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  
  3912. --WHEN OpportunityIDCCC IS NULL THEN 1  WHEN YEAR(EngSignedDateCCC) IS NULL THEN 1  WHEN ISNULL(NumberOfEmployees,0) = 0 THEN 1  ELSE 0 END) [E1],
  3913. CASE WHEN t.ServiceLine in ('R&D','SALT','179D Services','179D','R&D Services','SALT Services')
  3914. 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
  3915.         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
  3916.         WHEN State IS NULL THEN 1 WHEN EngTypeCCC IS NULL THEN 1 WHEN ServiceLine IS NULL THEN 1
  3917.         ELSE 0 END ELSE 0 END [E1],
  3918. /*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],
  3919. 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],
  3920. 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],*/
  3921. 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],
  3922. 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],
  3923. 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],
  3924. 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
  3925. And Role = 'BD' and Employee = t.PBD)<1 AND (SELECT count(*) from dbo.ActiveBDRDandDraw where IsActive = 1 And Role = 'BD'
  3926. and Employee = t.SBD) <1 THEN 5 ELSE 0 END [E5],
  3927. 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
  3928. And Role = 'RD' and Employee =t. PRD)<1 AND (SELECT count(*) from dbo.ActiveBDRDandDraw where IsActive = 1 And Role = 'RD'
  3929. and Employee = t.SRD) <1 THEN 6 ELSE 0 END [E6]
  3930. into #BDMException
  3931. FROM BDM.BDMasterSource t
  3932. where CloseDate >= '01/01/2020'
  3933.  
  3934. --Truncating exception table to reload the table with latest exceptions
  3935. truncate table bdm.BDMasterException
  3936.  
  3937. --Unpivot the exception data from temporary table and insert into BDMasterException table
  3938. INSERT INTO bdm.BDMasterException (BDMasterSourceId, ExceptionKey)
  3939. (
  3940. select Id , ExceptionKey
  3941. FROM
  3942. (
  3943.     select ID, [E1], [E2], [E3],[E4],[E5],[E6]
  3944.     from #BDMException b
  3945. ) as cp
  3946. UNPIVOT (
  3947.      ExceptionKey For Exception in ([E1],[E2],[E3],[E4],[E5],[E6])
  3948.     ) as tab2
  3949. where ISNULL(ExceptionKey ,0) <> 0
  3950.  
  3951. )
  3952.  
  3953. --Process completed. Logging the information in log table
  3954.  
  3955. IF EXISTS (select * from BDM.BDMasterSuppressException)
  3956. BEGIN
  3957. Declare @BDMasterSourceId int, @ExceptionKey int, @IsRecordToSupress int;
  3958. Declare SuppressExcCursor CURSOR For
  3959.     select BDMasterSourceId, ExceptionKey from BDM.BDMasterSuppressException
  3960.  
  3961. Open SuppressExcCursor
  3962. FETCH NEXT FROM SuppressExcCursor INTO @BDMasterSourceId, @ExceptionKey
  3963.  
  3964.     While @@FETCH_STATUS = 0
  3965.     begin
  3966.         SET @IsRecordToSupress = 0
  3967.         if(@ExceptionKey = 1)
  3968.         begin
  3969.             --select @IsRecordToSupress = count(*) from BDM.BDMasterSrcExceptSuppress e
  3970.             --JOIN BDM.BDMasterSource s on s.id = e.id
  3971.             --where s.Client <> e.Client OR s.CPA <> e.CPA OR s.PRD <> e.PRD
  3972.             --or s.PBD <> e.PBD OR s.PRD <> e.PRD or s.FeeType <> e.FeeType
  3973.             --or s.Description <> e.Description /*or s.WIP <> e.WIP*/ or s.MajorIndustry <> e.MajorIndustry
  3974.             --or s.SIC <> e.SIC OR s.FeeCap <> e.FeeCap or s.State <> e.State
  3975.             --or s.ServiceLine <> e.ServiceLine or s.SFAccountID <> e.SFAccountID or s.OpportunityIDCCC <> e.OpportunityIDCCC
  3976.             --or s.EngSignedDateCCC <> e.EngSignedDateCCC or s.NumberOfEmployees <> e.NumberOfEmployees
  3977.             select @IsRecordToSupress = count(*) from BDM.BDMasterSrcExceptSuppress e
  3978.             JOIN BDM.BDMasterSource s on s.id = e.id
  3979.             where s.Client <> e.Client OR s.CPA <> e.CPA OR s.PRD <> e.PRD
  3980.             or s.PBD <> e.PBD
  3981.             or s.Description <> e.Description /*or s.WIP <> e.WIP */
  3982.             or s.SIC <> e.SIC OR s.FeeCap <> e.FeeCap or s.State <> e.State or s.EngTypeCCC <> e.EngTypeCCC
  3983.             or s.ServiceLine <> e.ServiceLine
  3984.         end
  3985.         else if (@ExceptionKey =  2)
  3986.         begin
  3987.             select @IsRecordToSupress = count(*) from BDM.BDMasterSrcExceptSuppress e
  3988.             JOIN BDM.BDMasterSource s on s.id = e.id
  3989.             where s.PBD <> e.PBD OR s.PRD <> e.PRD
  3990.         end
  3991.         else if (@ExceptionKey =  3)
  3992.         begin
  3993.             select @IsRecordToSupress = count(*) from BDM.BDMasterSrcExceptSuppress e
  3994.             JOIN BDM.BDMasterSource s on s.id = e.id
  3995.             where s.PBD <> e.PBD OR s.SBD <> e.SBD
  3996.         end
  3997.         else if (@ExceptionKey =  4)
  3998.         begin
  3999.             select @IsRecordToSupress = count(*) from BDM.BDMasterSrcExceptSuppress e
  4000.             JOIN BDM.BDMasterSource s on s.id = e.id
  4001.             where s.PRD <> e.PRD OR s.SRD <> e.SRD
  4002.         end
  4003.         else if (@ExceptionKey =  5)
  4004.         begin
  4005.             select @IsRecordToSupress = count(*) from BDM.BDMasterSrcExceptSuppress e
  4006.             JOIN BDM.BDMasterSource s on s.id = e.id
  4007.             where s.ServiceLine <> e.ServiceLine OR s.PBD <> e.PBD or s.SBD <> e.SBD
  4008.         end
  4009.         else if (@ExceptionKey =  6)
  4010.         begin
  4011.             select @IsRecordToSupress = count(*) from BDM.BDMasterSrcExceptSuppress e
  4012.             JOIN BDM.BDMasterSource s on s.id = e.id
  4013.             where s.ServiceLine <> e.ServiceLine OR s.PRD <> e.PRD or s.SRD <> e.SRD
  4014.         end
  4015.  
  4016.         if(@IsRecordToSupress > 0)
  4017.             begin
  4018.                 delete from BDM.BDMasterSuppressException where BDMasterSourceId = @BDMasterSourceId and ExceptionKey = @ExceptionKey
  4019.             end
  4020.     FETCH NEXT FROM SuppressExcCursor INTO @BDMasterSourceId, @ExceptionKey
  4021.     end
  4022. CLOSE SuppressExcCursor
  4023. DEALLOCATE SuppressExcCursor
  4024.  
  4025. END
  4026. exec [bdm].[LogBDMasterSource] @Id = @LogId, @Activity = 'INFO', @Details = 'Validation process end'
  4027.  
  4028. END
  4029.  
  4030.  
  4031. --Step 6
  4032.  
  4033. USE [FP&A]
  4034. GO
  4035. /****** Object:  StoredProcedure [BDM].[proc_UnPublishedBDMasterMatterData]    Script Date: 2/6/2025 10:55:30 AM ******/
  4036. SET ANSI_NULLS ON
  4037. GO
  4038. SET QUOTED_IDENTIFIER ON
  4039. GO
  4040.  
  4041. CREATE PROCEDURE [BDM].[proc_UnPublishedBDMasterMatterData] (@IsUnPublished bit)
  4042. AS BEGIN
  4043.  
  4044.  
  4045. UPDATE BDM.BDMasterChange SET ChangeValue = LEFT(ChangeValue,11)+'00:00:00'
  4046.          where FieldName Like '%Date%' and changeValue like '%T%-%'
  4047.          ;
  4048.  
  4049. if object_id('tempdb.dbo.#bdmChangeData','U') is not null
  4050. drop table #bdmChangeData;
  4051.  
  4052. WITH ChangeRecords As
  4053. (select MatterNumber, OpportunityID, BDMasterSourceId, FieldName, ChangeValue, OrigValue, ExceptionKey, ModifiedBy
  4054.  from (
  4055.   select c.MatterNumber, c.OpportunityID, c.FieldName, c.ChangeValue, c.OrigValue, c.ExceptionKey, c.ModifiedBy, c.Flag, c.MatchFlagSetDate ,c.BDMasterSourceId,
  4056.   ROW_NUMBER() OVER(PARTITION BY MatterNumber, OpportunityID, FieldName order by modifiedDate desc) rn
  4057.   from BDM.BDMasterChange c
  4058.   --JOIn BDM.BDMasterSource  s on c.BDMasterSourceId = s.id
  4059.   --where s.Id = c.BDMasterSourceId--on s.Number = c.MatterNumber and s.OpportunityIDCCC = c.OpportunityID
  4060.  
  4061.   --where Number is not null  --and number = '309143.0002'
  4062.  -- and s.id = @ID
  4063.   ) a where rn =1 and a.Flag = 'Edit From App'
  4064. )
  4065.  
  4066. select *
  4067. into #bdmChangeData
  4068. from
  4069. (
  4070.     select BDMasterSourceId, FieldName, ChangeValue from ChangeRecords)
  4071.         as ChangeData
  4072.         PIVOT (
  4073.             Max(ChangeValue)
  4074.             For FieldName In
  4075.             ([Description],[Client],[MattStatus],[CloseDate],
  4076.             [IsEvergreenCCC],[EngTypeCCC],[EngSignedDateCCC],[ServiceLine],[State],[OriginalWIP],[AdjustedWIP]
  4077. ,[MajorIndustry],[PBD],[SBD],[PRD],[SRD],[PBDAllocationPercent],[SBDAllocationPercent],[PRDAllocationPercent],[SRDAllocationPercent],[CPA],[CPAPercent]
  4078. ,[ReferralSource],[CPAAlliance],[SFAccountID],[SFParentAccount],[SFChildID],[SFChildAccount],[EAReferral],[EATeam],[EAIndustry],[EAParentName]
  4079. ,[EAYearAttended],[EAEventDate],[WebinarIPA],[EASpeaker],[FeeType],[Industry],[NumberOfEmployees],[FeeCap]
  4080. ,[SIC],[Year],[Billed],[Collected],[AccountReceivable],[CPAContact],[IndustryIntake],[EstimatedCredits]
  4081. --,[PBDWIPAllocation],[SBDWIPAllocation],[SOE1WIPAllocation],[SOE2WIPAllocation]
  4082. ,[Region],[HistoricalAlliance],[AddEG],[OneTimeAdj],[ReferralCategory],[FO]
  4083. ,[Associations],[CommissionPM],[PMPct],[PBDComPercent],[SBDComPercent],[PRDComPercent],[SRDComPercent]/*,[SOE1ComPercent],[SOE2ComPercent]*/,[OpRefSourceCPA],[OpRefSourceConference],[OpRefSourceNonConference]
  4084. ,[OpRefSourceDirect],[OpRefSourceEA],[OpRefSourceWebinar],[OpRefSourceWebsite],[OpRefSourceReferralSource],[PM],[CR]
  4085. ,[Quarter],[Month],[Week],[CPANewExistingNewAgain],[CPAOrignalSignedDate],[OpRefSourceEmployee1],[OpRefSourceEmployee2]
  4086. ,[OpRefSourceEmployee3],[AnnualRevenue],[OpRefSourceRavingFan],[YearEnd],[FeeCapPercentageType], [UpdatedWIP],[OriginalDate],[BDAssist]
  4087. ,[RelatedEntity],[MinTaxYear]
  4088. ,[Source])
  4089.         ) As ChangePivot
  4090.  
  4091. if object_id('tempdb.dbo.#BDMasterDataToUnPublished','U') is not null
  4092. drop table #BDMasterDataToUnPublished;
  4093. select * into #BDMasterDataToUnPublished
  4094. from (
  4095. SELECT s.ID
  4096. ,s.[Number]
  4097. ,s.MattIndex
  4098. ,COALESCE(c.[Description],s.[Description]) [Description]
  4099. ,COALESCE(c.[Client],s.[Client]) [Client]
  4100. ,COALESCE(c.[MattStatus],s.[MattStatus]) [MattStatus]
  4101. ,COALESCE(c.[CloseDate],s.[CloseDate]) [CloseDate]
  4102. ,COALESCE(c.[OriginalDate],s.[OriginalDate]) [OriginalDate]
  4103. ,COALESCE(c.[IsEvergreenCCC],s.[IsEvergreenCCC]) [IsEvergreenCCC]
  4104. ,COALESCE(c.[EngTypeCCC],s.[EngTypeCCC]) [EngTypeCCC]
  4105. ,COALESCE(c.[EngSignedDateCCC],s.[EngSignedDateCCC]) [EngSignedDateCCC]
  4106. ,s.[OpportunityIDCCC]
  4107. ,COALESCE(c.[ServiceLine],s.[ServiceLine]) [ServiceLine]
  4108. ,COALESCE(c.[State],s.[State]) [State]
  4109. ,COALESCE(c.[OriginalWIP],s.[OriginalWIP]) [OriginalWIP]
  4110. ,COALESCE(c.[AdjustedWIP],s.[AdjustedWIP]) [AdjustedWIP]
  4111. ,COALESCE(c.[UpdatedWIP],s.[UpdatedWIP]) [UpdatedWIP]
  4112. ,COALESCE(c.[MajorIndustry],s.[MajorIndustry]) [MajorIndustry]
  4113. ,COALESCE(c.[PBD],s.[PBD]) [PBD]
  4114. ,COALESCE(c.[SBD],s.[SBD]) [SBD]
  4115. ,COALESCE(c.[PRD],s.[PRD]) [PRD]
  4116. ,COALESCE(c.[SRD],s.[SRD]) [SRD]
  4117. ,COALESCE(c.[PBDAllocationPercent],s.[PBDAllocationPercent]) [PBDAllocationPercent]
  4118. ,COALESCE(c.[SBDAllocationPercent],s.[SBDAllocationPercent]) [SBDAllocationPercent]
  4119. ,COALESCE(c.[PRDAllocationPercent],s.[PRDAllocationPercent]) [PRDAllocationPercent]
  4120. ,COALESCE(c.[SRDAllocationPercent],s.[SRDAllocationPercent]) [SRDAllocationPercent]
  4121. ,COALESCE(c.[CPA],s.[CPA]) [CPA]
  4122. ,COALESCE(c.[CPAPercent],s.[CPAPercent]) [CPAPercent]
  4123. ,COALESCE(c.[ReferralSource],s.[ReferralSource]) [ReferralSource]
  4124. ,COALESCE(c.[CPAAlliance],s.[CPAAlliance]) [CPAAlliance]
  4125. ,COALESCE(c.[SFAccountID],s.[SFAccountID]) [SFAccountID]
  4126. ,COALESCE(c.[SFParentAccount],s.[SFParentAccount]) [SFParentAccount]
  4127. ,COALESCE(c.[SFChildID],s.[SFChildID]) [SFChildID]
  4128. ,COALESCE(c.[SFChildAccount],s.[SFChildAccount]) [SFChildAccount]
  4129. ,COALESCE(c.[EAReferral],s.[EAReferral]) [EAReferral]
  4130. ,COALESCE(c.[EATeam],s.[EATeam]) [EATeam]
  4131. ,COALESCE(c.[EAIndustry],s.[EAIndustry]) [EAIndustry]
  4132. ,COALESCE(c.[EAParentName],s.[EAParentName]) [EAParentName]
  4133. ,COALESCE(c.[EAYearAttended],s.[EAYearAttended]) [EAYearAttended]
  4134. ,COALESCE(c.[EAEventDate],s.[EAEventDate]) [EAEventDate]
  4135. ,COALESCE(c.[WebinarIPA],s.[WebinarIPA]) [WebinarIPA]
  4136. ,COALESCE(c.[EASpeaker],s.[EASpeaker]) [EASpeaker]
  4137. ,COALESCE(c.[FeeType],s.[FeeType]) [FeeType]
  4138. ,COALESCE(c.[Industry],s.[Industry]) [Industry]
  4139. ,COALESCE(c.[NumberOfEmployees],s.[NumberOfEmployees]) [NumberOfEmployees]
  4140. ,COALESCE(c.[FeeCap],s.[FeeCap]) [FeeCap]
  4141. ,COALESCE(c.[SIC],s.[SIC]) [SIC]
  4142. ,COALESCE(c.[Year],s.[Year]) [Year]
  4143. ,COALESCE(c.[Billed],s.[Billed]) [Billed]
  4144. ,COALESCE(c.[Collected],s.[Collected]) [Collected]
  4145. ,COALESCE(c.[AccountReceivable],s.[AccountReceivable]) [AccountReceivable]
  4146. ,COALESCE(c.[CPAContact],s.[CPAContact]) [CPAContact]
  4147. ,COALESCE(c.[IndustryIntake],s.[IndustryIntake]) [IndustryIntake]
  4148. ,COALESCE(c.[EstimatedCredits],s.[EstimatedCredits]) [EstimatedCredits]
  4149. --,COALESCE(c.[PBDWIPAllocation],s.[PBDWIPAllocation]) [PBDWIPAllocation]
  4150. --,COALESCE(c.[SBDWIPAllocation],s.[SBDWIPAllocation]) [SBDWIPAllocation]
  4151. --,COALESCE(c.[SOE1WIPAllocation],s.[SOE1WIPAllocation]) [SOE1WIPAllocation]
  4152. --,COALESCE(c.[SOE2WIPAllocation],s.[SOE2WIPAllocation]) [SOE2WIPAllocation]
  4153. ,COALESCE(c.[Region],s.[Region]) [Region]
  4154. ,COALESCE(c.[HistoricalAlliance],s.[HistoricalAlliance]) [HistoricalAlliance]
  4155. ,COALESCE(c.[AddEG],s.[AddEG]) [AddEG]
  4156. ,COALESCE(c.[OneTimeAdj],s.[OneTimeAdj]) [OneTimeAdj]
  4157. ,COALESCE(c.[ReferralCategory],s.[ReferralCategory]) [ReferralCategory]
  4158. ,COALESCE(c.[FO],s.[FO]) [FO]
  4159. ,COALESCE(c.[Associations],s.[Associations]) [Associations]
  4160. ,COALESCE(c.[CommissionPM],s.[CommissionPM]) [CommissionPM]
  4161. ,COALESCE(c.[PMPct],s.[PMPct]) [PMPct]
  4162. ,COALESCE(c.[PBDComPercent],s.[PBDComPercent]) [PBDComPercent]
  4163. ,COALESCE(c.[SBDComPercent],s.[SBDComPercent]) [SBDComPercent]
  4164. ,COALESCE(c.[PRDComPercent],s.[PRDComPercent]) [PRDComPercent]
  4165. ,COALESCE(c.[SRDComPercent],s.[SRDComPercent]) [SRDComPercent]
  4166. --,COALESCE(c.[SOE1ComPercent],s.[SOE1ComPercent]) [SOE1ComPercent]
  4167. --,COALESCE(c.[SOE2ComPercent],s.[SOE2ComPercent]) [SOE2ComPercent]
  4168. ,COALESCE(c.[OpRefSourceCPA],s.[OpRefSourceCPA]) [OpRefSourceCPA]
  4169. ,COALESCE(c.[OpRefSourceConference],s.[OpRefSourceConference]) [OpRefSourceConference]
  4170. ,COALESCE(c.[OpRefSourceNonConference],s.[OpRefSourceNonConference]) [OpRefSourceNonConference]
  4171. ,COALESCE(c.[OpRefSourceDirect],s.[OpRefSourceDirect]) [OpRefSourceDirect]
  4172. ,COALESCE(c.[OpRefSourceEA],s.[OpRefSourceEA]) [OpRefSourceEA]
  4173. ,COALESCE(c.[OpRefSourceWebinar],s.[OpRefSourceWebinar]) [OpRefSourceWebinar]
  4174. ,COALESCE(c.[OpRefSourceWebsite],s.[OpRefSourceWebsite]) [OpRefSourceWebsite]
  4175. ,COALESCE(c.[OpRefSourceReferralSource],s.[OpRefSourceReferralSource]) [OpRefSourceReferralSource]
  4176. ,COALESCE(c.[PM],s.[PM]) [PM]
  4177. ,COALESCE(c.[CR],s.[CR]) [CR]
  4178. ,COALESCE(c.[Quarter],s.[Quarter]) [Quarter]
  4179. ,COALESCE(c.[Month],s.[Month]) [Month]
  4180. ,COALESCE(c.[Week],s.[Week]) [Week]
  4181. ,COALESCE(c.[CPANewExistingNewAgain],s.[CPANewExistingNewAgain]) [CPANewExistingNewAgain]
  4182. ,COALESCE(c.[CPAOrignalSignedDate],s.[CPAOrignalSignedDate]) [CPAOrignalSignedDate]
  4183. ,COALESCE(c.[OpRefSourceEmployee1],s.[OpRefSourceEmployee1]) [OpRefSourceEmployee1]
  4184. ,COALESCE(c.[OpRefSourceEmployee2],s.[OpRefSourceEmployee2]) [OpRefSourceEmployee2]
  4185. ,COALESCE(c.[OpRefSourceEmployee3],s.[OpRefSourceEmployee3]) [OpRefSourceEmployee3]
  4186. ,COALESCE(c.[AnnualRevenue],s.[AnnualRevenue]) [AnnualRevenue]
  4187. ,COALESCE(c.[OpRefSourceRavingFan],s.[OpRefSourceRavingFan]) [OpRefSourceRavingFan]
  4188. ,COALESCE(c.[YearEnd], s.[YearEnd]) [YearEnd]
  4189. ,COALESCE(c.[FeeCapPercentageType],s.[FeeCapPercentageType]) [FeeCapPercentageType]
  4190. ,COALESCE(c.[BDAssist],s.[BDAssist]) [BDAssist]
  4191. ,COALESCE(c.[RelatedEntity],s.[RelatedEntity]) [RelatedEntity]
  4192. ,COALESCE(c.[MinTaxYear],s.[MinTaxYear]) [MinTaxYear]
  4193. ,COALESCE(c.[Source],s.[Source]) [Source]
  4194. ,s.LastUpdatedDate
  4195. ,s.IsCloned_CCC
  4196. ,s.MaxTaxYear
  4197.   --INTO #BDMasterDataToUnPublished
  4198.   FROM [bdm].[BDMasterSource] s
  4199.   LEFT JOIN #bdmChangeData c on s.id = c.BDMasterSourceId
  4200.   --order by s.ID
  4201.  
  4202.   UNION
  4203.  
  4204.   SELECT s.ID
  4205. ,s.[Number]
  4206. ,s.MattIndex
  4207. ,COALESCE(c.[Description],s.[Description]) [Description]
  4208. ,COALESCE(c.[Client],s.[Client]) [Client]
  4209. ,COALESCE(c.[MattStatus],s.[MattStatus]) [MattStatus]
  4210. ,COALESCE(c.[CloseDate],s.[CloseDate]) [CloseDate]
  4211. ,COALESCE(c.[OriginalDate],s.[OriginalDate]) [OriginalDate]
  4212. ,COALESCE(c.[IsEvergreenCCC],s.[IsEvergreenCCC]) [IsEvergreenCCC]
  4213. ,COALESCE(c.[EngTypeCCC],s.[EngTypeCCC]) [EngTypeCCC]
  4214. ,COALESCE(c.[EngSignedDateCCC],s.[EngSignedDateCCC]) [EngSignedDateCCC]
  4215. ,s.[OpportunityIDCCC]
  4216. ,COALESCE(c.[ServiceLine],s.[ServiceLine]) [ServiceLine]
  4217. ,COALESCE(c.[State],s.[State]) [State]
  4218. ,COALESCE(c.[OriginalWIP],s.[OriginalWIP]) [OriginalWIP]
  4219. ,COALESCE(c.[AdjustedWIP],s.[AdjustedWIP]) [AdjustedWIP]
  4220. ,COALESCE(c.[UpdatedWIP],s.[UpdatedWIP]) [UpdatedWIP]
  4221. ,COALESCE(c.[MajorIndustry],s.[MajorIndustry]) [MajorIndustry]
  4222. ,COALESCE(c.[PBD],s.[PBD]) [PBD]
  4223. ,COALESCE(c.[SBD],s.[SBD]) [SBD]
  4224. ,COALESCE(c.[PRD],s.[PRD]) [PRD]
  4225. ,COALESCE(c.[SRD],s.[SRD]) [SRD]
  4226. ,COALESCE(c.[PBDAllocationPercent],s.[PBDAllocationPercent]) [PBDAllocationPercent]
  4227. ,COALESCE(c.[SBDAllocationPercent],s.[SBDAllocationPercent]) [SBDAllocationPercent]
  4228. ,COALESCE(c.[PRDAllocationPercent],s.[PRDAllocationPercent]) [PRDAllocationPercent]
  4229. ,COALESCE(c.[SRDAllocationPercent],s.[SRDAllocationPercent]) [SRDAllocationPercent]
  4230. ,COALESCE(c.[CPA],s.[CPA]) [CPA]
  4231. ,COALESCE(c.[CPAPercent],s.[CPAPercent]) [CPAPercent]
  4232. ,COALESCE(c.[ReferralSource],s.[ReferralSource]) [ReferralSource]
  4233. ,COALESCE(c.[CPAAlliance],s.[CPAAlliance]) [CPAAlliance]
  4234. ,COALESCE(c.[SFAccountID],s.[SFAccountID]) [SFAccountID]
  4235. ,COALESCE(c.[SFParentAccount],s.[SFParentAccount]) [SFParentAccount]
  4236. ,COALESCE(c.[SFChildID],s.[SFChildID]) [SFChildID]
  4237. ,COALESCE(c.[SFChildAccount],s.[SFChildAccount]) [SFChildAccount]
  4238. ,COALESCE(c.[EAReferral],s.[EAReferral]) [EAReferral]
  4239. ,COALESCE(c.[EATeam],s.[EATeam]) [EATeam]
  4240. ,COALESCE(c.[EAIndustry],s.[EAIndustry]) [EAIndustry]
  4241. ,COALESCE(c.[EAParentName],s.[EAParentName]) [EAParentName]
  4242. ,COALESCE(c.[EAYearAttended],s.[EAYearAttended]) [EAYearAttended]
  4243. ,COALESCE(c.[EAEventDate],s.[EAEventDate]) [EAEventDate]
  4244. ,COALESCE(c.[WebinarIPA],s.[WebinarIPA]) [WebinarIPA]
  4245. ,COALESCE(c.[EASpeaker],s.[EASpeaker]) [EASpeaker]
  4246. ,COALESCE(c.[FeeType],s.[FeeType]) [FeeType]
  4247. ,COALESCE(c.[Industry],s.[Industry]) [Industry]
  4248. ,COALESCE(c.[NumberOfEmployees],s.[NumberOfEmployees]) [NumberOfEmployees]
  4249. ,COALESCE(c.[FeeCap],s.[FeeCap]) [FeeCap]
  4250. ,COALESCE(c.[SIC],s.[SIC]) [SIC]
  4251. ,COALESCE(c.[Year],s.[Year]) [Year]
  4252. ,COALESCE(c.[Billed],s.[Billed]) [Billed]
  4253. ,COALESCE(c.[Collected],s.[Collected]) [Collected]
  4254. ,COALESCE(c.[AccountReceivable],s.[AccountReceivable]) [AccountReceivable]
  4255. ,COALESCE(c.[CPAContact],s.[CPAContact]) [CPAContact]
  4256. ,COALESCE(c.[IndustryIntake],s.[IndustryIntake]) [IndustryIntake]
  4257. ,COALESCE(c.[EstimatedCredits],s.[EstimatedCredits]) [EstimatedCredits]
  4258. --,COALESCE(c.[PBDWIPAllocation],s.[PBDWIPAllocation]) [PBDWIPAllocation]
  4259. --,COALESCE(c.[SBDWIPAllocation],s.[SBDWIPAllocation]) [SBDWIPAllocation]
  4260. --,COALESCE(c.[SOE1WIPAllocation],s.[SOE1WIPAllocation]) [SOE1WIPAllocation]
  4261. --,COALESCE(c.[SOE2WIPAllocation],s.[SOE2WIPAllocation]) [SOE2WIPAllocation]
  4262. ,COALESCE(c.[Region],s.[Region]) [Region]
  4263. ,COALESCE(c.[HistoricalAlliance],s.[HistoricalAlliance]) [HistoricalAlliance]
  4264. ,COALESCE(c.[AddEG],s.[AddEG]) [AddEG]
  4265. ,COALESCE(c.[OneTimeAdj],s.[OneTimeAdj]) [OneTimeAdj]
  4266. ,COALESCE(c.[ReferralCategory],s.[ReferralCategory]) [ReferralCategory]
  4267. ,COALESCE(c.[FO],s.[FO]) [FO]
  4268. ,COALESCE(c.[Associations],s.[Associations]) [Associations]
  4269. ,COALESCE(c.[CommissionPM],s.[CommissionPM]) [CommissionPM]
  4270. ,COALESCE(c.[PMPct],s.[PMPct]) [PMPct]
  4271. ,COALESCE(c.[PBDComPercent],s.[PBDComPercent]) [PBDComPercent]
  4272. ,COALESCE(c.[SBDComPercent],s.[SBDComPercent]) [SBDComPercent]
  4273. ,COALESCE(c.[PRDComPercent],s.[PRDComPercent]) [PRDComPercent]
  4274. ,COALESCE(c.[SRDComPercent],s.[SRDComPercent]) [SRDComPercent]
  4275. --,COALESCE(c.[SOE1ComPercent],s.[SOE1ComPercent]) [SOE1ComPercent]
  4276. --,COALESCE(c.[SOE2ComPercent],s.[SOE2ComPercent]) [SOE2ComPercent]
  4277. ,COALESCE(c.[OpRefSourceCPA],s.[OpRefSourceCPA]) [OpRefSourceCPA]
  4278. ,COALESCE(c.[OpRefSourceConference],s.[OpRefSourceConference]) [OpRefSourceConference]
  4279. ,COALESCE(c.[OpRefSourceNonConference],s.[OpRefSourceNonConference]) [OpRefSourceNonConference]
  4280. ,COALESCE(c.[OpRefSourceDirect],s.[OpRefSourceDirect]) [OpRefSourceDirect]
  4281. ,COALESCE(c.[OpRefSourceEA],s.[OpRefSourceEA]) [OpRefSourceEA]
  4282. ,COALESCE(c.[OpRefSourceWebinar],s.[OpRefSourceWebinar]) [OpRefSourceWebinar]
  4283. ,COALESCE(c.[OpRefSourceWebsite],s.[OpRefSourceWebsite]) [OpRefSourceWebsite]
  4284. ,COALESCE(c.[OpRefSourceReferralSource],s.[OpRefSourceReferralSource]) [OpRefSourceReferralSource]
  4285. ,COALESCE(c.[PM],s.[PM]) [PM]
  4286. ,COALESCE(c.[CR],s.[CR]) [CR]
  4287. ,COALESCE(c.[Quarter],s.[Quarter]) [Quarter]
  4288. ,COALESCE(c.[Month],s.[Month]) [Month]
  4289. ,COALESCE(c.[Week],s.[Week]) [Week]
  4290. ,COALESCE(c.[CPANewExistingNewAgain],s.[CPANewExistingNewAgain]) [CPANewExistingNewAgain]
  4291. ,COALESCE(c.[CPAOrignalSignedDate],s.[CPAOrignalSignedDate]) [CPAOrignalSignedDate]
  4292. ,COALESCE(c.[OpRefSourceEmployee1],s.[OpRefSourceEmployee1]) [OpRefSourceEmployee1]
  4293. ,COALESCE(c.[OpRefSourceEmployee2],s.[OpRefSourceEmployee2]) [OpRefSourceEmployee2]
  4294. ,COALESCE(c.[OpRefSourceEmployee3],s.[OpRefSourceEmployee3]) [OpRefSourceEmployee3]
  4295. ,COALESCE(c.[AnnualRevenue],s.[AnnualRevenue]) [AnnualRevenue]
  4296. ,COALESCE(c.[OpRefSourceRavingFan],s.[OpRefSourceRavingFan]) [OpRefSourceRavingFan]
  4297. ,COALESCE(c.[YearEnd], s.[YearEnd]) [YearEnd]
  4298. ,COALESCE(c.[FeeCapPercentageType],s.[FeeCapPercentageType]) [FeeCapPercentageType]
  4299. ,COALESCE(c.[BDAssist],s.[BDAssist]) [BDAssist]
  4300. ,COALESCE(c.[RelatedEntity],s.[RelatedEntity]) [RelatedEntity]
  4301. ,COALESCE(c.[MinTaxYear],s.[MinTaxYear]) [MinTaxYear]
  4302. ,COALESCE(c.[Source],s.[Source]) [Source]
  4303. ,s.LastUpdatedDate
  4304. ,null
  4305. ,null
  4306.   --INTO #BDMasterDataToUnPublished
  4307.   FROM [bdm].[BDMasterAppInsert] s
  4308.   LEFT JOIN #bdmChangeData c on s.id = c.BDMasterSourceId
  4309.   --order by s.ID
  4310.  --where s.id = 1630
  4311. ) a order by id
  4312.  
  4313. IF ISNULL(@IsUnPublished,0) = 1
  4314.     BEGIN  
  4315.     IF EXISTS (SELECT * FROM #BDMasterDataToUnPublished)
  4316.         truncate table BDM.BDMasterUnPublished;
  4317.  
  4318.     INSERT INTO BDM.BDMasterUnPublished
  4319.     (
  4320.        
  4321.     [MattIndex]
  4322.       ,[Number]
  4323.       ,[Description]
  4324.       ,[Client]
  4325.       ,[MattStatus]
  4326.       ,[CloseDate]
  4327.       ,[IsEvergreenCCC]
  4328.       ,[EngTypeCCC]
  4329.       ,[EngSignedDateCCC]
  4330.       ,[OpportunityIDCCC]
  4331.       ,[ServiceLine]
  4332.       ,[State]
  4333.       ,[OriginalWIP]
  4334.       ,[AdjustedWIP]
  4335.       ,[MajorIndustry]
  4336.       ,[PBD]
  4337.       ,[SBD]
  4338.       ,[PRD]
  4339.       ,[SRD]
  4340.       ,[PBDAllocationPercent]
  4341.       ,[SBDAllocationPercent]
  4342.       ,[PRDAllocationPercent]
  4343.       ,[SRDAllocationPercent]
  4344.       ,[CPA]
  4345.       ,[CPAPercent]
  4346.       ,[ReferralSource]
  4347.       ,[CPAAlliance]
  4348.       ,[SFAccountID]
  4349.       ,[SFParentAccount]
  4350.       ,[SFChildID]
  4351.       ,[SFChildAccount]
  4352.       ,[EAReferral]
  4353.       ,[EATeam]
  4354.       ,[EAIndustry]
  4355.       ,[EAParentName]
  4356.       ,[EAYearAttended]
  4357.       ,[EAEventDate]
  4358.       ,[WebinarIPA]
  4359.       ,[EASpeaker]
  4360.       ,[FeeType]
  4361.       ,[Industry]
  4362.       ,[NumberOfEmployees]
  4363.       ,[FeeCap]
  4364.       ,[SIC]
  4365.       ,[Year]
  4366.       ,[Billed]
  4367.       ,[Collected]
  4368.       ,[AccountReceivable]
  4369.       ,[CPAContact]
  4370.       ,[IndustryIntake]
  4371.       ,[EstimatedCredits]
  4372.       ,[PBDWIPAllocation]
  4373.       ,[SBDWIPAllocation]
  4374.       ,[SOE1WIPAllocation]
  4375.       ,[SOE2WIPAllocation]
  4376.       ,[Region]
  4377.       ,[HistoricalAlliance]
  4378.       ,[AddEG]
  4379.       ,[OneTimeAdj]
  4380.       ,[ReferralCategory]
  4381.       ,[FO]
  4382.       ,[Associations]
  4383.       ,[CommissionPM]
  4384.       ,[PMPct]
  4385.       ,[PBDComPercent]
  4386.       ,[SBDComPercent]
  4387.       ,[PRDComPercent]
  4388.       ,[SRDComPercent]
  4389.       --,[SOE1ComPercent]
  4390.       --,[SOE2ComPercent]
  4391.       ,[OpRefSourceCPA]
  4392.       ,[OpRefSourceConference]
  4393.       ,[OpRefSourceNonConference]
  4394.       ,[OpRefSourceDirect]
  4395.       ,[OpRefSourceEA]
  4396.       ,[OpRefSourceWebinar]
  4397.       ,[OpRefSourceWebsite]
  4398.       ,[OpRefSourceReferralSource]
  4399.       ,[PM]
  4400.       ,[CR]
  4401.       ,[Quarter]
  4402.       ,[Month]
  4403.       ,[Week]
  4404.       ,[CPANewExistingNewAgain]
  4405.       ,[CPAOrignalSignedDate]
  4406.       ,[OpRefSourceEmployee1]
  4407.       ,[OpRefSourceEmployee2]
  4408.       ,[OpRefSourceEmployee3]
  4409.       ,[LastUpdatedDate]
  4410.       ,[OpRefSourceRavingFan]
  4411.       ,[AnnualRevenue]
  4412.       ,[YearEnd]
  4413.       ,[FeeCapPercentageType]
  4414.       ,[UpdatedWIP]
  4415.       ,[BookDate]
  4416.       ,[BDAssist]
  4417.       ,[RelatedEntity]
  4418.       ,[MinTaxYear]
  4419.       ,[Source]
  4420.       ,ISCloned_CCC
  4421.       ,MaxTaxYear
  4422.     )
  4423.     (
  4424.         SELECT
  4425.     [MattIndex]
  4426.       ,[Number]
  4427.       ,b.[Description]
  4428.       ,[Client]
  4429.       , CASE WHEN MattStatus IN ('KO','CANCELDUP','Cancel_NOEL','TERM','TERM_EG','TERM_ERCLIVE') THEN 'Suspended'
  4430.         WHEN MattStatus IN ('COMP_ERCLIVE','COMP','CLOSING','CLOSING_ERCLIVE') THEN 'Completed'
  4431.         WHEN MattStatus IN ('HOLDAR','HOLDUTL','HOLDREP','HOLDFYR','LINKED','PEND','HOLDAUD','PENDEG','INPROC'
  4432.             ,'HOLDRESELL','HOLDFYE','HOLDCLI','EGREADYTOASSIGN','NO_EL','HOLDBD','HOLDFF','HOLDAYE','PENDCOMP','HOLDARREP')
  4433.             THEN 'In-Process'
  4434.         WHEN MattStatus is null THEN
  4435.                         CASE  o.StageName
  4436.                                 WHEN 'Closed - Project Completed' THEN 'In-Process'
  4437.                                 WHEN 'Closed - Study Completed' THEN 'In-Process'
  4438.                                 WHEN 'Closed - Study in Process' THEN 'In-Process'
  4439.                                 WHEN 'Closed - Project in Process' THEN 'In-Process'
  4440.                                 ELSE 'Suspended'
  4441.                         END
  4442.         ELSE MattStatus END [MattStatus]
  4443.       ,b.[CloseDate]
  4444.       ,[IsEvergreenCCC]
  4445.       ,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
  4446.       ,[EngSignedDateCCC]
  4447.       ,[OpportunityIDCCC]
  4448.       ,[ServiceLine]
  4449.       ,[State]
  4450.       ,[OriginalWIP]
  4451.       ,[AdjustedWIP]
  4452.       ,[MajorIndustry]
  4453.       ,[PBD]
  4454.       ,[SBD]
  4455.       ,[PRD]
  4456.       ,[SRD]
  4457.       ,[PBDAllocationPercent]
  4458.       ,[SBDAllocationPercent]
  4459.       ,[PRDAllocationPercent]
  4460.       ,[SRDAllocationPercent]
  4461.       ,[CPA]
  4462.       ,[CPAPercent]
  4463.       ,[ReferralSource]
  4464.       ,[CPAAlliance]
  4465.       ,[SFAccountID]
  4466.       ,[SFParentAccount]
  4467.       ,[SFChildID]
  4468.       ,[SFChildAccount]
  4469.       ,[EAReferral]
  4470.       ,[EATeam]
  4471.       ,[EAIndustry]
  4472.       ,[EAParentName]
  4473.       ,[EAYearAttended]
  4474.       ,[EAEventDate]
  4475.       ,[WebinarIPA]
  4476.       ,[EASpeaker]
  4477.       ,[FeeType]
  4478.       ,[Industry]
  4479.       ,[NumberOfEmployees]
  4480.       ,[FeeCap]
  4481.       ,[SIC]
  4482.       ,[Year]
  4483.       ,[Billed]
  4484.       ,[Collected]
  4485.       ,[AccountReceivable]
  4486.       ,[CPAContact]
  4487.       ,[IndustryIntake]
  4488.       ,[EstimatedCredits]
  4489.       ,COALESCE([PBDAllocationPercent],0) * [AdjustedWIP] [PBDWIPAllocation]
  4490.       ,COALESCE([SBDAllocationPercent],0) * [AdjustedWIP][SBDWIPAllocation]
  4491.       ,COALESCE([PRDAllocationPercent],0) * [AdjustedWIP][SOE1WIPAllocation]
  4492.       ,COALESCE([SRDAllocationPercent],0) * [AdjustedWIP][SOE2WIPAllocation]
  4493.       ,[Region]
  4494.       ,[HistoricalAlliance]
  4495.       ,[AddEG]
  4496.       ,[OneTimeAdj]
  4497.       ,[ReferralCategory]
  4498.       ,[FO]
  4499.       ,[Associations]
  4500.       ,[CommissionPM]
  4501.       ,[PMPct]
  4502.       ,[PBDComPercent]
  4503.       ,[SBDComPercent]
  4504.       ,[PRDComPercent]
  4505.       ,[SRDComPercent]
  4506.       --,[SOE1ComPercent]
  4507.       --,[SOE2ComPercent]
  4508.       ,[OpRefSourceCPA]
  4509.       ,[OpRefSourceConference]
  4510.       ,[OpRefSourceNonConference]
  4511.       ,[OpRefSourceDirect]
  4512.       ,[OpRefSourceEA]
  4513.       ,[OpRefSourceWebinar]
  4514.       ,[OpRefSourceWebsite]
  4515.       ,[OpRefSourceReferralSource]
  4516.       ,[PM]
  4517.       ,[CR]
  4518.       ,[Quarter]
  4519.       ,[Month]
  4520.       ,[Week]
  4521.       ,[CPANewExistingNewAgain]
  4522.       ,[CPAOrignalSignedDate]
  4523.       ,[OpRefSourceEmployee1]
  4524.       ,[OpRefSourceEmployee2]
  4525.       ,[OpRefSourceEmployee3]
  4526.       ,[LastUpdatedDate]
  4527.       ,[OpRefSourceRavingFan]
  4528.       ,[AnnualRevenue]
  4529.       ,[YearEnd]
  4530.       ,[FeeCapPercentageType]
  4531.       ,[UpdatedWIP]
  4532.       ,[OriginalDate]
  4533.       ,[BDAssist]
  4534.       ,[RelatedEntity]
  4535.       ,[MinTaxYear]
  4536.       ,[Source]
  4537.       ,ISCloned_CCC
  4538.       ,MaxTaxYear
  4539.     FROM #BDMasterDataToUnPublished b
  4540.     LEFT join
  4541.     SalesforceClone..Opportunity o on o.id = b.[OpportunityIDCCC])
  4542.     END
  4543. ELSE
  4544.     SELECT [ID],
  4545.     [MattIndex]
  4546.       ,[Number]
  4547.       ,[Description]
  4548.       ,[Client]
  4549.       ,[MattStatus]
  4550.       ,[CloseDate]
  4551.       ,[IsEvergreenCCC]
  4552.       ,[EngTypeCCC]
  4553.       ,[EngSignedDateCCC]
  4554.       ,[OpportunityIDCCC]
  4555.       ,[ServiceLine]
  4556.       ,[State]
  4557.       ,[OriginalWIP]
  4558.       ,[AdjustedWIP]
  4559.       ,[MajorIndustry]
  4560.       ,[PBD]
  4561.       ,[SBD]
  4562.       ,[PRD]
  4563.       ,[SRD]
  4564.       ,[PBDAllocationPercent]
  4565.       ,[SBDAllocationPercent]
  4566.       ,[PRDAllocationPercent]
  4567.       ,[SRDAllocationPercent]
  4568.       ,[CPA]
  4569.       ,[CPAPercent]
  4570.       ,[ReferralSource]
  4571.       ,[CPAAlliance]
  4572.       ,[SFAccountID]
  4573.       ,[SFParentAccount]
  4574.       ,[SFChildID]
  4575.       ,[SFChildAccount]
  4576.       ,[EAReferral]
  4577.       ,[EATeam]
  4578.       ,[EAIndustry]
  4579.       ,[EAParentName]
  4580.       ,[EAYearAttended]
  4581.       ,[EAEventDate]
  4582.       ,[WebinarIPA]
  4583.       ,[EASpeaker]
  4584.       ,[FeeType]
  4585.       ,[Industry]
  4586.       ,[NumberOfEmployees]
  4587.       ,[FeeCap]
  4588.       ,[SIC]
  4589.       ,[Year]
  4590.       ,[Billed]
  4591.       ,[Collected]
  4592.       ,[AccountReceivable]
  4593.       ,[CPAContact]
  4594.       ,[IndustryIntake]
  4595.       ,[EstimatedCredits]
  4596.       ,COALESCE([PBDAllocationPercent],0) * [AdjustedWIP] [PBDWIPAllocation]
  4597.       ,COALESCE([SBDAllocationPercent],0) * [AdjustedWIP][SBDWIPAllocation]
  4598.       ,COALESCE([PRDAllocationPercent],0) * [AdjustedWIP][SOE1WIPAllocation]
  4599.       ,COALESCE([SRDAllocationPercent],0) * [AdjustedWIP][SOE2WIPAllocation]
  4600.       ,[Region]
  4601.       ,[HistoricalAlliance]
  4602.       ,[AddEG]
  4603.       ,[OneTimeAdj]
  4604.       ,[ReferralCategory]
  4605.       ,[FO]
  4606.       ,[Associations]
  4607.       ,[CommissionPM]
  4608.       ,[PMPct]
  4609.       ,[PBDComPercent]
  4610.       ,[SBDComPercent]
  4611.       ,[PRDComPercent]
  4612.       ,[SRDComPercent]
  4613.       --,[SOE1ComPercent]
  4614.       --,[SOE2ComPercent]
  4615.       ,[OpRefSourceCPA]
  4616.       ,[OpRefSourceConference]
  4617.       ,[OpRefSourceNonConference]
  4618.       ,[OpRefSourceDirect]
  4619.       ,[OpRefSourceEA]
  4620.       ,[OpRefSourceWebinar]
  4621.       ,[OpRefSourceWebsite]
  4622.       ,[OpRefSourceReferralSource]
  4623.       ,[PM]
  4624.       ,[CR]
  4625.       ,[Quarter]
  4626.       ,[Month]
  4627.       ,[Week]
  4628.       ,[CPANewExistingNewAgain]
  4629.       ,[CPAOrignalSignedDate]
  4630.       ,[OpRefSourceEmployee1]
  4631.       ,[OpRefSourceEmployee2]
  4632.       ,[OpRefSourceEmployee3]
  4633.       ,[LastUpdatedDate]
  4634.       ,[OpRefSourceRavingFan]
  4635.       ,[AnnualRevenue]
  4636.       ,[YearEnd]
  4637.       ,[FeeCapPercentageType]
  4638.       ,[UpdatedWIP]
  4639.       ,[OriginalDate]
  4640.       ,[BDAssist]
  4641.       ,[RelatedEntity]
  4642.       ,ISCloned_CCC
  4643.       ,MaxTaxYear
  4644.      FROM #BDMasterDataToUnPublished order by id
  4645.  
  4646. END
  4647. --Added proc to UnPublished to old source for legacy reports
  4648. EXEC [BDM].[usprPopulateOldBDMasterTable]
  4649.  
  4650. --Step 7
  4651.  
  4652. USE [FP&A]
  4653. GO
  4654. /****** Object:  StoredProcedure [dbo].[CPACombinedReportData]    Script Date: 2/6/2025 11:06:52 AM ******/
  4655. SET ANSI_NULLS ON
  4656. GO
  4657. SET QUOTED_IDENTIFIER ON
  4658. GO
  4659.  
  4660. CREATE PROC [dbo].[CPACombinedReportData] AS
  4661. BEGIN
  4662.  
  4663. set transaction isolation level read uncommitted
  4664. /*
  4665. drop table if exists #Round0;
  4666. drop table if exists #Round1;
  4667. drop table if exists #Round2;
  4668. drop table if exists #Round3;
  4669. drop table if exists #Round4;
  4670. drop table if exists #Round5;
  4671. drop table if exists #Round6;
  4672. drop table if exists #Round7;
  4673. drop table if exists #Round8;
  4674. drop table if exists #Round9;
  4675. drop table if exists #Round10;
  4676. drop table if exists #Round11;
  4677. drop table if exists #Round12;
  4678. drop table if exists #Round13;
  4679. drop table if exists #Round14;
  4680. drop table if exists #Round15;
  4681. drop table if exists #Round16;
  4682. drop table if exists #Round17;
  4683. drop table if exists #Round18;
  4684. drop table if exists #Round19;
  4685.  
  4686.  
  4687. SELECT CM.CPA_NAME,CF.CPAFirmName,CF.AccountID,CPAFirmIndex
  4688. INTO #Round0
  4689. FROM
  4690. (
  4691. SELECT CPA_NAME,MatterNUmber
  4692. FROM
  4693. [fp&a]..CPAMatch CM
  4694. WHERE
  4695. ARMIndex IN (
  4696. SELECT ARMIndex
  4697. FROM
  4698. [fp&a]..CPAMatch
  4699. GROUP BY ARMIndex
  4700. HAVING COUNT(ARMIndex) = 1 AND SUM(COALESCE(TRY_CAST(AMOUNTDUETOCPA as numeric),0))>0)
  4701. GROUP BY  CPA_NAME,MatterNUmber
  4702. ) CM
  4703. JOIN
  4704. TE_3E_PROD_Clone..Matter M on M.NUmber COLLATE SQL_Latin1_General_CP1_CI_AS = CM.MatterNUmber
  4705. JOIN
  4706. (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
  4707. FROM
  4708. TE_3E_PROD_Clone..AG_MattCPAFirm
  4709. GROUP BY MatterLkup
  4710. HAVING COUNT(DISTINCT CPAFirm)=1
  4711. )
  4712. MCF on MCF.MatterLkup = M.MattINdex
  4713. JOIN
  4714. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
  4715. GROUP BY
  4716. CM.CPA_NAME,CPAFirmName,CF.AccountID,CPAFirmIndex
  4717.  
  4718. SELECT CM.CPA_NAME,CF.CPAFirmName,CF.AccountID,CPAFirmIndex
  4719. INTO #Round1
  4720. FROM
  4721. (
  4722. SELECT CPA_NAME,MatterNUmber
  4723. FROM
  4724. [fp&a]..CPAMatch CM
  4725. WHERE
  4726. ARMIndex IN (
  4727. SELECT ARMIndex
  4728. FROM
  4729. [fp&a]..CPAMatch
  4730. WHERE
  4731. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round0)
  4732. GROUP BY ARMIndex
  4733. HAVING COUNT(ARMIndex) = 1)
  4734. AND
  4735. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round0)
  4736. GROUP BY  CPA_NAME,MatterNUmber
  4737. ) CM
  4738. JOIN
  4739. TE_3E_PROD_Clone..Matter M on M.NUmber COLLATE SQL_Latin1_General_CP1_CI_AS = CM.MatterNUmber
  4740. JOIN
  4741. (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
  4742. FROM
  4743. TE_3E_PROD_Clone..AG_MattCPAFirm
  4744. GROUP BY MatterLkup
  4745. HAVING COUNT(DISTINCT CPAFirm)=1
  4746. )
  4747. MCF on MCF.MatterLkup = M.MattINdex
  4748. JOIN
  4749. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
  4750. GROUP BY
  4751. CM.CPA_NAME,CPAFirmName,CF.AccountID,CPAFirmIndex
  4752.  
  4753.  
  4754.  
  4755. SELECT CM.CPA_NAME,CF.CPAFirmName,CF.AccountID,CPAFirmIndex
  4756. INTO #Round2
  4757. FROM
  4758. (
  4759. SELECT CPA_NAME,MatterNUmber
  4760. FROM
  4761. [fp&a]..CPAMatch CM
  4762. WHERE
  4763. ARMIndex IN (
  4764. SELECT ARMIndex
  4765. FROM
  4766. [fp&a]..CPAMatch
  4767. WHERE
  4768. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
  4769. GROUP BY ARMIndex
  4770. HAVING COUNT(ARMIndex) = 1)
  4771. AND
  4772. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
  4773. GROUP BY  CPA_NAME,MatterNUmber
  4774. ) CM
  4775. JOIN
  4776. TE_3E_PROD_Clone..Matter M on M.NUmber COLLATE SQL_Latin1_General_CP1_CI_AS = CM.MatterNUmber
  4777. JOIN
  4778. (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
  4779. FROM
  4780. TE_3E_PROD_Clone..AG_MattCPAFirm
  4781. WHERE
  4782. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round1)
  4783. GROUP BY MatterLkup
  4784. HAVING COUNT(DISTINCT CPAFirm)=1
  4785. )
  4786. MCF on MCF.MatterLkup = M.MattINdex
  4787. JOIN
  4788. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
  4789. GROUP BY
  4790. CM.CPA_NAME,CPAFirmName,CF.AccountID,CPAFirmIndex
  4791.  
  4792.  
  4793. SELECT CM.CPA_NAME,CF.CPAFirmName,CF.AccountID,CPAFirmIndex
  4794. INTO #Round3
  4795. FROM
  4796. (
  4797. SELECT CPA_NAME,MatterNUmber
  4798. FROM
  4799. [fp&a]..CPAMatch CM
  4800. WHERE
  4801. ARMIndex IN (
  4802. SELECT ARMIndex
  4803. FROM
  4804. [fp&a]..CPAMatch
  4805. WHERE
  4806. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
  4807. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
  4808. GROUP BY ARMIndex
  4809. HAVING COUNT(ARMIndex) = 1)
  4810. AND
  4811. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
  4812. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
  4813. GROUP BY  CPA_NAME,MatterNUmber
  4814. ) CM
  4815. JOIN
  4816. TE_3E_PROD_Clone..Matter M on M.NUmber COLLATE SQL_Latin1_General_CP1_CI_AS = CM.MatterNUmber
  4817. JOIN
  4818. (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
  4819. FROM
  4820. TE_3E_PROD_Clone..AG_MattCPAFirm
  4821. WHERE
  4822. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round2) AND
  4823. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round1)
  4824. GROUP BY MatterLkup
  4825. HAVING COUNT(DISTINCT CPAFirm)=1
  4826. )
  4827. MCF on MCF.MatterLkup = M.MattINdex
  4828. JOIN
  4829. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
  4830. GROUP BY
  4831. CM.CPA_NAME,CPAFirmName,CF.AccountID,CPAFirmIndex
  4832.  
  4833.  
  4834. SELECT CM.CPA_NAME,CF.CPAFirmName,CF.AccountID,CPAFirmIndex
  4835. INTO #Round4
  4836. FROM
  4837. (
  4838. SELECT CPA_NAME,[CLIENT ID]
  4839. FROM
  4840. [fp&a]..CPAMatch CM
  4841. WHERE
  4842. ARMIndex IN (
  4843. SELECT ARMIndex
  4844. FROM
  4845. [fp&a]..CPAMatch
  4846. WHERE
  4847. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round3) and
  4848. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
  4849. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
  4850. GROUP BY ARMIndex
  4851. HAVING COUNT(ARMIndex) = 1)
  4852. AND
  4853. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round3) and
  4854. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
  4855. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
  4856. GROUP BY  CPA_NAME,[CLIENT ID]
  4857. ) CM
  4858. JOIN
  4859. TE_3E_PROD_Clone..Matter M on M.Client = CM.[CLIENT ID]
  4860. JOIN
  4861. (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
  4862. FROM
  4863. TE_3E_PROD_Clone..AG_MattCPAFirm
  4864. WHERE
  4865. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round3) AND
  4866. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round2) AND
  4867. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round1)
  4868. GROUP BY MatterLkup
  4869. HAVING COUNT(DISTINCT CPAFirm)=1
  4870. )
  4871. MCF on MCF.MatterLkup = M.MattINdex
  4872. JOIN
  4873. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
  4874. GROUP BY
  4875. CM.CPA_NAME,CPAFirmName,CF.AccountID,CPAFirmIndex
  4876.  
  4877.  
  4878.  
  4879. SELECT CM.CPA_NAME,CF.CPAFirmName,CF.AccountID,CPAFirmIndex
  4880. INTO #Round5
  4881. --SELECT *
  4882. FROM
  4883. (
  4884. SELECT CPA_NAME,ARMIndex
  4885. FROM
  4886. [fp&a]..CPAMatch CM
  4887. WHERE
  4888. ARMIndex IN (
  4889. SELECT ARMIndex
  4890. FROM
  4891. [fp&a]..CPAMatch
  4892. WHERE
  4893. CPA_NAME != 'Null' AND
  4894. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round4) and
  4895. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round3) and
  4896. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
  4897. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
  4898. GROUP BY ARMIndex
  4899. HAVING COUNT(ARMIndex) = 1)
  4900. AND
  4901. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round4) and
  4902. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round3) and
  4903. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
  4904. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
  4905. GROUP BY  CPA_NAME,ARMIndex
  4906. ) CM
  4907. JOIN
  4908. TE_3E_PROD_Clone..ARMaster AM on AM.ARMIndex = CM.ARMIndex
  4909. JOIN
  4910. TE_3E_PROD_Clone..InvMaster IM on IM.InvIndex = AM.InvMaster
  4911. JOIN
  4912. TE_3E_PROD_Clone..Matter M on M.Mattindex = IM.LeadMatter
  4913. JOIN
  4914. (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
  4915. FROM
  4916. TE_3E_PROD_Clone..AG_MattCPAFirm
  4917. WHERE
  4918. FeeAllocation is not null and
  4919. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round4) AND
  4920. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round3) AND
  4921. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round2) AND
  4922. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round1)
  4923. GROUP BY MatterLkup
  4924. HAVING COUNT(DISTINCT CPAFirm)=1
  4925. )
  4926. MCF on MCF.MatterLkup = M.MattINdex
  4927. JOIN
  4928. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
  4929. --WHERE CM.ARMIndex = 364262
  4930. GROUP BY
  4931. CM.CPA_NAME,CPAFirmName,CF.AccountID,CPAFirmIndex
  4932.  
  4933.  
  4934.  
  4935. SELECT CM.CPA_NAME,CF.CPAFirmName,CF.AccountID,CPAFirmIndex
  4936. INTO #Round6
  4937. --SELECT *
  4938. FROM
  4939. (
  4940. SELECT CPA_NAME,ARMIndex
  4941. FROM
  4942. [fp&a]..CPAMatch CM
  4943. WHERE
  4944. ARMIndex IN (
  4945. SELECT ARMIndex
  4946. FROM
  4947. [fp&a]..CPAMatch
  4948. WHERE
  4949. CPA_NAME != 'Null' AND
  4950. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round5) and
  4951. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round4) and
  4952. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round3) and
  4953. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
  4954. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
  4955. GROUP BY ARMIndex
  4956. HAVING COUNT(ARMIndex) = 1)
  4957. AND
  4958. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round5) and
  4959. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round4) and
  4960. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round3) and
  4961. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
  4962. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
  4963. GROUP BY  CPA_NAME,ARMIndex
  4964. ) CM
  4965. JOIN
  4966. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS = CM.CPA_NAME
  4967. --JOIN
  4968. --TE_3E_PROD_Clone..ARMaster AM on AM.ARMIndex = CM.ARMIndex
  4969. --JOIN
  4970. --TE_3E_PROD_Clone..InvMaster IM on IM.InvIndex = AM.InvMaster
  4971. --JOIN
  4972. --TE_3E_PROD_Clone..Matter M on M.Mattindex = IM.LeadMatter
  4973. JOIN
  4974. (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
  4975. FROM
  4976. TE_3E_PROD_Clone..AG_MattCPAFirm
  4977. WHERE
  4978. --FeeAllocation is not null and
  4979. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round5) AND
  4980. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round4) AND
  4981. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round3) AND
  4982. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round2) AND
  4983. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round1)
  4984. GROUP BY MatterLkup
  4985. HAVING COUNT(DISTINCT CPAFirm)=1
  4986. )
  4987. MCF on CF.CPAFirmIndex = MCF.CPAFirm
  4988.  
  4989.  
  4990. GROUP BY
  4991. CM.CPA_NAME,CPAFirmName,CF.AccountID,CPAFirmIndex
  4992.  
  4993.  
  4994.  
  4995.  
  4996. SELECT CM.CPA_NAME,CF.CPAFirmName,CF.AccountID,CPAFirmIndex
  4997. INTO #Round7
  4998. --SELECT *
  4999. FROM
  5000. (
  5001. SELECT CPA_NAME,ARMIndex
  5002. FROM
  5003. [fp&a]..CPAMatch CM
  5004. WHERE
  5005. ARMIndex IN (
  5006. SELECT ARMIndex
  5007. FROM
  5008. [fp&a]..CPAMatch
  5009. WHERE
  5010. CPA_NAME != 'Null' AND
  5011. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round6) and
  5012. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round5) and
  5013. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round4) and
  5014. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round3) and
  5015. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
  5016. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
  5017. GROUP BY ARMIndex
  5018. HAVING COUNT(ARMIndex) = 1)
  5019. AND
  5020. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round6) and
  5021. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round5) and
  5022. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round4) and
  5023. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round3) and
  5024. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round2) and
  5025. CPA_NAME NOT IN (SELECT CPA_NAME FROM #Round1)
  5026. GROUP BY  CPA_NAME,ARMIndex
  5027. ) CM
  5028. JOIN
  5029. TE_3E_PROD_Clone..ARMaster AM on AM.ARMIndex = CM.ARMIndex
  5030. JOIN
  5031. TE_3E_PROD_Clone..InvMaster IM on IM.InvIndex = AM.InvMaster
  5032. JOIN
  5033. TE_3E_PROD_Clone..Matter M on M.Mattindex = IM.LeadMatter
  5034. JOIN
  5035. (SELECT Client,MAX(CPAFirm) CPAFirm
  5036. FROM
  5037. TE_3E_PROD_Clone..AG_MattCPAFirm mcf
  5038. JOIN
  5039. TE_3E_PROD_Clone..Matter m on m.MattIndex = mcf.MatterLkup
  5040. WHERE
  5041. --FeeAllocation is not null and
  5042. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round6) AND
  5043. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round5) AND
  5044. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round4) AND
  5045. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round3) AND
  5046. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round2) AND
  5047. CPAFirm NOT IN (SELECT CPAFirmIndex FROM #Round1)
  5048. GROUP BY Client
  5049. HAVING COUNT(DISTINCT CPAFirm)=1
  5050. )
  5051. MCF on MCF.Client = m.client
  5052. JOIN
  5053. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
  5054.  
  5055. GROUP BY
  5056. CM.CPA_NAME,CPAFirmName,CF.AccountID,CPAFirmIndex
  5057.  
  5058.  
  5059.  
  5060. SELECT CPA_NAME,CPAFirmName,a.id AccountID, CPAFirmIndex
  5061. into #Round8
  5062. FROM
  5063. [fp&a]..CPAMatch cm
  5064. JOIN
  5065. SalesforceClone..account a on a.name = cm.CPA_NAME
  5066. LEFT JOIN
  5067. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
  5068. WHERE
  5069. CPA_NAME NOT IN (
  5070. SELECT CPA_NAME
  5071. FROM
  5072. #Round1
  5073. UNION ALL
  5074. SELECT CPA_NAME
  5075. FROM
  5076. #Round2
  5077. UNION ALL
  5078. SELECT CPA_NAME
  5079. FROM
  5080. #Round3
  5081. UNION ALL
  5082. SELECT CPA_NAME
  5083. FROM
  5084. #Round4
  5085. UNION ALL
  5086. SELECT CPA_NAME
  5087. FROM
  5088. #Round5
  5089. UNION ALL
  5090. SELECT CPA_NAME
  5091. FROM
  5092. #Round6
  5093. UNION ALL
  5094. SELECT CPA_NAME
  5095. FROM
  5096. #Round7)
  5097. GROUP BY CPA_NAME,CPAFirmName,a.id , CPAFirmIndex
  5098.  
  5099. SELECT CPA_NAME,CPAFirmName,cf.AccountID, cf.CPAFirmIndex
  5100. into #Round9
  5101.  
  5102. FROM
  5103. [fp&a]..CPAMatch cm
  5104. JOIN
  5105. TE_3E_PROD_Clone..ARMaster AM on AM.ARMIndex = cm.ARMIndex
  5106. JOIN
  5107. TE_3E_PROD_Clone..Matter m on m.MattIndex = am.Matter
  5108. JOIN
  5109. SalesforceClone..Opportunity o on o.id = m.OpportunityID_CCC COLLATE SQL_Latin1_General_CP1_CI_AS
  5110. JOIN
  5111. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = o.Referring_CPA_Firm_ID__c
  5112. LEFT JOIN (
  5113. SELECT CPAFirmIndex
  5114. FROM
  5115. #Round1
  5116. UNION ALL
  5117. SELECT CPAFirmIndex
  5118. FROM
  5119. #Round2
  5120. UNION ALL
  5121. SELECT CPAFirmIndex
  5122. FROM
  5123. #Round3
  5124. UNION ALL
  5125. SELECT CPAFirmIndex
  5126. FROM
  5127. #Round4
  5128. UNION ALL
  5129. SELECT CPAFirmIndex
  5130. FROM
  5131. #Round5
  5132. UNION ALL
  5133. SELECT CPAFirmIndex
  5134. FROM
  5135. #Round6
  5136. UNION ALL
  5137. SELECT CPAFirmIndex
  5138. FROM
  5139. #Round7
  5140. UNION ALL
  5141. SELECT CPAFirmIndex
  5142. FROM
  5143. #Round8) a on a.CPAFirmIndex = cf.CPAFirmIndex
  5144.  
  5145. WHERE
  5146. a.CPAFirmIndex is null and
  5147. CPA_NAME NOT IN (
  5148. SELECT CPA_NAME
  5149. FROM
  5150. #Round1
  5151. UNION ALL
  5152. SELECT CPA_NAME
  5153. FROM
  5154. #Round2
  5155. UNION ALL
  5156. SELECT CPA_NAME
  5157. FROM
  5158. #Round3
  5159. UNION ALL
  5160. SELECT CPA_NAME
  5161. FROM
  5162. #Round4
  5163. UNION ALL
  5164. SELECT CPA_NAME
  5165. FROM
  5166. #Round5
  5167. UNION ALL
  5168. SELECT CPA_NAME
  5169. FROM
  5170. #Round6
  5171. UNION ALL
  5172. SELECT CPA_NAME
  5173. FROM
  5174. #Round7
  5175. UNION ALL
  5176. SELECT CPA_NAME
  5177. FROM
  5178. #Round8)
  5179. GROUP BY CPA_NAME,CPAFirmName,cf.AccountID , cf.CPAFirmIndex
  5180.  
  5181.  
  5182. SELECT CPA_NAME,CPAFirmName,cf.AccountID, cf.CPAFirmIndex
  5183. into #Round10
  5184.  
  5185. FROM
  5186. [fp&a]..CPAMatch cm
  5187. JOIN
  5188. TE_3E_PROD_Clone..ARMaster AM on AM.ARMIndex = cm.ARMIndex
  5189. JOIN
  5190. TE_3E_PROD_Clone..Matter m on m.MattIndex = am.Matter
  5191. JOIN
  5192. SalesforceClone..Opportunity o on o.id = m.OpportunityID_CCC COLLATE SQL_Latin1_General_CP1_CI_AS
  5193. JOIN
  5194. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = o.Amending_CPA_Firm_ID__c
  5195. LEFT JOIN (
  5196. SELECT CPAFirmIndex
  5197. FROM
  5198. #Round1
  5199. UNION ALL
  5200. SELECT CPAFirmIndex
  5201. FROM
  5202. #Round2
  5203. UNION ALL
  5204. SELECT CPAFirmIndex
  5205. FROM
  5206. #Round3
  5207. UNION ALL
  5208. SELECT CPAFirmIndex
  5209. FROM
  5210. #Round4
  5211. UNION ALL
  5212. SELECT CPAFirmIndex
  5213. FROM
  5214. #Round5
  5215. UNION ALL
  5216. SELECT CPAFirmIndex
  5217. FROM
  5218. #Round6
  5219. UNION ALL
  5220. SELECT CPAFirmIndex
  5221. FROM
  5222. #Round7
  5223. UNION ALL
  5224. SELECT CPAFirmIndex
  5225. FROM
  5226. #Round8
  5227. UNION ALL
  5228. SELECT CPAFirmIndex
  5229. FROM
  5230. #Round9) a on a.CPAFirmIndex = cf.CPAFirmIndex
  5231.  
  5232. WHERE
  5233. a.CPAFirmIndex is null and
  5234. CPA_NAME NOT IN (
  5235. SELECT CPA_NAME
  5236. FROM
  5237. #Round1
  5238. UNION ALL
  5239. SELECT CPA_NAME
  5240. FROM
  5241. #Round2
  5242. UNION ALL
  5243. SELECT CPA_NAME
  5244. FROM
  5245. #Round3
  5246. UNION ALL
  5247. SELECT CPA_NAME
  5248. FROM
  5249. #Round4
  5250. UNION ALL
  5251. SELECT CPA_NAME
  5252. FROM
  5253. #Round5
  5254. UNION ALL
  5255. SELECT CPA_NAME
  5256. FROM
  5257. #Round6
  5258. UNION ALL
  5259. SELECT CPA_NAME
  5260. FROM
  5261. #Round7
  5262. UNION ALL
  5263. SELECT CPA_NAME
  5264. FROM
  5265. #Round8
  5266. UNION ALL
  5267. SELECT CPA_NAME
  5268. FROM
  5269. #Round9)
  5270. GROUP BY CPA_NAME,CPAFirmName,cf.AccountID , cf.CPAFirmIndex
  5271.  
  5272.  
  5273. SELECT CPA_NAME,CPAFirmName,cf.AccountID, cf.CPAFirmIndex
  5274. into #Round11
  5275.  
  5276. FROM
  5277. [fp&a]..CPAMatch cm
  5278. JOIN
  5279. TE_3E_PROD_Clone..ARMaster AM on AM.ARMIndex = cm.ARMIndex
  5280. JOIN
  5281. TE_3E_PROD_Clone..Matter m on m.MattIndex = am.Matter
  5282. JOIN
  5283. TE_3E_PROD_Clone..Client c on c.ClientIndex = m.Client
  5284. JOIN
  5285. SalesforceClone..account ac on ac.id = c.AccountID_CCC COLLATE SQL_Latin1_General_CP1_CI_AS
  5286. JOIN
  5287. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = ac.CPA_Account__c
  5288. LEFT JOIN (
  5289. SELECT CPAFirmIndex
  5290. FROM
  5291. #Round1
  5292. UNION ALL
  5293. SELECT CPAFirmIndex
  5294. FROM
  5295. #Round2
  5296. UNION ALL
  5297. SELECT CPAFirmIndex
  5298. FROM
  5299. #Round3
  5300. UNION ALL
  5301. SELECT CPAFirmIndex
  5302. FROM
  5303. #Round4
  5304. UNION ALL
  5305. SELECT CPAFirmIndex
  5306. FROM
  5307. #Round5
  5308. UNION ALL
  5309. SELECT CPAFirmIndex
  5310. FROM
  5311. #Round6
  5312. UNION ALL
  5313. SELECT CPAFirmIndex
  5314. FROM
  5315. #Round7
  5316. UNION ALL
  5317. SELECT CPAFirmIndex
  5318. FROM
  5319. #Round8
  5320. UNION ALL
  5321. SELECT CPAFirmIndex
  5322. FROM
  5323. #Round9
  5324. UNION ALL
  5325. SELECT CPAFirmIndex
  5326. FROM
  5327. #Round10) a on a.CPAFirmIndex = cf.CPAFirmIndex
  5328.  
  5329. WHERE
  5330. a.CPAFirmIndex is null and
  5331. CPA_NAME NOT IN (
  5332. SELECT CPA_NAME
  5333. FROM
  5334. #Round1
  5335. UNION ALL
  5336. SELECT CPA_NAME
  5337. FROM
  5338. #Round2
  5339. UNION ALL
  5340. SELECT CPA_NAME
  5341. FROM
  5342. #Round3
  5343. UNION ALL
  5344. SELECT CPA_NAME
  5345. FROM
  5346. #Round4
  5347. UNION ALL
  5348. SELECT CPA_NAME
  5349. FROM
  5350. #Round5
  5351. UNION ALL
  5352. SELECT CPA_NAME
  5353. FROM
  5354. #Round6
  5355. UNION ALL
  5356. SELECT CPA_NAME
  5357. FROM
  5358. #Round7
  5359. UNION ALL
  5360. SELECT CPA_NAME
  5361. FROM
  5362. #Round8
  5363. UNION ALL
  5364. SELECT CPA_NAME
  5365. FROM
  5366. #Round9
  5367. UNION ALL
  5368. SELECT CPA_NAME
  5369. FROM
  5370. #Round10)
  5371. GROUP BY CPA_NAME,CPAFirmName,cf.AccountID , cf.CPAFirmIndex
  5372.  
  5373.  
  5374.  
  5375. SELECT CPA_NAME,CPAFirmName,a.id AccountID, CPAFirmIndex
  5376. into #Round12
  5377. FROM
  5378. [fp&a]..CPAMatch cm
  5379. JOIN
  5380. SalesforceClone..account a on  a.name like '%' + cm.CPA_NAME + '%'
  5381. JOIN
  5382. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
  5383. WHERE
  5384.  CPA_NAME != 'Bbs' AND
  5385. CPA_NAME NOT IN (
  5386. SELECT CPA_NAME
  5387. FROM
  5388. #Round1
  5389. UNION ALL
  5390. SELECT CPA_NAME
  5391. FROM
  5392. #Round2
  5393. UNION ALL
  5394. SELECT CPA_NAME
  5395. FROM
  5396. #Round3
  5397. UNION ALL
  5398. SELECT CPA_NAME
  5399. FROM
  5400. #Round4
  5401. UNION ALL
  5402. SELECT CPA_NAME
  5403. FROM
  5404. #Round5
  5405. UNION ALL
  5406. SELECT CPA_NAME
  5407. FROM
  5408. #Round6
  5409. UNION ALL
  5410. SELECT CPA_NAME
  5411. FROM
  5412. #Round7
  5413. UNION ALL
  5414. SELECT CPA_NAME
  5415. FROM
  5416. #Round8
  5417. UNION ALL
  5418. SELECT CPA_NAME
  5419. FROM
  5420. #Round9
  5421. UNION ALL
  5422. SELECT CPA_NAME
  5423. FROM
  5424. #Round10
  5425. UNION ALL
  5426. SELECT CPA_NAME
  5427. FROM
  5428. #Round11)
  5429. GROUP BY CPA_NAME,CPAFirmName,a.id , CPAFirmIndex
  5430.  
  5431.  
  5432. SELECT CPA_NAME,CPAFirmName,a.id AccountID, CPAFirmIndex
  5433. into #Round13
  5434. FROM
  5435. [fp&a]..CPAMatch cm
  5436. JOIN
  5437. SalesforceClone..account a on  REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(a.name,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'  ',' ') = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(cm.CPA_NAME,'*',''),',',''),' & ',' '),' and ',' '),'.',''),'  ',' ')
  5438. JOIN
  5439. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
  5440. WHERE
  5441.  CPA_NAME != 'Bbs' AND
  5442. CPA_NAME NOT IN (
  5443. SELECT CPA_NAME
  5444. FROM
  5445. #Round1
  5446. UNION ALL
  5447. SELECT CPA_NAME
  5448. FROM
  5449. #Round2
  5450. UNION ALL
  5451. SELECT CPA_NAME
  5452. FROM
  5453. #Round3
  5454. UNION ALL
  5455. SELECT CPA_NAME
  5456. FROM
  5457. #Round4
  5458. UNION ALL
  5459. SELECT CPA_NAME
  5460. FROM
  5461. #Round5
  5462. UNION ALL
  5463. SELECT CPA_NAME
  5464. FROM
  5465. #Round6
  5466. UNION ALL
  5467. SELECT CPA_NAME
  5468. FROM
  5469. #Round7
  5470. UNION ALL
  5471. SELECT CPA_NAME
  5472. FROM
  5473. #Round8
  5474. UNION ALL
  5475. SELECT CPA_NAME
  5476. FROM
  5477. #Round9
  5478. UNION ALL
  5479. SELECT CPA_NAME
  5480. FROM
  5481. #Round10
  5482. UNION ALL
  5483. SELECT CPA_NAME
  5484. FROM
  5485. #Round11
  5486. UNION ALL
  5487. SELECT CPA_NAME
  5488. FROM
  5489. #Round12)
  5490. GROUP BY CPA_NAME,CPAFirmName,a.id , CPAFirmIndex
  5491.  
  5492.  
  5493. SELECT CPA_NAME,CPAFirmName,a.id AccountID, CPAFirmIndex
  5494. into #Round14
  5495. FROM
  5496. [fp&a]..CPAMatch cm
  5497. JOIN
  5498. 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','') ,'  ',' ')
  5499. JOIN
  5500. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
  5501. WHERE
  5502.  CPA_NAME != 'Bbs' AND
  5503. CPA_NAME NOT IN (
  5504. SELECT CPA_NAME
  5505. FROM
  5506. #Round1
  5507. UNION ALL
  5508. SELECT CPA_NAME
  5509. FROM
  5510. #Round2
  5511. UNION ALL
  5512. SELECT CPA_NAME
  5513. FROM
  5514. #Round3
  5515. UNION ALL
  5516. SELECT CPA_NAME
  5517. FROM
  5518. #Round4
  5519. UNION ALL
  5520. SELECT CPA_NAME
  5521. FROM
  5522. #Round5
  5523. UNION ALL
  5524. SELECT CPA_NAME
  5525. FROM
  5526. #Round6
  5527. UNION ALL
  5528. SELECT CPA_NAME
  5529. FROM
  5530. #Round7
  5531. UNION ALL
  5532. SELECT CPA_NAME
  5533. FROM
  5534. #Round8
  5535. UNION ALL
  5536. SELECT CPA_NAME
  5537. FROM
  5538. #Round9
  5539. UNION ALL
  5540. SELECT CPA_NAME
  5541. FROM
  5542. #Round10
  5543. UNION ALL
  5544. SELECT CPA_NAME
  5545. FROM
  5546. #Round11
  5547. UNION ALL
  5548. SELECT CPA_NAME
  5549. FROM
  5550. #Round12
  5551. UNION ALL
  5552. SELECT CPA_NAME
  5553. FROM
  5554. #Round13)
  5555. GROUP BY CPA_NAME,CPAFirmName,a.id , CPAFirmIndex
  5556.  
  5557.  
  5558.  
  5559.  
  5560.  
  5561. SELECT CPA_NAME,CPAFirmName,a1.CPA_Account__c AccountID, CPAFirmIndex
  5562. into #Round15
  5563. FROM
  5564. [fp&a]..CPAMatch cm
  5565. JOIN
  5566. 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','') ,'  ',' ')
  5567. JOIN
  5568. SalesforceClone..account a1 on  a1.CPA_Contact__c = c.id
  5569. JOIN
  5570. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a1.CPA_Account__c
  5571. WHERE
  5572.  CPA_NAME != 'Bbs' AND
  5573. CPA_NAME NOT IN (
  5574. SELECT CPA_NAME
  5575. FROM
  5576. #Round1
  5577. UNION ALL
  5578. SELECT CPA_NAME
  5579. FROM
  5580. #Round2
  5581. UNION ALL
  5582. SELECT CPA_NAME
  5583. FROM
  5584. #Round3
  5585. UNION ALL
  5586. SELECT CPA_NAME
  5587. FROM
  5588. #Round4
  5589. UNION ALL
  5590. SELECT CPA_NAME
  5591. FROM
  5592. #Round5
  5593. UNION ALL
  5594. SELECT CPA_NAME
  5595. FROM
  5596. #Round6
  5597. UNION ALL
  5598. SELECT CPA_NAME
  5599. FROM
  5600. #Round7
  5601. UNION ALL
  5602. SELECT CPA_NAME
  5603. FROM
  5604. #Round8
  5605. UNION ALL
  5606. SELECT CPA_NAME
  5607. FROM
  5608. #Round9
  5609. UNION ALL
  5610. SELECT CPA_NAME
  5611. FROM
  5612. #Round10
  5613. UNION ALL
  5614. SELECT CPA_NAME
  5615. FROM
  5616. #Round11
  5617. UNION ALL
  5618. SELECT CPA_NAME
  5619. FROM
  5620. #Round12
  5621. UNION ALL
  5622. SELECT CPA_NAME
  5623. FROM
  5624. #Round13
  5625. UNION ALL
  5626. SELECT CPA_NAME
  5627. FROM
  5628. #Round14)
  5629. GROUP BY CPA_NAME,CPAFirmName,a1.CPA_Account__c , CPAFirmIndex
  5630.  
  5631.  
  5632.  
  5633. SELECT CPA_NAME,CPAFirmName,c.AccountId AccountID, CPAFirmIndex
  5634. into #Round16
  5635. FROM
  5636. [fp&a]..CPAMatch cm
  5637. JOIN
  5638. 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','') ,'  ',' ')
  5639. --JOIN
  5640. --SalesforceClone..account a1 on  a1.id = c.AccountId
  5641. JOIN
  5642. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = c.AccountId
  5643. WHERE
  5644.  CPA_NAME != 'Bbs' AND CPAFirmName not in ('Miller Ward & Co','Welker Harris & Co') AND
  5645. CPA_NAME NOT IN (
  5646. SELECT CPA_NAME
  5647. FROM
  5648. #Round1
  5649. UNION ALL
  5650. SELECT CPA_NAME
  5651. FROM
  5652. #Round2
  5653. UNION ALL
  5654. SELECT CPA_NAME
  5655. FROM
  5656. #Round3
  5657. UNION ALL
  5658. SELECT CPA_NAME
  5659. FROM
  5660. #Round4
  5661. UNION ALL
  5662. SELECT CPA_NAME
  5663. FROM
  5664. #Round5
  5665. UNION ALL
  5666. SELECT CPA_NAME
  5667. FROM
  5668. #Round6
  5669. UNION ALL
  5670. SELECT CPA_NAME
  5671. FROM
  5672. #Round7
  5673. UNION ALL
  5674. SELECT CPA_NAME
  5675. FROM
  5676. #Round8
  5677. UNION ALL
  5678. SELECT CPA_NAME
  5679. FROM
  5680. #Round9
  5681. UNION ALL
  5682. SELECT CPA_NAME
  5683. FROM
  5684. #Round10
  5685. UNION ALL
  5686. SELECT CPA_NAME
  5687. FROM
  5688. #Round11
  5689. UNION ALL
  5690. SELECT CPA_NAME
  5691. FROM
  5692. #Round12
  5693. UNION ALL
  5694. SELECT CPA_NAME
  5695. FROM
  5696. #Round13
  5697. UNION ALL
  5698. SELECT CPA_NAME
  5699. FROM
  5700. #Round14
  5701. UNION ALL
  5702. SELECT CPA_NAME
  5703. FROM
  5704. #Round15)
  5705. GROUP BY CPA_NAME,CPAFirmName,c.AccountId , CPAFirmIndex
  5706.  
  5707.  
  5708.  
  5709. SELECT CPA_NAME,CPAFirmName,a1.CPA_Account__c AccountID, CPAFirmIndex
  5710. into #Round17
  5711. FROM
  5712. [fp&a]..CPAMatch cm
  5713. JOIN
  5714. 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','') ,'  ',' ')
  5715. JOIN
  5716. SalesforceClone..account a1 on  a1.id = c.AccountId
  5717. JOIN
  5718. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a1.CPA_Account__c
  5719. WHERE
  5720.  CPA_NAME != 'Bbs' AND CPAFirmName not in ('Miller Ward & Co','Welker Harris & Co','Harding Shymanski & Company Psc - Evansville IN') AND
  5721. CPA_NAME NOT IN (
  5722. SELECT CPA_NAME
  5723. FROM
  5724. #Round1
  5725. UNION ALL
  5726. SELECT CPA_NAME
  5727. FROM
  5728. #Round2
  5729. UNION ALL
  5730. SELECT CPA_NAME
  5731. FROM
  5732. #Round3
  5733. UNION ALL
  5734. SELECT CPA_NAME
  5735. FROM
  5736. #Round4
  5737. UNION ALL
  5738. SELECT CPA_NAME
  5739. FROM
  5740. #Round5
  5741. UNION ALL
  5742. SELECT CPA_NAME
  5743. FROM
  5744. #Round6
  5745. UNION ALL
  5746. SELECT CPA_NAME
  5747. FROM
  5748. #Round7
  5749. UNION ALL
  5750. SELECT CPA_NAME
  5751. FROM
  5752. #Round8
  5753. UNION ALL
  5754. SELECT CPA_NAME
  5755. FROM
  5756. #Round9
  5757. UNION ALL
  5758. SELECT CPA_NAME
  5759. FROM
  5760. #Round10
  5761. UNION ALL
  5762. SELECT CPA_NAME
  5763. FROM
  5764. #Round11
  5765. UNION ALL
  5766. SELECT CPA_NAME
  5767. FROM
  5768. #Round12
  5769. UNION ALL
  5770. SELECT CPA_NAME
  5771. FROM
  5772. #Round13
  5773. UNION ALL
  5774. SELECT CPA_NAME
  5775. FROM
  5776. #Round14
  5777. UNION ALL
  5778. SELECT CPA_NAME
  5779. FROM
  5780. #Round15
  5781. UNION ALL
  5782. SELECT CPA_NAME
  5783. FROM
  5784. #Round16)
  5785. GROUP BY CPA_NAME,CPAFirmName,a1.CPA_Account__c , CPAFirmIndex
  5786.  
  5787.  
  5788.  
  5789. SELECT CPA_NAME,CPAFirmName,a.id AccountID, CPAFirmIndex
  5790. into #Round18
  5791. FROM
  5792. [fp&a]..CPAMatch cm
  5793. JOIN
  5794. 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','') ,'  ',' ') + '%'
  5795. JOIN
  5796. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
  5797. WHERE
  5798.  CPA_NAME != 'Bbs' AND
  5799. CPA_NAME NOT IN (
  5800. SELECT CPA_NAME
  5801. FROM
  5802. #Round1
  5803. UNION ALL
  5804. SELECT CPA_NAME
  5805. FROM
  5806. #Round2
  5807. UNION ALL
  5808. SELECT CPA_NAME
  5809. FROM
  5810. #Round3
  5811. UNION ALL
  5812. SELECT CPA_NAME
  5813. FROM
  5814. #Round4
  5815. UNION ALL
  5816. SELECT CPA_NAME
  5817. FROM
  5818. #Round5
  5819. UNION ALL
  5820. SELECT CPA_NAME
  5821. FROM
  5822. #Round6
  5823. UNION ALL
  5824. SELECT CPA_NAME
  5825. FROM
  5826. #Round7
  5827. UNION ALL
  5828. SELECT CPA_NAME
  5829. FROM
  5830. #Round8
  5831. UNION ALL
  5832. SELECT CPA_NAME
  5833. FROM
  5834. #Round9
  5835. UNION ALL
  5836. SELECT CPA_NAME
  5837. FROM
  5838. #Round10
  5839. UNION ALL
  5840. SELECT CPA_NAME
  5841. FROM
  5842. #Round11
  5843. UNION ALL
  5844. SELECT CPA_NAME
  5845. FROM
  5846. #Round12
  5847. UNION ALL
  5848. SELECT CPA_NAME
  5849. FROM
  5850. #Round13
  5851. UNION ALL
  5852. SELECT CPA_NAME
  5853. FROM
  5854. #Round14
  5855. UNION ALL
  5856. SELECT CPA_NAME
  5857. FROM
  5858. #Round15
  5859. UNION ALL
  5860. SELECT CPA_NAME
  5861. FROM
  5862. #Round16
  5863. UNION ALL
  5864. SELECT CPA_NAME
  5865. FROM
  5866. #Round17)
  5867. GROUP BY CPA_NAME,CPAFirmName,a.id , CPAFirmIndex
  5868.  
  5869.  
  5870. SELECT CPA_NAME,CPAFirmName,a.id AccountID, CPAFirmIndex
  5871. into #Round19
  5872. FROM
  5873. [fp&a]..CPAMatch cm
  5874. JOIN
  5875. 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','') ,'  ',' ') + '%'
  5876. JOIN
  5877. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
  5878. WHERE
  5879.  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
  5880.  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
  5881. CPA_NAME NOT IN (
  5882. SELECT CPA_NAME
  5883. FROM
  5884. #Round1
  5885. UNION ALL
  5886. SELECT CPA_NAME
  5887. FROM
  5888. #Round2
  5889. UNION ALL
  5890. SELECT CPA_NAME
  5891. FROM
  5892. #Round3
  5893. UNION ALL
  5894. SELECT CPA_NAME
  5895. FROM
  5896. #Round4
  5897. UNION ALL
  5898. SELECT CPA_NAME
  5899. FROM
  5900. #Round5
  5901. UNION ALL
  5902. SELECT CPA_NAME
  5903. FROM
  5904. #Round6
  5905. UNION ALL
  5906. SELECT CPA_NAME
  5907. FROM
  5908. #Round7
  5909. UNION ALL
  5910. SELECT CPA_NAME
  5911. FROM
  5912. #Round8
  5913. UNION ALL
  5914. SELECT CPA_NAME
  5915. FROM
  5916. #Round9
  5917. UNION ALL
  5918. SELECT CPA_NAME
  5919. FROM
  5920. #Round10
  5921. UNION ALL
  5922. SELECT CPA_NAME
  5923. FROM
  5924. #Round11
  5925. UNION ALL
  5926. SELECT CPA_NAME
  5927. FROM
  5928. #Round12
  5929. UNION ALL
  5930. SELECT CPA_NAME
  5931. FROM
  5932. #Round13
  5933. UNION ALL
  5934. SELECT CPA_NAME
  5935. FROM
  5936. #Round14
  5937. UNION ALL
  5938. SELECT CPA_NAME
  5939. FROM
  5940. #Round15
  5941. UNION ALL
  5942. SELECT CPA_NAME
  5943. FROM
  5944. #Round16
  5945. UNION ALL
  5946. SELECT CPA_NAME
  5947. FROM
  5948. #Round17
  5949. UNION ALL
  5950. SELECT CPA_NAME
  5951. FROM
  5952. #Round18)
  5953. GROUP BY CPA_NAME,CPAFirmName,a.id , CPAFirmIndex
  5954. */
  5955. drop table if exists #Cpam
  5956. /*
  5957. SELECT CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS CPAFirmName,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS AccountID, CPAFirmIndex
  5958. into #cpam
  5959. FROM
  5960. #Round1
  5961. UNION ALL
  5962. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  5963. FROM
  5964. #Round2
  5965. UNION ALL
  5966. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  5967. FROM
  5968. #Round3
  5969. UNION ALL
  5970. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  5971. FROM
  5972. #Round4
  5973. UNION ALL
  5974. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  5975. FROM
  5976. #Round5
  5977. UNION ALL
  5978. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  5979. FROM
  5980. #Round6
  5981. UNION ALL
  5982. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  5983. FROM
  5984. #Round7
  5985. UNION ALL
  5986. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  5987. FROM
  5988. #Round8
  5989. UNION ALL
  5990. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  5991. FROM
  5992. #Round9
  5993. UNION ALL
  5994. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  5995. FROM
  5996. #Round10
  5997. UNION ALL
  5998. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  5999. FROM
  6000. #Round11
  6001. UNION ALL
  6002. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  6003. FROM
  6004. #Round12
  6005. UNION ALL
  6006. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  6007. FROM
  6008. #Round13
  6009. UNION ALL
  6010. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  6011. FROM
  6012. #Round14
  6013. UNION ALL
  6014. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  6015. FROM
  6016. #Round15
  6017. UNION ALL
  6018. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  6019. FROM
  6020. #Round16
  6021. UNION ALL
  6022. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  6023. FROM
  6024. #Round17
  6025. UNION ALL
  6026. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  6027. FROM
  6028. #Round18
  6029. UNION ALL
  6030. SELECT  CPA_NAME,CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS,AccountID COLLATE SQL_Latin1_General_CP1_CI_AS, CPAFirmIndex
  6031. FROM
  6032. #Round19
  6033. */
  6034.  
  6035.  
  6036. drop table if exists #Round0;
  6037. drop table if exists #acc;
  6038.  
  6039. SELECT CPA_NAME,CPAFirmName, AccountID, CPAFirmIndex
  6040. into #Round0
  6041. FROM
  6042. (
  6043. SELECT CPA_NAME,CPAFirmName,a.id AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn
  6044. FROM
  6045. [FP&A]..CPAMatch CM
  6046. JOIN
  6047. SalesforceClone..Account a on a.Name = CM.CPA_NAME
  6048. JOIN
  6049. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
  6050. LEFT JOIN
  6051. (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
  6052. FROM
  6053. TE_3E_PROD_Clone..AG_MattCPAFirm
  6054. GROUP BY CPAFirm
  6055. ) MCF on MCF.CPAFirm = CF.CPAFirmIndex
  6056. ) a WHERE rn = 1
  6057. GROUP BY CPA_NAME,CPAFirmName,AccountID , CPAFirmIndex
  6058.  
  6059. INSERT INTO #Round0
  6060. SELECT CPA_NAME,CPAFirmName,AccountID AccountID, CPAFirmIndex
  6061.  
  6062. FROM
  6063. (
  6064. SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn
  6065. FROM
  6066. [FP&A]..CPAMatch CM
  6067. JOIN
  6068. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS = cm.CPA_NAME
  6069. LEFT JOIN
  6070. (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
  6071. FROM
  6072. TE_3E_PROD_Clone..AG_MattCPAFirm
  6073. GROUP BY CPAFirm
  6074. ) MCF on MCF.CPAFirm = CF.CPAFirmIndex
  6075. WHERE AccountID is not null
  6076. ) a WHERE rn = 1
  6077.  
  6078. AND
  6079.  CPA_NAME NOT IN (
  6080. SELECT CPA_NAME
  6081. FROM
  6082. #Round0)
  6083. GROUP BY CPA_NAME,CPAFirmName,AccountID , CPAFirmIndex
  6084.  
  6085. 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
  6086. INTO #acc
  6087. FROM SalesforceClone..account  a
  6088.  
  6089. INSERT INTO #Round0
  6090. SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex
  6091. FROM
  6092. (
  6093. SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn
  6094. FROM
  6095. (SELECT * FROM
  6096. [fp&a]..CPAMatch cm
  6097. WHERE
  6098. 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
  6099. CPA_NAME NOT IN (
  6100. SELECT CPA_NAME
  6101. FROM
  6102. #Round0))cm
  6103. JOIN
  6104. #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','') ,'  ',' ') + '%'
  6105. JOIN
  6106. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
  6107. LEFT JOIN
  6108. (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
  6109. FROM
  6110. TE_3E_PROD_Clone..AG_MattCPAFirm
  6111. GROUP BY CPAFirm
  6112. ) MCF on MCF.CPAFirm = CF.CPAFirmIndex
  6113. WHERE AccountID is not null
  6114. AND
  6115.  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.')
  6116. ) a WHERE rn = 1
  6117. GROUP BY CPA_NAME,CPAFirmName,AccountID , CPAFirmIndex
  6118.  
  6119.  
  6120.  
  6121. INSERT INTO #Round0
  6122. SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex
  6123. FROM
  6124. (
  6125. SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn
  6126. FROM
  6127. (SELECT * FROM
  6128. [fp&a]..CPAMatch cm
  6129. WHERE
  6130. 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
  6131. CPA_NAME NOT IN (
  6132. SELECT CPA_NAME
  6133. FROM
  6134. #Round0))cm
  6135. JOIN
  6136. #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 + '%'
  6137. JOIN
  6138. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = a.id
  6139. LEFT JOIN
  6140. (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
  6141. FROM
  6142. TE_3E_PROD_Clone..AG_MattCPAFirm
  6143. GROUP BY CPAFirm
  6144. ) MCF on MCF.CPAFirm = CF.CPAFirmIndex
  6145. WHERE AccountID is not null
  6146. AND
  6147.  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.')
  6148. ) a WHERE rn = 1
  6149. GROUP BY CPA_NAME,CPAFirmName,AccountID , CPAFirmIndex
  6150.  
  6151.  
  6152. 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
  6153. INTO #acc3e
  6154. FROM TE_3E_PROD_Clone..AG_CPAFirm  a
  6155.  
  6156.  
  6157. INSERT INTO #Round0
  6158. SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex
  6159. FROM
  6160. (
  6161. SELECT CPA_NAME,name CPAFirmName,AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn
  6162. FROM
  6163. (SELECT * FROM
  6164. [fp&a]..CPAMatch cm
  6165. WHERE
  6166. 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
  6167. CPA_NAME NOT IN (
  6168. SELECT CPA_NAME
  6169. FROM
  6170. #Round0))cm
  6171. JOIN
  6172. #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 + '%'
  6173. LEFT JOIN
  6174. (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
  6175. FROM
  6176. TE_3E_PROD_Clone..AG_MattCPAFirm
  6177. GROUP BY CPAFirm
  6178. ) MCF on MCF.CPAFirm = a.CPAFirmIndex
  6179. WHERE AccountID is not null
  6180. AND
  6181.  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.')
  6182. ) a WHERE rn = 1
  6183. GROUP BY CPA_NAME,CPAFirmName,AccountID , CPAFirmIndex
  6184.  
  6185.  
  6186. INSERT INTO #Round0
  6187. SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex
  6188. FROM
  6189. (
  6190. SELECT CPA_NAME,name CPAFirmName,AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn
  6191. FROM
  6192. (SELECT * FROM
  6193. [fp&a]..CPAMatch cm
  6194. WHERE
  6195. 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
  6196. CPA_NAME NOT IN (
  6197. SELECT CPA_NAME
  6198. FROM
  6199. #Round0))cm
  6200. JOIN
  6201. #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','') ,'  ',' ') + '%'
  6202. LEFT JOIN
  6203. (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
  6204. FROM
  6205. TE_3E_PROD_Clone..AG_MattCPAFirm
  6206. GROUP BY CPAFirm
  6207. ) MCF on MCF.CPAFirm = a.CPAFirmIndex
  6208. WHERE AccountID is not null
  6209. AND
  6210.  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.')
  6211. ) a WHERE rn = 1
  6212. GROUP BY CPA_NAME,CPAFirmName,AccountID , CPAFirmIndex
  6213.  
  6214.  
  6215. INSERT INTO #Round0
  6216. SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex-- ,a2.name--,MatterNUmber
  6217. FROM
  6218. (
  6219. SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn,MatterNUmber
  6220. FROM
  6221. (SELECT CPA_NAME,MatterNUmber FROM
  6222. [fp&a]..CPAMatch CM
  6223. where
  6224. CPA_NAME NOT IN (SELECT CPA_NAME
  6225. FROM
  6226. #Round0) AND
  6227. ARMIndex IN (
  6228. SELECT ARMIndex
  6229. FROM
  6230. [fp&a]..CPAMatch
  6231. GROUP BY ARMIndex
  6232. HAVING COUNT(ARMIndex) = 1 AND SUM(COALESCE(TRY_CAST(AMOUNTDUETOCPA as numeric),0))>0)
  6233. GROUP BY  CPA_NAME,MatterNUmber
  6234. ) CM
  6235. JOIN
  6236. TE_3E_PROD_Clone..Matter M on M.NUmber COLLATE SQL_Latin1_General_CP1_CI_AS = CM.MatterNUmber
  6237. JOIN
  6238. (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
  6239. FROM
  6240. TE_3E_PROD_Clone..AG_MattCPAFirm
  6241. GROUP BY MatterLkup
  6242. HAVING COUNT(DISTINCT CPAFirm)=1
  6243. )
  6244. MCF on MCF.MatterLkup = M.MattINdex
  6245. JOIN
  6246. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
  6247. LEFT JOIN
  6248. (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
  6249. FROM
  6250. TE_3E_PROD_Clone..AG_MattCPAFirm
  6251. GROUP BY CPAFirm
  6252. ) MCF2 on MCF.CPAFirm = CF.CPAFirmIndex
  6253. WHERE AccountID is not null
  6254. ) a
  6255. JOIN
  6256. SalesForceClone..account a2 on a2.id = a.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS
  6257. WHERE rn = 1
  6258. GROUP BY
  6259. CPA_NAME,CPAFirmName,AccountID,CPAFirmIndex--,a2.name--,MatterNUmber
  6260.  
  6261.  
  6262.  
  6263.  
  6264. INSERT INTO #Round0
  6265. SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex-- ,a2.name--,MatterNUmber
  6266. FROM
  6267. (
  6268. SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn,MatterNUmber
  6269. FROM
  6270. (SELECT CPA_NAME,MatterNUmber FROM
  6271. [fp&a]..CPAMatch CM
  6272. where
  6273. CPA_NAME NOT IN (SELECT CPA_NAME
  6274. FROM
  6275. #Round0) AND
  6276. ARMIndex IN (
  6277. SELECT ARMIndex
  6278. FROM
  6279. [fp&a]..CPAMatch
  6280. GROUP BY ARMIndex
  6281. HAVING COUNT(ARMIndex) = 1 )
  6282. GROUP BY  CPA_NAME,MatterNUmber
  6283. ) CM
  6284. JOIN
  6285. TE_3E_PROD_Clone..Matter M on M.NUmber COLLATE SQL_Latin1_General_CP1_CI_AS = CM.MatterNUmber
  6286. JOIN
  6287. (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
  6288. FROM
  6289. TE_3E_PROD_Clone..AG_MattCPAFirm
  6290. GROUP BY MatterLkup
  6291. HAVING COUNT(DISTINCT CPAFirm)=1
  6292. )
  6293. MCF on MCF.MatterLkup = M.MattINdex
  6294. JOIN
  6295. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
  6296. LEFT JOIN
  6297. (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
  6298. FROM
  6299. TE_3E_PROD_Clone..AG_MattCPAFirm
  6300. GROUP BY CPAFirm
  6301. ) MCF2 on MCF.CPAFirm = CF.CPAFirmIndex
  6302. WHERE AccountID is not null
  6303. ) a
  6304. JOIN
  6305. SalesForceClone..account a2 on a2.id = a.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS
  6306. WHERE rn = 1
  6307. GROUP BY
  6308. CPA_NAME,CPAFirmName,AccountID,CPAFirmIndex--,a2.name--,MatterNUmber
  6309.  
  6310. INSERT INTO #Round0
  6311. SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex-- ,a2.name--,MatterNUmber
  6312. FROM
  6313. (
  6314. SELECT CPA_NAME,CPAFirmName,AccountID, CPAFirmIndex ,ROW_NUMBER()OVER(Partition By CPA_NAME Order By Nbr desc,MaxTS Desc) rn,MatterNUmber
  6315. FROM
  6316. (SELECT CPA_NAME,MatterNUmber FROM
  6317. [fp&a]..CPAMatch CM
  6318. where
  6319. CPA_NAME NOT IN (SELECT CPA_NAME
  6320. FROM
  6321. #Round0) AND
  6322. ARMIndex IN (
  6323. SELECT ARMIndex
  6324. FROM
  6325. [fp&a]..CPAMatch
  6326. where
  6327. CPA_NAME NOT IN (SELECT CPA_NAME
  6328. FROM
  6329. #Round0)
  6330. GROUP BY ARMIndex
  6331. HAVING COUNT(ARMIndex) = 1 )
  6332. GROUP BY  CPA_NAME,MatterNUmber
  6333. ) CM
  6334. JOIN
  6335. TE_3E_PROD_Clone..Matter M on M.NUmber COLLATE SQL_Latin1_General_CP1_CI_AS = CM.MatterNUmber
  6336. JOIN
  6337. (SELECT Matterlkup,MAX(CPAFirm) CPAFirm
  6338. FROM
  6339. TE_3E_PROD_Clone..AG_MattCPAFirm
  6340. where
  6341. CPAFirm NOT IN (SELECT CPAFirmIndex
  6342. FROM
  6343. #Round0)
  6344. GROUP BY MatterLkup
  6345. HAVING COUNT(DISTINCT CPAFirm)=1
  6346. )
  6347. MCF on MCF.MatterLkup = M.MattINdex
  6348. JOIN
  6349. TE_3E_PROD_Clone..AG_CPAFirm CF on CF.CPAFirmIndex = MCF.CPAFirm
  6350. LEFT JOIN
  6351. (SELECT CPAFirm,COUNT(1) Nbr,MAX(TimeStamp) MaxTS
  6352. FROM
  6353. TE_3E_PROD_Clone..AG_MattCPAFirm
  6354. GROUP BY CPAFirm
  6355. ) MCF2 on MCF.CPAFirm = CF.CPAFirmIndex
  6356. WHERE AccountID is not null
  6357. ) a
  6358. JOIN
  6359. SalesForceClone..account a2 on a2.id = a.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS
  6360. WHERE rn = 1
  6361. GROUP BY
  6362. CPA_NAME,CPAFirmName,AccountID,CPAFirmIndex--,a2.name--,MatterNUmber
  6363.  
  6364.  
  6365.  
  6366. SELECT CPA_NAME, CPAFirmName, AccountID, CPAFirmIndex
  6367. into #cpam
  6368. FROM
  6369. #Round0
  6370.  
  6371.  
  6372. --SELECT *
  6373. --FROM
  6374. --#cpam
  6375.  
  6376. drop table if exists #cpahm;
  6377.  
  6378.        select
  6379.               c.*
  6380.        --,      cpa1.[Type] [CPA1_Type]
  6381.        --,      cpa1.[ParentId] [CPA1_ParentId]
  6382.        --,      cpa1.CreatedDate [CPA1_CreatedDate]
  6383.        ,      coalesce(cpa4.[Id], cpa3.[Id], cpa2.[Id], cpa1.[Id]) [CPATop_AccountId]
  6384.        ,      coalesce(cpa4.[Name], cpa3.[Name], cpa2.[Name], cpa1.[Name]) [CPATop_Name]
  6385.        --,      cpa2.[Id] [CPA2_AccountId]
  6386.        --,      cpa2.[Name] [CPA2_Name]
  6387.        --,      cpa2.[ParentId] [CPA2_ParentId]
  6388.        --,      cpa3.[Id] [CPA3_AccountId]
  6389.        --,      cpa3.[Name] [CPA3_Name]
  6390.        --,      cpa3.[ParentId] [CPA3_ParentId]
  6391.        --,      cpa4.[Id] [CPA4_AccountId]
  6392.        --,      cpa4.[Name] [CPA4_Name]
  6393.        --,      cpa4.[ParentId] [CPA4_ParentId]
  6394.        into #cpahm
  6395.        from
  6396.               #cpam c
  6397.        left join
  6398.               SalesForceClone.dbo.Account cpa1 on cpa1.[Id] = c.AccountID
  6399.        left join
  6400.               SalesForceClone.dbo.Account cpa2 on cpa2.[Id] = cpa1.[ParentId]
  6401.        left join
  6402.               SalesForceClone.dbo.Account cpa3 on cpa3.[Id] = cpa2.[ParentId]
  6403.        left join
  6404.               SalesForceClone.dbo.Account cpa4 on cpa4.id = cpa3.ParentId
  6405.  
  6406.  
  6407.  
  6408.  
  6409. drop table if exists #cpa;
  6410.  
  6411.        select
  6412.               a.[CPAId]
  6413.        ,      a.[CPAName]
  6414.        into #cpa
  6415.        from
  6416.               (
  6417.                      select
  6418.                            o.Referring_CPA_Firm_ID__c [CPAId]
  6419.                      ,      o.CPA_Referral_Firm__c [CPAName]
  6420.                      from
  6421.                            SalesForceClone.dbo.Opportunity o
  6422.                      where
  6423.                            StageName like '%closed%'
  6424.                            and o.Referring_CPA_Firm_ID__c is not null
  6425.                      group by
  6426.                            o.Referring_CPA_Firm_ID__c
  6427.                      ,      o.CPA_Referral_Firm__c
  6428.  
  6429.                      union all
  6430.  
  6431.                      select
  6432.                            o.Amending_CPA_Firm_ID__c [CPAId]
  6433.                      ,      o.Amending_CPA_Firm__c [CPAName]
  6434.                      from
  6435.                            SalesForceClone.dbo.Opportunity o
  6436.                      where
  6437.                            StageName like '%closed%'
  6438.                            and o.Amending_CPA_Firm_ID__c is not null
  6439.                      group by
  6440.                            o.Amending_CPA_Firm_ID__c
  6441.                      ,      o.Amending_CPA_Firm__c
  6442.  
  6443.                      union all
  6444.  
  6445.                      select
  6446.                            cpa.Id [CPAId]
  6447.                      ,      cpa.[Name] [CPAName]
  6448.                      from
  6449.                            SalesForceClone.dbo.Opportunity o
  6450.                      left join
  6451.                            SalesForceClone.dbo.Account a on a.id = o.AccountId
  6452.                      left join
  6453.                            SalesForceClone.dbo.Account cpa on cpa.id = a.CPA_Account__c
  6454.                      where
  6455.                            o.StageName like '%closed%'
  6456.                            and cpa.Id is not null
  6457.                      group by
  6458.                            cpa.Id
  6459.                      ,      cpa.[Name]
  6460.               ) a
  6461.        group by
  6462.               [CPAId]
  6463.        ,      [CPAName]
  6464.  
  6465.  
  6466. drop table if exists #cpah;
  6467.  
  6468.        select
  6469.               c.[CPAId] [CPA1_AccountId]
  6470.        ,      c.[CPAName] [CPA1_Name]
  6471.        ,      cpa1.[Type] [CPA1_Type]
  6472.        ,      cpa1.[ParentId] [CPA1_ParentId]
  6473.        ,      cpa1.CreatedDate [CPA1_CreatedDate]
  6474.        ,      coalesce(cpa4.[Id], cpa3.[Id], cpa2.[Id], cpa1.[Id]) [CPATop_AccountId]
  6475.        ,      coalesce(cpa4.[Name], cpa3.[Name], cpa2.[Name], cpa1.[Name]) [CPATop_Name]
  6476.        ,      cpa2.[Id] [CPA2_AccountId]
  6477.        ,      cpa2.[Name] [CPA2_Name]
  6478.        ,      cpa2.[ParentId] [CPA2_ParentId]
  6479.        ,      cpa3.[Id] [CPA3_AccountId]
  6480.        ,      cpa3.[Name] [CPA3_Name]
  6481.        ,      cpa3.[ParentId] [CPA3_ParentId]
  6482.        ,      cpa4.[Id] [CPA4_AccountId]
  6483.        ,      cpa4.[Name] [CPA4_Name]
  6484.        ,      cpa4.[ParentId] [CPA4_ParentId]
  6485.        into #cpah
  6486.        from
  6487.               #cpa c
  6488.        left join
  6489.               SalesForceClone.dbo.Account cpa1 on cpa1.[Id] = c.[CPAId]
  6490.        left join
  6491.               SalesForceClone.dbo.Account cpa2 on cpa2.[Id] = cpa1.[ParentId]
  6492.        left join
  6493.               SalesForceClone.dbo.Account cpa3 on cpa3.[Id] = cpa2.[ParentId]
  6494.        left join
  6495.               SalesForceClone.dbo.Account cpa4 on cpa4.id = cpa3.ParentId
  6496.  
  6497.  
  6498. --SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
  6499.  
  6500. drop table if exists #Base;
  6501.  
  6502. SELECT CPAMatchId,
  6503. CPA_NAME
  6504. , CM.Client,
  6505.           CASE WHEN PAIDINFULL ='0' THEN NULL ELSE PAIDINFULL END [Client Paid In Full], CM.INVOICENUMBER,
  6506.           CASE WHEN (INVOICEDATE='1/0/1900' OR INVOICEDATE='0') THEN '' ELSE FORMAT(try_convert(DATE, INVOICEDATE), 'MM/dd/yyyy') END [Invoice Date],
  6507.           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],
  6508.           try_convert(DECIMAL(15,2),CASE WHEN AMOUNTPAID is null THEN '0' ELSE AMOUNTPAID END) [Amount Paid],
  6509.           try_convert(DECIMAL(15,2),CASE WHEN EXPENSES IS NULL THEN '0' ELSE EXPENSES END) [Expenses],
  6510.           try_convert(DECIMAL(15,2),CASE WHEN AMOUNTPAIDLESSEXPENSES IS NULL THEN '0' ELSE AMOUNTPAIDLESSEXPENSES END) [Amount Paid Less Expenses],
  6511.           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],
  6512.           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],
  6513.           CASE WHEN (DATEPAIDTOCPA='1/0/1900' OR DATEPAIDTOCPA='0') THEN '' ELSE FORMAT(try_convert(DATE, DATEPAIDTOCPA), 'MM/dd/yyyy') END [Date Paid],
  6514.           try_convert(Decimal(15,2), REMAININGDUETOCPA ) [Remaining Amount Due to CPA]
  6515.           ,CASE
  6516.           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)
  6517.           = 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
  6518.           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)
  6519.           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)
  6520.           = 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
  6521.           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)
  6522.           ELSE COALESCE(CASE WHEN nord.Mattindex is null and COALESCE(CM.ARMIndex,-1) != -1 THEN 225 END, MD.PG2,C.PG2,C2.PG2,-1)
  6523.           END
  6524.            SL
  6525.           ,CM.MattCategory
  6526.          
  6527.           INTO #Base
  6528.           FROM [FP&A].dbo.CPAMatch CM
  6529.           LEFT JOIN
  6530.           TE_3E_PROD_Clone..ARMaster AM on AM.ARMIndex = CM.ARMIndex
  6531.           OUTER APPLY
  6532.           (SELECT TOP 1 MD.* ,CASE WHEN MattStatus in ('KO','TERM') AND PracticeGRoup = 225 THEN 110
  6533.           WHEN  (pc.PGDetHdr is null OR FNDate >AM.InvDate) AND PracticeGRoup = 225 THEN 110
  6534.           ELSE PracticeGRoup END PG2,FnDate
  6535.           FROM
  6536.           TE_3E_PROD_Clone..MattDate MD
  6537.           JOIN
  6538.           TE_3E_PROD_Clone..Matter M on M.MattIndex = MD.Matterlkup
  6539.           JOIN
  6540.           TE_3E_PROD_Clone..PGDetHdr_CCC PH on PH.MatterLkUp = M.MattIndex --AND PH.NxEndDate = '99991231' AND PH.NxStartDate != '99991231'
  6541.           LEFT JOIN
  6542.           (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
  6543.           WHERE MD.MatterLkUp = AM.Matter and MD.NxEndDate = '99991231' --and MD.PracticeGroup IN (@PG)
  6544.           ORDER by MD.NxStartDate,COALESCE(FnDate,GETDATE())) MD
  6545.           OUTER APPLY
  6546.           (SELECT TOP 1 MD.*,CASE WHEN MattStatus in ('KO','TERM') AND PracticeGRoup = 225 THEN 110
  6547.           WHEN  (pc.PGDetHdr is null OR FNDate >IM.InvDate) AND PracticeGRoup = 225 THEN 110
  6548.           ELSE PracticeGRoup END PG2
  6549.           FROM
  6550.           TE_3E_PROD_Clone..Payor P
  6551.           JOIN
  6552.           TE_3E_PROD_Clone..InvMaster IM on IM.DefPayor = P.PayorIndex
  6553.           JOIN
  6554.           TE_3E_PROD_Clone..ARMaster AM on AM.InvMaster = IM.InvIndex
  6555.           JOIN
  6556.           TE_3E_PROD_Clone..MattDate MD on MD.MatterLkUp = AM.Matter  and NxEndDate = '99991231'
  6557.           JOIN
  6558.           TE_3E_PROD_Clone..Matter M on M.MattIndex = MD.Matterlkup
  6559.           JOIN
  6560.           TE_3E_PROD_Clone..PGDetHdr_CCC PH on PH.MatterLkUp = M.MattIndex --AND PH.NxEndDate = '99991231' AND PH.NxStartDate != '99991231'
  6561.           LEFT JOIN
  6562.           (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
  6563.           WHERE  P.Entity = CM.[CLIENT ID] --and MD.PracticeGroup IN (@PG)
  6564.           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())
  6565.           ) C
  6566.           OUTER APPLY
  6567.           (SELECT TOP 1 MD.*,CASE WHEN MattStatus in ('KO','TERM') AND PracticeGRoup = 225 THEN 110
  6568.           WHEN (pc.PGDetHdr is null OR FNDate >IM.InvDate) AND PracticeGRoup = 225 THEN 110
  6569.           ELSE PracticeGRoup END PG2
  6570.           FROM
  6571.           TE_3E_PROD_Clone..Payor P
  6572.           JOIN
  6573.           TE_3E_PROD_Clone..InvMaster IM on IM.DefPayor = P.PayorIndex
  6574.           JOIN
  6575.           TE_3E_PROD_Clone..ARMaster AM on AM.InvMaster = IM.InvIndex
  6576.           JOIN
  6577.           TE_3E_PROD_Clone..MattDate MD on MD.MatterLkUp = AM.Matter  and NxEndDate = '99991231'
  6578.           JOIN
  6579.           TE_3E_PROD_Clone..Matter M on M.MattIndex = MD.Matterlkup
  6580.           JOIN
  6581.           TE_3E_PROD_Clone..PGDetHdr_CCC PH on PH.MatterLkUp = M.MattIndex --AND PH.NxEndDate = '99991231' AND PH.NxStartDate != '99991231'
  6582.           LEFT JOIN
  6583.           (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
  6584.           WHERE  P.DisplayName COLLATE SQL_Latin1_General_CP1_CI_AS = CM.Client --and MD.PracticeGroup IN (@PG)
  6585.           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())
  6586.           ) C2
  6587.           OUTER APPLY
  6588.           (SELECT TOP 1 mrd.* FROM TE_3E_PROD_Clone..Matter m
  6589.           JOIN
  6590.           TE_3E_PROD_Clone..Client c on c.ClientIndex = m.Client
  6591.           JOIN
  6592.           TE_3E_PROD_Clone..Matter mrd on mrd.client = c.ClientINdex
  6593.           JOIN
  6594.           TE_3E_PROD_Clone..MattDate MD on MD.Matterlkup = mrd.MattIndex AND NxEndDate = '99991231' and NxStartDate != '99991231' and PracticeGroup in (110,120,130)
  6595.           WHERE m.MattIndex = AM. Matter) nord
  6596.          where
  6597.             cpamatchid not in (select cpamatchid from [FP&A].dbo.CPAMatch where ARMIndex != -1 and isnull(trim(AMOUNTDUETOCPA),'0') = '0' and CPAMatchId is not null)
  6598.          --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))
  6599.          --AND CPA_NAME = @CPAParameter) IN (@PG))
  6600.          --AND CPA_NAME = 'Somerset Cpas'
  6601.          
  6602. drop table if exists #SLD;
  6603.  
  6604. SELECT *
  6605. INTO #SLD
  6606. FROM (
  6607. SELECT CM.CPA_NAME
  6608. ,CM.[Amount Paid To CPA]
  6609. ,pg.Description SLD
  6610. FROM
  6611. (
  6612. SELECT *
  6613. FROM
  6614. #Base) CM
  6615.  
  6616.          LEFT JOIN
  6617.          TE_3E_PROD_CLONE..PracticeGRoup pg on pg.code = CM.SL
  6618.  
  6619. ) p PIVOT
  6620. (SUM([AMount Paid To CPA]) FOR SLD IN ([R&D Services],[ERC Services],[179D Services])) p
  6621.  
  6622.  
  6623. drop table if exists #SLO;
  6624.  
  6625. SELECT CPA_NAME
  6626. ,[R&D Services] [R&D Services OS]
  6627. ,[ERC Services] [ERC Services OS]
  6628. ,[179D Services] [179D Services OS]
  6629. INTO #SLO
  6630. FROM (
  6631. SELECT CM.CPA_NAME
  6632. ,CM.[Remaining Amount Due to CPA]
  6633. ,pg.Description SLD
  6634. FROM
  6635. (
  6636. SELECT *
  6637. FROM
  6638. #Base) CM
  6639.  
  6640.          LEFT JOIN
  6641.          TE_3E_PROD_CLONE..PracticeGRoup pg on pg.code = CM.SL
  6642.  
  6643. ) p PIVOT
  6644. (SUM([Remaining Amount Due to CPA]) FOR SLD IN ([R&D Services],[ERC Services],[179D Services])) p
  6645.  
  6646.  
  6647.  
  6648. drop table if exists #FAAmts;
  6649.  
  6650. SELECT
  6651.     [CPATop_AccountId]
  6652. ,   [CPATop_Name]
  6653. ,   SUM(ClientPaidLessExpenses) ClientPaidLessExpenses
  6654. ,   SUM(AMountDueToCPA)AMountDueToCPA
  6655. ,   SUM(AmountPaidToCPA) AmountPaidToCPA
  6656. ,   SUM([R&D Services]) [R&D Services]
  6657. ,   SUM([ERC Services])[ERC Services]
  6658. ,   SUM([Other Services])[Other Services]
  6659. ,   SUM(AmountOutStandingToCPA) AmountOutStandingToCPA
  6660. ,   SUM([R&D Services OS]) [R&D Services OS]
  6661. ,   SUM([ERC Services OS])[ERC Services OS]
  6662. ,   SUM([Other Services OS])[Other Services OS]
  6663. ,   SUM(ERCClientPaid)ERCClientPaid
  6664. INTO #FAAmts
  6665. FROM
  6666. (
  6667. SELECT a.*
  6668. ,   [CPATop_AccountId]
  6669. ,   [CPATop_Name]
  6670. ,ROW_NUMBER()OVER(PArtition by a.CPA_Name ORDER BY DIFFERENCE(a.CPA_NAME,CPATop_Name) desc) rn
  6671. FROM
  6672. (
  6673. SELECT
  6674.     a.CPA_Name
  6675. ,   State
  6676. ,   COUNT(Distinct a.Client) NbrClients
  6677.  
  6678. ,   SUM(TRY_CAST(InvoiceAmount as numeric(12,2))) ClientInvoices
  6679. ,   SUM(TRY_CAST(AMOUNTPAIDLESSEXPENSES as numeric(12,2))) ClientPaidLessExpenses
  6680. ,   SUM(TRY_CAST(AMOUNTDUETOCPA as numeric(12,2))) AMountDueToCPA
  6681. ,   SUM(TRY_CAST(AMOUNTPAIDTOCPA as numeric(12,2))) AmountPaidToCPA
  6682. ,   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]
  6683. ,   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]
  6684. ,   COALESCE(SUM(TRY_CAST(AMOUNTPAIDTOCPA as numeric(12,2))),0)
  6685.     -(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))
  6686.     -(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))
  6687.     [Other Services]
  6688. ,   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]
  6689. ,   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]
  6690. ,   COALESCE(SUM(TRY_CAST(REMAININGDUETOCPA as numeric(12,2))),0)
  6691.     -(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))
  6692.     -(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))
  6693.     [Other Services OS]
  6694. ,   SUM(TRY_CAST(REMAININGDUETOCPA as numeric(12,2)))  AmountOutStandingToCPA
  6695. ,   COUNT(DISTINCT CASE WHEN COALESCE([ERC Services],0) + COALESCE([ERC Services OS],0)>0 THEN Client END) ERCClientPaid
  6696. FROM (
  6697.  
  6698. 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
  6699. FROM
  6700. [FP&A]..CPAMatch CM
  6701.  
  6702. LEFT JOIN
  6703. (SELECT CPAEntity,CPAFirm
  6704. FROM
  6705. TE_3E_PROD_Clone..CPADetails_CCC
  6706. GROUP BY CPAEntity,CPAFirm)
  6707.  cd on cd.CPAEntity = CM.CPAID
  6708.  LEFT JOIN
  6709.  SalesforceClone..account a on a.Name = cd.CPAFirm COLLATE SQL_Latin1_General_CP1_CI_AS
  6710.  LEFT JOIN
  6711.  TE_3E_PROD_Clone..Payee P on P.NAme COLLATE SQL_Latin1_General_CP1_CI_AS = CM.CPA_NAME
  6712.  LEFT JOIN
  6713.  TE_3E_PROD_Clone..Site s on s.SiteIndex = P.CkSite
  6714.  LEFT JOIN
  6715.  TE_3E_PROD_Clone..Address ad on ad.AddrIndex = s.Address
  6716. LEFT JOIN
  6717. (SELECT CPAFirm,CPAState
  6718. FROM
  6719. TE_3E_PROD_Clone.[dbo].[NBI_Import_CPADetails_CCC]
  6720. GROUP BY CPAFirm,CPAState) NBF on NBF.CPAFirm = cd.CPAFirm
  6721. LEFT JOIN
  6722. TE_3E_PROD_Clone..Entity e on e.EntIndex = CM.CPAID
  6723. LEFT JOIN
  6724. (SELECT CPAName,CPAState
  6725. FROM
  6726. TE_3E_PROD_Clone.[dbo].[NBI_Import_CPADetails_CCC]
  6727. GROUP BY CPAName,CPAState
  6728. )  NBP on NBP.CPAName = e.DisplayName
  6729. LEFT JOIN
  6730. TE_3E_PROD_Clone.[dbo].[AG_CPAFirm] cf on cf.CPAFirmName COLLATE SQL_Latin1_General_CP1_CI_AS = CM.CPA_NAME
  6731. LEFT JOIN
  6732. SalesforceClone..account a2 on a2.id = cf.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS
  6733.  
  6734. ) a
  6735. LEFT JOIN
  6736. #SLD SL on SL.CPA_NAME = a.CPA_NAME
  6737. LEFT JOIN
  6738. #SLO SO on SO.CPA_NAME = a.CPA_NAME
  6739. GROUP BY
  6740.     a.CPA_Name
  6741. ,   State
  6742. ,   ([R&D Services])
  6743. ,   ([ERC Services])
  6744. ,   [179D Services]
  6745. ,   ([R&D Services OS])
  6746. ,   ([ERC Services OS])
  6747. ,   [179D Services OS]
  6748. ) a
  6749. JOIN
  6750. #cpahm chm on chm.CPA_NAme = a.CPA_NAME
  6751. )b
  6752. WHERE rn = 1
  6753. GROUP BY
  6754.     [CPATop_AccountId]
  6755. ,   [CPATop_Name]
  6756.  
  6757.  
  6758. drop table if exists #cpafinal;
  6759.  
  6760.        select
  6761.               o.Id [OpportunityId]
  6762.        ,      a.id [AccountId]
  6763.        ,      a.[Name] [AccountName]
  6764.        ,      c.CPA1_AccountId [CPAAccountId]
  6765.        ,      c.CPATop_Name [CPAName]
  6766.        ,      c.[CPATop_AccountId] [CPATop_AccountId]
  6767.        ,      con.[Name] [CPAContact]
  6768.  
  6769.        into #cpafinal
  6770.        from
  6771.               SalesForceClone.dbo.Account a
  6772.        left join
  6773.               SalesForceClone.dbo.Contact con on con.Id = a.CPA_Contact__c
  6774.        join
  6775.            SalesforceClone.dbo.Opportunity o on o.AccountId = a.Id
  6776.        left join
  6777.               #cpah c on c.CPA1_AccountId = COALESCE(a.CPA_Account__c,o.Amending_CPA_Firm_ID__c ,o.Referring_CPA_Firm_ID__c)
  6778.        group by
  6779.               o.Id
  6780.        ,      a.id
  6781.        ,      a.[Name]
  6782.        ,      c.CPA1_AccountId
  6783.        ,      c.CPATop_Name
  6784.        ,      con.[Name]
  6785.        ,      c.[CPATop_AccountId]
  6786.        
  6787.  
  6788.        drop table if exists #IsTalent;
  6789.  
  6790.        SELECT AccountId
  6791.        ,    CASE WHEN Service_Type__c IN ('External Audit','Tax Services','AMS','Business Advisory & Valuation') THEN 1 ELSE 0 END IsTalent
  6792.        into #IsTalent
  6793.        FROM
  6794.        SalesforceClone.dbo.Opportunity
  6795.        WHERE
  6796.        Service_Type__c IN ('External Audit','Tax Services','AMS','Business Advisory & Valuation')
  6797.        GROUP BY
  6798.        AccountId
  6799.        ,    CASE WHEN Service_Type__c IN ('External Audit','Tax Services','AMS','Business Advisory & Valuation') THEN 1 ELSE 0 END
  6800.  
  6801.  
  6802. drop table if exists #Credits;
  6803.  
  6804. select
  6805.        m.[MattIndex]
  6806. ,      m.[Number] [Job_No]
  6807. ,      m.OpportunityID_CCC [OpportunityId]
  6808. ,      c.AccountID_CCC [AccountId]
  6809. ,      m.[DisplayName] [Description]
  6810. ,      m.[Client]
  6811. ,      c.[DisplayName] [Company]
  6812. ,      s.[Code] [State]
  6813. ,      m.[EngSignedDate_CCC] [DateSigned]
  6814. ,      year(m.[EngSignedDate_CCC]) [Year]
  6815. ,      replace(ms.[Description],'CLOSING','Closing') [Status]
  6816. ,      md.[Description] SL
  6817. ,      case
  6818.               when m.MattCategory = 'NEW' then 'New'
  6819.               when m.MattCategory  = 'FU' then 'FU'
  6820.               when et.[Description] = 'New Business' then 'New'
  6821.               when et.[Description] = 'Follow - Up' then 'FU'
  6822.               when et.[Description] = 'Continuation' then 'Continuation'
  6823.               end [New_FU]
  6824. ,     isnull ( coalesce(pc.[FinalCredits],0), 0) [FinalCredit]
  6825. ,     Coalesce(pc.[Total],0) [Total]
  6826. ,     case when md.[PracticeGroup] = 225 then coalesce(pc.[FinalCredits],0) else Coalesce(pc.[Total],0) end [Total2]
  6827. ,      atk.[BD1] [PBD]
  6828. ,      CASE WHEN BDMC.[MattIndex] is not null then 1 else 0 end [StudyCount]
  6829. ,      cpa.[CPAAccountId]
  6830. ,      coalesce(cpa.[CPAName],'Direct') [CPA]
  6831. ,      cpa.[CPAContact] [CPA_Contact]
  6832. ,      case when md.[PracticeGroup] = 225 then 1 else 0 end [isERC]
  6833. ,   case when pc.[FinalCredits]!= 0 then 1 else pc.[FinalCredits] end isFinalCredits
  6834. ,    CASE WHEN BDM.[MattIndex] is not null  then AdjustedWIP else 0 end AdjWIP
  6835. ,   SUM(CASE WHEN BDM.[MattIndex] is not null  then AdjustedWIP else 0 end)OVER(Partition BY m.[Client]) ClientTotalWIP
  6836. ,   [CPATop_AccountId]
  6837.  
  6838.  
  6839. into #Credits
  6840. from
  6841.        TE_3E_PROD_Clone.dbo.Matter m
  6842. LEFT JOIN
  6843. (SELECT BDM.[MattIndex],SUM(AdjustedWIP)AdjustedWIP,OpportunityIDCCC
  6844. FROM
  6845. [FP&A].BDM.BDMasterUnpublished BDM
  6846. WHERE
  6847. BDM.[EngTypeCCC] = 'New'
  6848. GROUP BY BDM.[MattIndex],OpportunityIDCCC) BDM on BDM.[MattIndex] = m.Mattindex
  6849. LEFT JOIN
  6850. (SELECT BDM.[MattIndex],OpportunityIDCCC
  6851. FROM
  6852. [FP&A].BDM.BDMasterUnpublished BDM
  6853. WHERE
  6854. BDM.[EngTypeCCC] = 'New' and BDM.OneTimeAdj = '0'
  6855. GROUP BY BDM.[MattIndex],OpportunityIDCCC) BDMC on BDMC.[MattIndex] = m.Mattindex
  6856. join
  6857.        TE_3E_PROD_Clone.dbo.Client c on c.ClientIndex = m.Client
  6858. left join
  6859.        TE_3E_PROD_Clone.[dbo].[Site] si on si.[SiteIndex] = c.[InvoiceSite]
  6860. left join
  6861.        TE_3E_PROD_Clone.[dbo].[Address] a on si.[Address] = a.[AddrIndex]
  6862. left join
  6863.        TE_3E_PROD_Clone.[dbo].[State] s on a.[State] = s.[Code]
  6864. join
  6865.        TE_3E_PROD_Clone.dbo.MattStatus ms on ms.code = m.MattStatus
  6866. left join
  6867.        TE_3E_PROD_Clone.[dbo].[EngType_CCC] et on et.[Code] = m.[EngType_CCC]
  6868. left join
  6869.        (
  6870.               select
  6871.                      row_number() over(partition by MatterLkUp order by effstart desc, nxStartDate desc, nxEndDate desc) [Rn]
  6872.               ,      PGDetHdr_CCCID
  6873.               ,      MatterLkUp
  6874.               ,     AdjWIP
  6875.               from
  6876.                      TE_3E_PROD_Clone.dbo.PGDetHdr_CCC
  6877.        ) ph on ph.MatterLkUp = m.MattIndex and ph.[Rn] = 1
  6878. left join
  6879.        (
  6880.               select
  6881.                      PGDetHdr
  6882.               ,      sum([FinalCredit]) [FinalCredits]
  6883.              ,       sum([Total]) [Total]
  6884.               from
  6885.                      TE_3E_PROD_Clone.dbo.PGDetChild_CCC
  6886.               group by
  6887.                      PGDetHdr
  6888.        ) pc on pc.PGDetHdr = ph.PGDetHdr_CCCID
  6889. left join
  6890.        (
  6891.               select
  6892.                      row_number() over(partition by md.MatterLkUp order by md.effstart desc, md.nxStartDate desc, md.nxEndDate desc) [Rn]
  6893.               ,      md.MatterLkUp
  6894.               ,      md.[PracticeGroup]
  6895.               ,      pg.[Description]
  6896.               from
  6897.                      TE_3E_PROD_Clone.dbo.MattDate md
  6898.               left join
  6899.                      TE_3E_PROD_Clone.dbo.PracticeGroup pg on pg.code = md.PracticeGroup
  6900.        ) md on md.MatterLkUp = m.MattIndex and md.[Rn] = 1
  6901. left join
  6902.        (
  6903.               select
  6904.                      row_number() over (partition by atk.[MatterLkUp] order by atk.[EffStart] desc) [Rn]
  6905.               ,      atk.[MatterLkUp]
  6906.               ,      atk.[BDTkpr1]
  6907.               ,      [FP&A].[dbo].[fGetFirstNameLastName](tk.DisplayName) [BD1]
  6908.               from
  6909.                      TE_3E_PROD_Clone.[dbo].[AssociatedTkprs_CCC] atk
  6910.               left join
  6911.                      TE_3E_PROD_Clone.dbo.Timekeeper tk on tk.TkprIndex = atk.BDTkpr1
  6912.        ) atk on atk.[MatterLkUp] = m.[MattIndex] and atk.[rn] = 1
  6913. left join
  6914.        #cpafinal cpa on cpa.OpportunityId = m.OpportunityID_CCC collate SQL_Latin1_General_CP1_CI_AS
  6915. where
  6916.     ms.[Description] not in ('Cancel NoEL Received','Cancelled - Duplicate')
  6917.     and md.[Description] not like '%-Z%'
  6918.  
  6919.  
  6920.  
  6921.  
  6922.  
  6923. drop table if exists [FP&A]..CPAMatchandCredits;
  6924.  
  6925. SELECT
  6926.     c.ParentCPA
  6927. ,   a.BillingState State
  6928. ,   a.BillingCity City
  6929. ,   a.BillingPostalCode CPAZipCode
  6930. ,   COALESCE(a.Alliance__c,'Direct') Alliance
  6931. ,   bd.Name BD
  6932. ,   rd.Name RD
  6933. ,   credits.NoofClients
  6934. ,   Credits.StudyCount
  6935. ,   FA.ClientPaidLessExpenses
  6936. ,   FA.AMountDueToCPA TotalAmountDuetoCPA
  6937. ,   FA.AmountPaidToCPA TotalPaidtoCPA
  6938. ,   FA.AmountOutStandingToCPA TotalAmountOutsandingtoCPA
  6939. ,   COALESCE(FA.[ERC Services],0) + COALESCE(FA.[ERC Services OS],0) ERCAmountDueToCPA
  6940. ,   COALESCE(FA.[ERC Services],0) ERCPaidToCPA
  6941. ,   COALESCE(FA.[ERC Services OS],0) ERCAmountOutstandingToCPA
  6942. ,   COALESCE(FA.[R&D Services],0) + COALESCE(FA.[R&D Services OS],0) [R&DAmountDueToCPA]
  6943. ,   COALESCE(FA.[R&D Services],0) [R&DPaidToCPA]
  6944. ,   COALESCE(FA.[R&D Services OS],0) [R&DAmountOutstandingToCPA]
  6945. ,   COALESCE(FA.[Other Services],0) + COALESCE(FA.[Other Services OS],0) OtherAmountDueToCPA
  6946. ,   COALESCE(FA.[Other Services],0) OtherPaidToCPA
  6947. ,   COALESCE(FA.[Other Services OS],0) OtherAmountOutstandingToCPA
  6948. ,   credits.AdjWIP [TotalAdjustedWIP]
  6949. ,   credits.NoofBigClients
  6950. ,   TotalCreditsDElivered
  6951. ,   NoofERCClients
  6952. ,   CASE WHEN ERCClientPaid>NoofERCClients THEN NoofERCClients ELSE ERCClientPaid END ERCClientPaid
  6953. ,   ERCCreditsDElivered
  6954. ,   bderc.Name ERCBD
  6955. ,   rderc.Name ERCRD
  6956. ,   RDNew
  6957. ,   RDFU
  6958. ,   ERC
  6959. ,   CASE WHEN IsTalent = 1 THEN 'Yes' ELSE 'No' END IsTalent
  6960. INTO [FP&A]..CPAMatchandCredits
  6961. FROM
  6962. (SELECT CPATop_Name ParentCPA
  6963.     ,CPATop_AccountId ParentCPAId
  6964.     FROM
  6965.     #cpah c
  6966.     GROUP BY
  6967.      CPATop_Name
  6968.     ,CPATop_AccountId) c
  6969. JOIN
  6970. SalesforceClone..Account a on a.id = c.ParentCPAId
  6971. JOIN
  6972. SalesforceClone..[User] bd on bd.id = a.OwnerId
  6973. LEFT JOIN
  6974. SalesforceClone..[User] rd on rd.id = a.caller__c
  6975. LEFT JOIN
  6976. (SELECT [CPATop_AccountId]
  6977. ,   COUNT(DISTINCT AccountId) NoofClients
  6978. ,   COUNT(DISTINCT CASE WHEN ClientTotalWIP>100000 THEN AccountId END) NoofBigClients
  6979. ,   SUM(AdjWIP) AdjWIP
  6980. ,   SUM([FinalCredit]) TotalCreditsDElivered
  6981. ,   COUNT(DISTINCT CASE WHEN isERC = 1 THEN AccountId END) NoofERCClients
  6982. ,   SUM(DISTINCT CASE WHEN isERC = 1 THEN [FinalCredit] END) ERCCreditsDElivered
  6983. ,   SUM(StudyCount)StudyCount
  6984.  
  6985. FROM
  6986. #Credits
  6987. GROUP BY
  6988. [CPATop_AccountId]
  6989. ) Credits on credits.[CPATop_AccountId] = c.ParentCPAId
  6990. LEFT JOIN
  6991. #FAAmts FA on FA.CPATop_AccountId = c.ParentCPAId
  6992. LEFT JOIN
  6993. SalesforceClone..[User] bderc on bderc.id = a.[Technical_Director_ERC__c]
  6994. LEFT JOIN
  6995. SalesforceClone..[User] rderc on rderc.id = a.[ERC_Relationship_Director__c]
  6996. LEFT JOIN (
  6997. SELECT *
  6998. FROM
  6999. (
  7000. SELECT AccountID
  7001. ,   Case
  7002.         when EngagementType = 150 AND PracticeGroup = 110 THEN 'RDNew'
  7003.         WHEN EngagementType = 125 AND PracticeGroup = 110 THEN 'RDFU'
  7004.         WHEN PracticeGroup = 225 THEN 'ERC'
  7005.         ELSE 'Other'
  7006.         END Type
  7007. ,   ACFDD.FeePercentage
  7008. FROM
  7009. [TE_3E_PROD_Clone].dbo.[AG_CPAFirm] ACF
  7010. JOIN
  7011. [TE_3E_PROD_Clone].[dbo].[AG_CPAFirmDate] ACFD on ACF.CPAFirmIndex = ACFD.AG_CPAFirmLkUp and ACFD.NxEndDate  = '99991231' and ACFD.NxStartDate != '99991231'
  7012. JOIN
  7013. [TE_3E_PROD_Clone].[dbo].[AG_CPAFirmDateDet] ACFDD on ACFDD.CPAFirmDate = ACFD.AG_CPAFirmDateID
  7014. WHERE
  7015.  PracticeGroup IN (110,225)
  7016. )a
  7017. PIVOT (MAX(FeePercentage) FOR TYpe in ([RDNew],[RDFU],[ERC]))p
  7018. ) Perc on Perc.AccountID COLLATE SQL_Latin1_General_CP1_CI_AS = c.ParentCPAId
  7019. LEFT JOIN
  7020. #IsTalent T on T.AccountId = c.ParentCPAId
  7021.  
  7022. END
  7023.  
  7024.  
  7025. --END OF PROCESS
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement