-- SCHEMA: fw

---------------------------------------------
--  TABLES
---------------------------------------------


---------------------------------------------
-- fw.ABBBudgetedCostPerRVU ------------------
---------------------------------------------
CREATE TABLE [fw].[ABBBudgetedCostPerRVU] (
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeID] int NOT NULL,
    [CostComponentID] int NOT NULL,
    [CostingConfigGuid] uniqueidentifier NOT NULL,
    [VariableDirectUnitCostPerRVU] decimal NULL,
    [TotalVariableDirectCost] decimal NULL,
    [TotalCost] decimal NULL
);
GO

---------------------------------------------

---------------------------------------------
-- fw.ABBFlexingReconciliation ------------------
---------------------------------------------
CREATE TABLE [fw].[ABBFlexingReconciliation] (
    [RowID] int NOT NULL,
    [CostingConfigGUID] uniqueidentifier NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [AccountID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeID] int NOT NULL,
    [CostComponentID] int NOT NULL,
    [ActualChargeUnits] decimal NOT NULL,
    [ActualChargeUnitsYTD] decimal NOT NULL,
    [ActualVariableDirectCost] decimal NOT NULL,
    [ActualVariableDirectCostYTD] decimal NOT NULL,
    [ActualFixedDirectCost] decimal NOT NULL,
    [ActualFixedDirectCostYTD] decimal NOT NULL,
    [BudgetChargeUnits] decimal NOT NULL,
    [BudgetChargeUnitsYTD] decimal NOT NULL,
    [BudgetVariableDirectCost] decimal NOT NULL,
    [BudgetVariableDirectCostYTD] decimal NOT NULL,
    [BudgetFixedDirectCost] decimal NOT NULL,
    [BudgetFixedDirectCostYTD] decimal NOT NULL,
    [FlexedVariableDirectCost] decimal NOT NULL,
    [FlexedVariableDirectCostYTD] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [IX_Unique] ON [fw].[ABBFlexingReconciliation] ([CostingConfigGUID], [FiscalYearID], [FiscalMonthID], [EntityID], [DepartmentID], [ChargeCodeID], [AccountID], [JobCodeID], [PayCodeID], [CostComponentID]);
GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Costi__2637F561] DEFAULT (newid()) FOR [CostingConfigGUID]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Fisca__272C199A] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Fisca__28203DD3] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Entit__2914620C] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Depar__2A088645] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Charg__2AFCAA7E] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Accou__2BF0CEB7] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__JobCo__2CE4F2F0] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__PayCo__2DD91729] DEFAULT ((0)) FOR [PayCodeID]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__CostC__2ECD3B62] DEFAULT ((0)) FOR [CostComponentID]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Actua__2FC15F9B] DEFAULT ((0)) FOR [ActualChargeUnits]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Actua__30B583D4] DEFAULT ((0)) FOR [ActualChargeUnitsYTD]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Actua__31A9A80D] DEFAULT ((0)) FOR [ActualVariableDirectCost]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Actua__329DCC46] DEFAULT ((0)) FOR [ActualVariableDirectCostYTD]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Actua__3391F07F] DEFAULT ((0)) FOR [ActualFixedDirectCost]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Actua__348614B8] DEFAULT ((0)) FOR [ActualFixedDirectCostYTD]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Budge__357A38F1] DEFAULT ((0)) FOR [BudgetChargeUnits]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Budge__366E5D2A] DEFAULT ((0)) FOR [BudgetChargeUnitsYTD]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Budge__37628163] DEFAULT ((0)) FOR [BudgetVariableDirectCost]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Budge__3856A59C] DEFAULT ((0)) FOR [BudgetVariableDirectCostYTD]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Budge__394AC9D5] DEFAULT ((0)) FOR [BudgetFixedDirectCost]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Budge__3A3EEE0E] DEFAULT ((0)) FOR [BudgetFixedDirectCostYTD]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Flexe__3B331247] DEFAULT ((0)) FOR [FlexedVariableDirectCost]; GO
ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Flexe__3C273680] DEFAULT ((0)) FOR [FlexedVariableDirectCostYTD]; GO

---------------------------------------------

---------------------------------------------
-- fw.ABBFlexingReconciliationCostingData ------------------
---------------------------------------------
CREATE TABLE [fw].[ABBFlexingReconciliationCostingData] (
    [CostingConfigGUID] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    [OriginalDepartmentID] int NOT NULL,
    [OriginalJobCodeID] int NOT NULL,
    [OriginalPayCodeID] int NOT NULL,
    [OriginalAccountID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [FiscalYearID] int NOT NULL,
    [FiscalMonthID] int NOT NULL,
    [CostComponentID] int NOT NULL,
    [FixedDirectUnitCost] decimal NOT NULL,
    [VariableDirectUnitCost] decimal NOT NULL,
    [BudgetFixedDirectUnitCost] decimal NOT NULL,
    [BudgetVariableDirectUnitCost] decimal NOT NULL,
    [ActualMonthlyVolume] decimal NOT NULL,
    [BudgetedMonthlyVolume] decimal NOT NULL,
    [RVU] money NOT NULL
);

CREATE NONCLUSTERED INDEX [IX_BudgetedMonthlyVolume] ON [fw].[ABBFlexingReconciliationCostingData] ([CostingConfigGUID], [OriginalDepartmentID], [OriginalJobCodeID], [OriginalPayCodeID], [OriginalAccountID], [ChargeCodeID], [FiscalYearID], [CostComponentID], [FiscalMonthID]) INCLUDE ([BudgetFixedDirectUnitCost], [BudgetedMonthlyVolume]);
CREATE NONCLUSTERED INDEX [IX_OriginalDepartmentID] ON [fw].[ABBFlexingReconciliationCostingData] ([OriginalDepartmentID]) INCLUDE ([CostingConfigGUID], [EntityID], [OriginalJobCodeID], [OriginalPayCodeID], [OriginalAccountID], [ChargeCodeID], [FiscalYearID], [FiscalMonthID], [CostComponentID], [FixedDirectUnitCost], [VariableDirectUnitCost], [BudgetFixedDirectUnitCost], [BudgetVariableDirectUnitCost], [ActualMonthlyVolume], [BudgetedMonthlyVolume]);
CREATE NONCLUSTERED INDEX [IX_viewABBFlexingReconciliation] ON [fw].[ABBFlexingReconciliationCostingData] ([EntityID], [OriginalDepartmentID], [ChargeCodeID], [FiscalYearID], [FiscalMonthID]) INCLUDE ([CostingConfigGUID], [OriginalJobCodeID], [OriginalPayCodeID], [OriginalAccountID], [CostComponentID], [FixedDirectUnitCost], [VariableDirectUnitCost], [BudgetFixedDirectUnitCost], [BudgetVariableDirectUnitCost], [ActualMonthlyVolume], [BudgetedMonthlyVolume]);
CREATE NONCLUSTERED INDEX [IX_ABBFlexingReconciliationCostingData_Perf1] ON [fw].[ABBFlexingReconciliationCostingData] ([CostingConfigGUID], [EntityID], [OriginalDepartmentID], [OriginalJobCodeID], [OriginalPayCodeID], [OriginalAccountID], [ChargeCodeID], [FiscalYearID], [CostComponentID], [FiscalMonthID]) INCLUDE ([BudgetFixedDirectUnitCost], [BudgetedMonthlyVolume]);
CREATE NONCLUSTERED INDEX [IX_ABBFlexingReconciliationCostingData_Perf2] ON [fw].[ABBFlexingReconciliationCostingData] ([CostingConfigGUID], [OriginalDepartmentID], [OriginalAccountID], [ChargeCodeID], [FiscalYearID]) INCLUDE ([EntityID], [OriginalJobCodeID], [OriginalPayCodeID], [FiscalMonthID], [CostComponentID], [FixedDirectUnitCost], [VariableDirectUnitCost], [BudgetFixedDirectUnitCost], [BudgetVariableDirectUnitCost], [ActualMonthlyVolume], [BudgetedMonthlyVolume], [RVU]);
GO
ALTER TABLE [fw].[ABBFlexingReconciliationCostingData] ADD CONSTRAINT [DF__ABBFlexingR__RVU__4C32B5C0] DEFAULT ((0.0)) FOR [RVU]; GO

---------------------------------------------

---------------------------------------------
-- fw.ABBFlexingReconciliationEncounterInfoData ------------------
---------------------------------------------
CREATE TABLE [fw].[ABBFlexingReconciliationEncounterInfoData] (
    [DepartmentID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [FiscalYearID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [FiscalMonthID] int NOT NULL,
    [EncounterCount] int NOT NULL
);
GO

---------------------------------------------

---------------------------------------------
-- fw.DepartmentChargeCodePrimaryStatisticMappingCache ------------------
---------------------------------------------
CREATE TABLE [fw].[DepartmentChargeCodePrimaryStatisticMappingCache] (
    [RowID] bigint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [DepartmentID] int NOT NULL,
    [OriginalDepartmentID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [PatientTypeRollupID] int NOT NULL,
    [AccountID] int NOT NULL,
    [Weight] decimal NOT NULL,
    [IsStaffing] bit NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE NONCLUSTERED INDEX [CORE_OriginalDepartmentID_FiscalYearID_ChargeCodeID_PatientTypeRollupID_IsStaffing] ON [fw].[DepartmentChargeCodePrimaryStatisticMappingCache] ([OriginalDepartmentID], [FiscalYearID], [ChargeCodeID], [PatientTypeRollupID], [IsStaffing]);
GO

---------------------------------------------

---------------------------------------------
-- fw.DepartmentChargeCodeStatisticMapping ------------------
---------------------------------------------
CREATE TABLE [fw].[DepartmentChargeCodeStatisticMapping] (
    [RowID] bigint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [DepartmentRollupLevelMemberID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [PatientTypeRollupID] tinyint NOT NULL,
    [AccountID] int NOT NULL,
    [Weight] decimal NOT NULL,
    [IsReviewed] bit NOT NULL,
    [DepartmentRollupLevelMemberColumnName] nvarchar(64) NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [FK__Departmen__Charg__67D1ABB5] FOREIGN KEY ([ChargeCodeID]) REFERENCES [fw].[DimChargeCode] ([ChargeCodeID]); GO
ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [DF_DepartmentChargeCodeStatisticMapping_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [DF_DepartmentChargeCodeStatisticMapping_DepartmentID] DEFAULT ((0)) FOR [DepartmentRollupLevelMemberID]; GO
ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [DF_DepartmentChargeCodeStatisticMapping_ChargeCodeID] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [DF_DepartmentChargeCodeStatisticMapping_PatientTypeRollupID] DEFAULT ((0)) FOR [PatientTypeRollupID]; GO
ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [DF_DepartmentChargeCodeStatisticMapping_AccountID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [DF_DepartmentChargeCodeStatisticMapping_Weight] DEFAULT ((0)) FOR [Weight]; GO
ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [DF_DepartmentChargeCodeStatisticMapping_DepartmentRollupLevelMemberColumnName] DEFAULT ('DepartmentID') FOR [DepartmentRollupLevelMemberColumnName]; GO
ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [DF_DepartmentChargeCodeStatisticMapping_IsReviewed] DEFAULT ((0)) FOR [IsReviewed]; GO

---------------------------------------------

---------------------------------------------
-- fw.DepartmentChargeCodeStatisticMappingCache ------------------
---------------------------------------------
CREATE TABLE [fw].[DepartmentChargeCodeStatisticMappingCache] (
    [FiscalYearID] smallint NOT NULL,
    [DepartmentID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [PatientTypeRollupID] int NOT NULL,
    [AccountID] int NOT NULL,
    [Weight] decimal NOT NULL
);

CREATE NONCLUSTERED INDEX [NCNU_DepartmentFisclaYearAccount] ON [fw].[DepartmentChargeCodeStatisticMappingCache] ([DepartmentID], [FiscalYearID], [AccountID]) INCLUDE ([ChargeCodeID], [PatientTypeRollupID], [Weight]);
GO

---------------------------------------------

---------------------------------------------
-- fw.DepartmentChargeCodeStatisticMappingStaffingCache ------------------
---------------------------------------------
CREATE TABLE [fw].[DepartmentChargeCodeStatisticMappingStaffingCache] (
    [RowID] bigint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [DepartmentID] int NOT NULL,
    [OriginalDepartmentID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [PatientTypeRollupID] int NOT NULL,
    [AccountID] int NOT NULL,
    [Weight] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE NONCLUSTERED INDEX [CORE_OriginalDepartmentID_FiscalYearID_ChargeCodeID_PatientTypeRollupID] ON [fw].[DepartmentChargeCodeStatisticMappingStaffingCache] ([OriginalDepartmentID], [FiscalYearID], [ChargeCodeID], [PatientTypeRollupID]);
GO

---------------------------------------------

---------------------------------------------
-- fw.DepartmentRollup ------------------
---------------------------------------------
CREATE TABLE [fw].[DepartmentRollup] (
    [DepartmentRollupLevelID] tinyint NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    PRIMARY KEY ([DepartmentRollupLevelID])
);
GO
ALTER TABLE [fw].[DepartmentRollup] ADD CONSTRAINT [CHK_FW_DepartmentRollup_DepartmentRollupLevelID] CHECK ([DepartmentRollupLevelID]>=(1) AND [DepartmentRollupLevelID]<=(9)); GO

---------------------------------------------

---------------------------------------------
-- fw.DimAccount ------------------
---------------------------------------------
CREATE TABLE [fw].[DimAccount] (
    [AccountID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [AccountCode] nvarchar(40) NULL,
    [Description] nvarchar(80) NOT NULL,
    [GLRollup] nvarchar(100) NOT NULL,
    [IsInverted] bit NOT NULL,
    [Inversion] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [PatientClass] nvarchar(100) NOT NULL,
    [CAPIsDefined] bit NOT NULL,
    [DSSIsDefined] bit NOT NULL,
    [DSSCostComponent] nvarchar(50) NOT NULL,
    [DSSStatisticDriver] nvarchar(50) NOT NULL,
    [DSSAccountRollup1ID] int NOT NULL,
    [DSSAccountRollup1Name] nvarchar(100) NOT NULL,
    [DSSAccountRollup1Category] nvarchar(100) NOT NULL,
    [DSSAccountRollup2ID] int NOT NULL,
    [DSSAccountRollup2Name] nvarchar(100) NOT NULL,
    [DSSAccountRollup3ID] int NOT NULL,
    [DSSAccountRollup3Name] nvarchar(100) NOT NULL,
    [MRIsDefined] bit NOT NULL,
    [FlexStatistic] nvarchar(100) NOT NULL,
    [FlexValue] money NOT NULL,
    [FlexBucketGUID] uniqueidentifier NOT NULL,
    [OBIsDefined] bit NOT NULL,
    [IsStat] bit NOT NULL,
    [IsGlobal] bit NOT NULL,
    [IsExpense] bit NOT NULL,
    [Variability] money NOT NULL,
    [OBDollarsFinancialReportingID] int NOT NULL,
    [OBDollarsFinancialReporting] varchar(200) NOT NULL,
    [OBDollarsFinancialReportingCategory] nvarchar(100) NOT NULL,
    [OBDollarsFinancialReportingLineName] nvarchar(100) NOT NULL,
    [OBDollarsFinancialReportingSortOrder] int NOT NULL,
    [OBUnitsFinancialReportingID] int NOT NULL,
    [OBUnitsFinancialReporting] varchar(200) NOT NULL,
    [OBUnitsFinancialReportingCategory] nvarchar(100) NOT NULL,
    [OBUnitsFinancialReportingLineName] nvarchar(100) NOT NULL,
    [OBUnitsFinancialReportingSortOrder] int NOT NULL,
    [OBAccountPHID] int NOT NULL,
    [OBModelSectionName] nvarchar(100) NOT NULL,
    [OBStatModelSectionID] int NOT NULL,
    [OBStatModelSectionName] nvarchar(100) NOT NULL,
    [OBStatUnitTypeID] tinyint NOT NULL,
    [OBUnitType] nvarchar(100) NOT NULL,
    [OBPayorID] int NOT NULL,
    [OBPayor] nvarchar(100) NOT NULL,
    [OBPayorGroupID] int NOT NULL,
    [OBPayorGroup] nvarchar(100) NOT NULL,
    [SPIsDefined] bit NOT NULL,
    [PatientTypeRollupID] tinyint NOT NULL,
    [PatientTypeRollupName] nvarchar(200) NOT NULL,
    [SPAccountRollupID] int NOT NULL,
    [SPAccountRollupName] nvarchar(200) NOT NULL,
    [SPStatAccountRollup] int NOT NULL,
    [SPStatAccountRollupName] nvarchar(100) NOT NULL,
    [SPAccountRollupCategory] nvarchar(100) NOT NULL,
    [SPPayorGroupID] int NOT NULL,
    [SPPayorGroupName] nvarchar(200) NOT NULL,
    [SPPhysicianGroupID] int NOT NULL,
    [SPPhysicianGroupName] nvarchar(200) NOT NULL,
    [SPJobCodeGroupID] int NOT NULL,
    [SPJobCodeGroupName] nvarchar(200) NOT NULL,
    [SPCapitalRollupID] int NOT NULL,
    [SPCapitalRollupName] nvarchar(200) NOT NULL,
    [SPDebtIssuanceID] int NOT NULL,
    [SPDebtIssuanceName] nvarchar(200) NOT NULL,
    [SPIsPhysicianOverride] bit NOT NULL,
    [PatientTypeID] int NOT NULL,
    [OBStaffing] nvarchar(100) NOT NULL,
    [TransactionID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [DSSAccountRollup4ID] int NOT NULL,
    [DSSAccountRollup4] varchar(100) NOT NULL,
    [DSSAccountRollup4Name] varchar(200) NOT NULL,
    [Name] nvarchar(123) NOT NULL,
    [DSSAccountRollup2Category] nvarchar(100) NOT NULL,
    [DSSAccountRollup3Category] nvarchar(100) NOT NULL,
    [DSSAccountRollup4Category] varchar(200) NOT NULL,
    [FWIsDefined] bit NOT NULL,
    [AccountCodeRaw] nvarchar(100) NOT NULL,
    [GMAccountRollup1] nvarchar(200) NOT NULL,
    [GMAccountRollup2] nvarchar(200) NOT NULL,
    [GMAccountRollup3] nvarchar(200) NOT NULL,
    [GMAccountRollup4] nvarchar(200) NOT NULL,
    [GMAccountRollup5] nvarchar(200) NOT NULL,
    [GMAccountRollup6] nvarchar(200) NOT NULL,
    [DSSAccountRollup5ID] int NOT NULL,
    [DSSAccountRollup5Name] nvarchar(100) NOT NULL,
    [DSSAccountRollup6ID] int NOT NULL,
    [DSSAccountRollup6Name] nvarchar(100) NOT NULL,
    [DSSAccountRollup7ID] int NOT NULL,
    [DSSAccountRollup7Name] nvarchar(100) NOT NULL,
    [SPHAccountRollupID] int NOT NULL,
    [SPHAccountRollupName] varchar(606) NOT NULL,
    [SPHAccountRollupConfidenceScore] float NOT NULL,
    [SPHVariability] decimal NOT NULL,
    [SPHCostComponent] nvarchar(400) NOT NULL,
    [SPHCostComponentRollup] nvarchar(400) NOT NULL,
    [GMAccountRollup7] nvarchar(200) NOT NULL,
    [IsSPHCostModel] bit NOT NULL,
    [SPHLineItem] nvarchar(200) NOT NULL,
    [SPHStatement] nvarchar(200) NOT NULL,
    [SPHCategory] nvarchar(200) NOT NULL,
    [SPHSection] nvarchar(200) NOT NULL,
    [SPHAccountRollupIsValidated] bit NOT NULL,
    [IsCBP] bit NOT NULL,
    PRIMARY KEY ([AccountID])
);

CREATE NONCLUSTERED INDEX [IX_AccountID_OBRollupIDs] ON [fw].[DimAccount] ([AccountID], [OBUnitsFinancialReportingID], [OBDollarsFinancialReportingID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Name] ON [fw].[DimAccount] ([Name]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_AccountCode] ON [fw].[DimAccount] ([AccountCode]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_MemberGUID] ON [fw].[DimAccount] ([MemberGUID]);
CREATE NONCLUSTERED INDEX [IX_AccountID] ON [fw].[DimAccount] ([AccountID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_AccountCode] ON [fw].[DimAccount] ([AccountCode]) INCLUDE ([AccountID]);
GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [FK_DimAccount_DimPatientType] FOREIGN KEY ([PatientTypeID]) REFERENCES [fw].[DimPatientType] ([PatientTypeID]); GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBIsD__3981D270] DEFAULT ((0)) FOR [OBIsDefined]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__IsSta__3ECB39DB] DEFAULT ((0)) FOR [IsStat]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_IsGlobal] DEFAULT ((0)) FOR [IsGlobal]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__IsExp__4B7B9146] DEFAULT ((0)) FOR [IsExpense]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__FWIsD__053F7F3C] DEFAULT ((0)) FOR [FWIsDefined]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_Variability] DEFAULT ((1)) FOR [Variability]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBDol__6DE91709] DEFAULT ((0)) FOR [OBDollarsFinancialReportingID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBDol__77728143] DEFAULT ('') FOR [OBDollarsFinancialReporting]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPHAc__07AD771D] DEFAULT ((0)) FOR [SPHAccountRollupIsValidated]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SDSAc__08489CE8] DEFAULT ((0)) FOR [SPHAccountRollupID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBDol__7866A57C] DEFAULT ('') FOR [OBDollarsFinancialReportingCategory]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SDSAc__093CC121] DEFAULT ('') FOR [SPHAccountRollupName]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBDol__7A4EEDEE] DEFAULT ('') FOR [OBDollarsFinancialReportingLineName]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBDol__2AF88001] DEFAULT ((0)) FOR [OBDollarsFinancialReportingSortOrder]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__Confi__0B250993] DEFAULT ((0)) FOR [SPHAccountRollupConfidenceScore]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBUni__6EDD3B42] DEFAULT ((0)) FOR [OBUnitsFinancialReportingID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBUni__7B431227] DEFAULT ('') FOR [OBUnitsFinancialReporting]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBUni__7C373660] DEFAULT ('') FOR [OBUnitsFinancialReportingCategory]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBUni__7E1F7ED2] DEFAULT ('') FOR [OBUnitsFinancialReportingLineName]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBUni__2BECA43A] DEFAULT ((0)) FOR [OBUnitsFinancialReportingSortOrder]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBAcc__1178418C] DEFAULT ((0)) FOR [OBAccountPHID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBMod__6C52D8C0] DEFAULT ('') FOR [OBModelSectionName]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBSta__20484969] DEFAULT ((0)) FOR [OBStatModelSectionID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBSta__213C6DA2] DEFAULT ('') FOR [OBStatModelSectionName]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBSta__6A33241F] DEFAULT ((0)) FOR [OBStatUnitTypeID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_OBUnitType] DEFAULT ('') FOR [OBUnitType]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBPay__7CBCB405] DEFAULT ((0)) FOR [OBPayorID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_OBPayor] DEFAULT ('') FOR [OBPayor]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBPay__05F1E3DB] DEFAULT ((0)) FOR [OBPayorGroupID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBPay__06E60814] DEFAULT ('') FOR [OBPayorGroup]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPIsD__3A75F6A9] DEFAULT ((0)) FOR [SPIsDefined]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__Patie__6433C725] DEFAULT ((0)) FOR [PatientTypeRollupID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__Patie__7EB84298] DEFAULT ('') FOR [PatientTypeRollupName]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_FWDIMACCOUNTSPACCOUNTROLLUPID] DEFAULT ((0)) FOR [SPAccountRollupID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPAcc__7FAC66D1] DEFAULT ('') FOR [SPAccountRollupName]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPSta__171085C4] DEFAULT ((0)) FOR [SPStatAccountRollup]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPSta__1804A9FD] DEFAULT ('') FOR [SPStatAccountRollupName]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPAcc__568D8309] DEFAULT ('') FOR [SPAccountRollupCategory]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_FWDIMACCOUNTSPPAYORGROUPID] DEFAULT ((0)) FOR [SPPayorGroupID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPPay__00A08B0A] DEFAULT ('') FOR [SPPayorGroupName]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPPhy__431DB774] DEFAULT ((0)) FOR [SPPhysicianGroupID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPPhy__0194AF43] DEFAULT ('') FOR [SPPhysicianGroupName]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_FWDIMACCOUNTSPJOBCODEGROUPID] DEFAULT ((0)) FOR [SPJobCodeGroupID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPJob__0288D37C] DEFAULT ('') FOR [SPJobCodeGroupName]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__26C5CC2F] DEFAULT ((0)) FOR [DSSAccountRollup4ID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_FWDIMACCOUNTSPCAPITALROLLUPID] DEFAULT ((0)) FOR [SPCapitalRollupID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__27B9F068] DEFAULT ('') FOR [DSSAccountRollup4]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPCap__037CF7B5] DEFAULT ('') FOR [SPCapitalRollupName]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__Histo__1AB06CF4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__28AE14A1] DEFAULT ('') FOR [DSSAccountRollup4Name]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_FWDIMACCOUNTSPDEBTISSUANCEID] DEFAULT ((0)) FOR [SPDebtIssuanceID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPDeb__04711BEE] DEFAULT ('') FOR [SPDebtIssuanceName]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPIsP__6985EB4D] DEFAULT ((0)) FOR [SPIsPhysicianOverride]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_PatientTypeID] DEFAULT ((0)) FOR [PatientTypeID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_OBAccountRollup] DEFAULT ('') FOR [OBStaffing]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__FW_DimAccount_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__337C4859] DEFAULT ((0)) FOR [DSSAccountRollup5ID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_FlexMetricGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FlexBucketGUID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__34706C92] DEFAULT ('') FOR [DSSAccountRollup5Name]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__356490CB] DEFAULT ((0)) FOR [DSSAccountRollup6ID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__3658B504] DEFAULT ('') FOR [DSSAccountRollup6Name]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPHVa__36E526EE] DEFAULT ((0)) FOR [SPHVariability]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__3AE6977F] DEFAULT ('') FOR [DSSAccountRollup2Category]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__3BDABBB8] DEFAULT ('') FOR [DSSAccountRollup3Category]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__3CCEDFF1] DEFAULT ('') FOR [DSSAccountRollup4Category]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__IsSPH__490F8F78] DEFAULT ((1)) FOR [IsSPHCostModel]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPHCo__55F3BDF3] DEFAULT ('') FOR [SPHCostComponent]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPHCo__56E7E22C] DEFAULT ('') FOR [SPHCostComponentRollup]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__Accou__5B694101] DEFAULT ('') FOR [AccountCodeRaw]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPHLi__68FE0774] DEFAULT ('') FOR [SPHLineItem]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPHSt__69F22BAD] DEFAULT ('') FOR [SPHStatement]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPHCa__6AE64FE6] DEFAULT ('') FOR [SPHCategory]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPHSe__6BDA741F] DEFAULT ('') FOR [SPHSection]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__Membe__19BC48BB] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__GMAcc__6CDEB11D] DEFAULT ('') FOR [GMAccountRollup1]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_Code] DEFAULT ('') FOR [AccountCode]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__GMAcc__6DD2D556] DEFAULT ('') FOR [GMAccountRollup2]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_Description] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__GMAcc__6EC6F98F] DEFAULT ('') FOR [GMAccountRollup3]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__GLRol__7BA49B88] DEFAULT ('') FOR [GLRollup]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__GMAcc__6FBB1DC8] DEFAULT ('') FOR [GMAccountRollup4]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__GMAcc__6FF38718] DEFAULT ('') FOR [GMAccountRollup7]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_IsInverted_1] DEFAULT ((0)) FOR [IsInverted]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__GMAcc__70AF4201] DEFAULT ('') FOR [GMAccountRollup5]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__Patie__2765843A] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__GMAcc__71A3663A] DEFAULT ('') FOR [GMAccountRollup6]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__Patie__2859A873] DEFAULT ('') FOR [PatientClass]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__72F7AEF0] DEFAULT ((0)) FOR [DSSAccountRollup7ID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__CAPIs__36A565C5] DEFAULT ((0)) FOR [CAPIsDefined]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__73EBD329] DEFAULT ('') FOR [DSSAccountRollup7Name]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSIs__379989FE] DEFAULT ((0)) FOR [DSSIsDefined]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSCo__64355DD3] DEFAULT ('') FOR [DSSCostComponent]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSSt__1EBE2B32] DEFAULT ('') FOR [DSSStatisticDriver]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__07C9AFF4] DEFAULT ((0)) FOR [DSSAccountRollup1ID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__0AA61C9F] DEFAULT ('') FOR [DSSAccountRollup1Name]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__08BDD42D] DEFAULT ('') FOR [DSSAccountRollup1Category]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__09B1F866] DEFAULT ((0)) FOR [DSSAccountRollup2ID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__0B9A40D8] DEFAULT ('') FOR [DSSAccountRollup2Name]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__0D82894A] DEFAULT ((0)) FOR [DSSAccountRollup3ID]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__0C8E6511] DEFAULT ('') FOR [DSSAccountRollup3Name]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__MRIsD__388DAE37] DEFAULT ((0)) FOR [MRIsDefined]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__IsCBP__7E266EE8] DEFAULT ((0)) FOR [IsCBP]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_FlexStatistic] DEFAULT ('') FOR [FlexStatistic]; GO
ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__FlexV__5CCDD875] DEFAULT ((0)) FOR [FlexValue]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimAgeCohort ------------------
---------------------------------------------
CREATE TABLE [fw].[DimAgeCohort] (
    [AgeCohortID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Code] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    [TimeMin] int NOT NULL,
    [TimeMax] int NOT NULL,
    [TimeMinUnit] nvarchar(100) NOT NULL,
    [TimeMaxUnit] nvarchar(100) NOT NULL,
    PRIMARY KEY ([AgeCohortID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimAgeCohort] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimAgeCohort] ([Name]);
GO
ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoh__Histo__6CAF9E17] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoh__TimeM__12BB0C99] DEFAULT ((0)) FOR [TimeMin]; GO
ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoh__TimeM__13AF30D2] DEFAULT ((0)) FOR [TimeMax]; GO
ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoh__TimeM__177FC1B6] DEFAULT ('') FOR [TimeMinUnit]; GO
ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoh__TimeM__1873E5EF] DEFAULT ('') FOR [TimeMaxUnit]; GO
ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoho__Name__6AC755A5] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoh__Membe__6BBB79DE] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoh__Trans__6DA3C250] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoho__Code__6E97E689] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoh__SortO__6F8C0AC2] DEFAULT ((0)) FOR [SortOrder]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimAssumption ------------------
---------------------------------------------
CREATE TABLE [fw].[DimAssumption] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [AssumptionID] int NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Category] nvarchar(100) NOT NULL,
    [SubCategory] nvarchar(100) NOT NULL,
    [Version] timestamp NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [DisplayFormat] nvarchar(200) NOT NULL,
    [SPIsPastingValues] bit NOT NULL,
    [SPIsProtectingRollingValues] bit NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([AssumptionID])
);

CREATE UNIQUE NONCLUSTERED INDEX [UQ__DimAssum__A67B3853390AD6E2] ON [fw].[DimAssumption] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__DimAssump__Histo__3EC3B038] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__DimAssump__SPIsP__0D3215CF] DEFAULT ((0)) FOR [SPIsProtectingRollingValues]; GO
ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__DimAssump__SPIsP__0FBE0EFF] DEFAULT ((0)) FOR [SPIsPastingValues]; GO
ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__DimAssump__Membe__3AF31F54] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__DimAssumpt__Name__3BE7438D] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__DimAssump__Categ__3CDB67C6] DEFAULT ('') FOR [Category]; GO
ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__DimAssump__SubCa__3DCF8BFF] DEFAULT ('') FOR [SubCategory]; GO
ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__FW_DimAssumption_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__DimAssump__Displ__7895EE7B] DEFAULT ('') FOR [DisplayFormat]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimCareSetting ------------------
---------------------------------------------
CREATE TABLE [fw].[DimCareSetting] (
    [CareSettingID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [Code] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [IsActive] bit NOT NULL,
    PRIMARY KEY ([CareSettingID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimCareSetting] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimCareSetting] ([Name]);
GO
ALTER TABLE [fw].[DimCareSetting] ADD CONSTRAINT [DF__DimCareSet__Name__2EBC8D3F] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimCareSetting] ADD CONSTRAINT [DF__DimCareSet__Code__2FB0B178] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimCareSetting] ADD CONSTRAINT [DF__DimCareSe__SortO__30A4D5B1] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimCareSetting] ADD CONSTRAINT [DF__DimCareSe__Membe__3198F9EA] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimCareSetting] ADD CONSTRAINT [DF__DimCareSe__Trans__3381425C] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimCareSetting] ADD CONSTRAINT [DF__DimCareSe__Histo__328D1E23] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimCareSetting] ADD CONSTRAINT [DF__DimCareSe__IsAct__77A48FDB] DEFAULT ((1)) FOR [IsActive]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimCareSettingPH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimCareSettingPH] (
    [CareSettingPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([CareSettingPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimCareSettingPH] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimCareSettingPH] ADD CONSTRAINT [DF__DimCareSet__Name__3E5F8ED9] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimCareSettingPH] ADD CONSTRAINT [DF__DimCareSe__Membe__3F53B312] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimCareSettingPH] ADD CONSTRAINT [DF__DimCareSe__Trans__413BFB84] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimCareSettingPH] ADD CONSTRAINT [DF__DimCareSe__Histo__4047D74B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimChargeCode ------------------
---------------------------------------------
CREATE TABLE [fw].[DimChargeCode] (
    [ChargeCodeID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [ChargeCode] nvarchar(100) NOT NULL,
    [Description] nvarchar(400) NOT NULL,
    [IsDefined] bit NOT NULL,
    [OBIsDefined] bit NOT NULL,
    [IsRVU] bit NOT NULL,
    [IsStatDriver] bit NOT NULL,
    [ChargeIncrease] decimal NOT NULL,
    [Category] nvarchar(200) NOT NULL,
    [RVUWeight] decimal NOT NULL,
    [StatType] nvarchar(50) NOT NULL,
    [PatientTypeID] int NOT NULL,
    [DSSIsDefined] bit NOT NULL,
    [DayTypeID] int NOT NULL,
    [DayType2ID] int NOT NULL,
    [DayType3ID] int NOT NULL,
    [UBRevenueCodeID] int NOT NULL,
    [CPTID] int NOT NULL,
    [IsActivityCost] bit NOT NULL,
    [TransactionID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [CostDriver] nvarchar(100) NOT NULL,
    [Rollup] nvarchar(200) NOT NULL,
    [IsPatientSpecific] bit NOT NULL,
    [FWIsDefined] bit NOT NULL,
    [DayType] nvarchar(443) NOT NULL,
    [DayType2] nvarchar(443) NOT NULL,
    [DayType3] nvarchar(443) NOT NULL,
    [TimeStampWeight] decimal NOT NULL,
    [IsTimeStamp] bit NOT NULL,
    [TimeStampPrecedent] int NOT NULL,
    [Name] nvarchar(503) NOT NULL,
    [IsSPHSupplyCosting] bit NOT NULL,
    [IsSPHTDCosting] bit NOT NULL,
    [SPHChargeCodePrefix] nvarchar(100) NOT NULL,
    PRIMARY KEY ([ChargeCodeID])
);

CREATE UNIQUE NONCLUSTERED INDEX [NCU_ChargeCode] ON [fw].[DimChargeCode] ([ChargeCode]) INCLUDE ([ChargeCodeID]);
CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimChargeCode] ([MemberGUID]);
CREATE NONCLUSTERED INDEX [NCNU_DateTypeID] ON [fw].[DimChargeCode] ([DayTypeID]);
CREATE NONCLUSTERED INDEX [NUNC_ChargeCodeID_Name] ON [fw].[DimChargeCode] ([ChargeCodeID]) INCLUDE ([Name]);
CREATE NONCLUSTERED INDEX [NC_IDX_ChargeCode_IsPatntSpecifc] ON [fw].[DimChargeCode] ([IsPatientSpecific]) INCLUDE ([ChargeCodeID]);
GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF_DimChargeCode_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF_DimChargeCode_Code] DEFAULT ('') FOR [ChargeCode]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF_DimChargeCode_IsDefined] DEFAULT ((1)) FOR [IsDefined]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__FWIsD__0727C7AE] DEFAULT ((0)) FOR [FWIsDefined]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__OBIsD__520432CE] DEFAULT ((0)) FOR [OBIsDefined]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__IsRVU__42B8672A] DEFAULT ((0)) FOR [IsRVU]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__IsSta__7A0C62FD] DEFAULT ((1)) FOR [IsStatDriver]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__Charg__7BF4AB6F] DEFAULT ((0)) FOR [ChargeIncrease]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__Categ__78241A8B] DEFAULT ('') FOR [Category]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__RVUWe__7ED1181A] DEFAULT ((1)) FOR [RVUWeight]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF_IsPatient_Specific] DEFAULT ((1)) FOR [IsPatientSpecific]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__StatT__43AC8B63] DEFAULT ('') FOR [StatType]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__Patie__745389A7] DEFAULT ((0)) FOR [PatientTypeID]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__DSSIs__52F85707] DEFAULT ((0)) FOR [DSSIsDefined]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__DayTy__19CCF6DE] DEFAULT ((0)) FOR [DayTypeID]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__DayTy__647D465B] DEFAULT ((0)) FOR [DayType2ID]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__DayTy__65716A94] DEFAULT ((0)) FOR [DayType3ID]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__UBRev__6B40E931] DEFAULT ((0)) FOR [UBRevenueCodeID]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__CPTID__6C350D6A] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__IsAct__481D061C] DEFAULT ((0)) FOR [IsActivityCost]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__FW_DimChargeCode_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__Descr__50D54340] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__IsSPH__36460870] DEFAULT ((0)) FOR [IsSPHSupplyCosting]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF_DimChargeCode_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__IsSPH__373A2CA9] DEFAULT ((0)) FOR [IsSPHTDCosting]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__SPHCh__382E50E2] DEFAULT ('') FOR [SPHChargeCodePrefix]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__TimeS__38FC1ED2] DEFAULT ((0)) FOR [TimeStampWeight]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__TimeS__39F0430B] DEFAULT ((0)) FOR [IsTimeStamp]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__TimeS__3AE46744] DEFAULT ((0)) FOR [TimeStampPrecedent]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF_DimChargeCode_Rollup] DEFAULT ('') FOR [Rollup]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__DayTy__6177EB69] DEFAULT ('') FOR [DayType]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__DayTy__626C0FA2] DEFAULT ('') FOR [DayType2]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__DayTy__636033DB] DEFAULT ('') FOR [DayType3]; GO
ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__CostD__6D4D57B1] DEFAULT ('') FOR [CostDriver]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimChargeCodePH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimChargeCodePH] (
    [ChargeCodePHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([ChargeCodePHID])
);
GO
ALTER TABLE [fw].[DimChargeCodePH] ADD CONSTRAINT [DF__DimChargeCodePH_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimChargeCodePH] ADD CONSTRAINT [DF__DimChargeCodePH_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimChargeCodePH] ADD CONSTRAINT [DF__DimChargeCodePH_TransactionID] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimChargeCodePH] ADD CONSTRAINT [DF__DimChargeCodePH_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimColumnHider ------------------
---------------------------------------------
CREATE TABLE [fw].[DimColumnHider] (
    [ColumnHiderID] tinyint NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([ColumnHiderID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_DimColumnHider] ON [fw].[DimColumnHider] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimColumnHider] ADD CONSTRAINT [DF_DimColumnHider_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimColumnHider] ADD CONSTRAINT [DF_DimColumnHider_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimColumnHider] ADD CONSTRAINT [DF__FW_DimColumnHider_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimColumnHider] ADD CONSTRAINT [DF__fw_DimColumnHider_Name] DEFAULT ('') FOR [Name]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimCompAnDepartment ------------------
---------------------------------------------
CREATE TABLE [fw].[DimCompAnDepartment] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [CompAnDepartmentID] int NOT NULL,
    [CompAnDepartmentCode] nvarchar(10) NOT NULL,
    [Description] nvarchar(200) NOT NULL,
    [DescriptionLong] nvarchar(400) NOT NULL,
    [CompAnDepartmentRollup1] nvarchar(200) NOT NULL,
    [CompAnDepartmentRollup2] nvarchar(200) NOT NULL,
    [CompAnDepartmentRollup3] nvarchar(200) NOT NULL,
    [CompAnDepartmentRollup4] nvarchar(200) NOT NULL,
    [CompAnPrimaryStat] nvarchar(200) NOT NULL,
    [SPHDepartmentRollupID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([CompAnDepartmentID])
);

CREATE UNIQUE NONCLUSTERED INDEX [NCU_CompAnDepartmentCode] ON [fw].[DimCompAnDepartment] ([CompAnDepartmentCode]) INCLUDE ([CompAnDepartmentID]);
GO
ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__Histo__62E79D70] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__CompA__64CFE5E2] DEFAULT ('') FOR [CompAnDepartmentCode]; GO
ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__Descr__65C40A1B] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__Descr__66B82E54] DEFAULT ('') FOR [DescriptionLong]; GO
ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__CompA__67AC528D] DEFAULT ('') FOR [CompAnDepartmentRollup1]; GO
ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__CompA__68A076C6] DEFAULT ('') FOR [CompAnDepartmentRollup2]; GO
ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__CompA__69949AFF] DEFAULT ('') FOR [CompAnDepartmentRollup3]; GO
ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__CompA__6A88BF38] DEFAULT ('') FOR [CompAnDepartmentRollup4]; GO
ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__CompA__6B7CE371] DEFAULT ('') FOR [CompAnPrimaryStat]; GO
ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__SPHDe__6C7107AA] DEFAULT ((0)) FOR [SPHDepartmentRollupID]; GO
ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__Membe__6D652BE3] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__Trans__6E59501C] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimCompAnPeerGroup ------------------
---------------------------------------------
CREATE TABLE [fw].[DimCompAnPeerGroup] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [CompAnPeerGroupID] int NOT NULL,
    [Name] nvarchar(300) NOT NULL,
    [Description] nvarchar(500) NOT NULL,
    [CompAnPeerGroupCode] nvarchar(10) NOT NULL,
    [TransactionID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([CompAnPeerGroupID])
);

CREATE UNIQUE NONCLUSTERED INDEX [NCU_CompAnPeerGroupCode] ON [fw].[DimCompAnPeerGroup] ([CompAnPeerGroupCode]) INCLUDE ([CompAnPeerGroupID]);
GO
ALTER TABLE [fw].[DimCompAnPeerGroup] ADD CONSTRAINT [DF__DimCompAn__Histo__3793F66E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimCompAnPeerGroup] ADD CONSTRAINT [DF__DimCompAnP__Name__397C3EE0] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimCompAnPeerGroup] ADD CONSTRAINT [DF__DimCompAn__Descr__3A706319] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimCompAnPeerGroup] ADD CONSTRAINT [DF__DimCompAn__CompA__3B648752] DEFAULT ('') FOR [CompAnPeerGroupCode]; GO
ALTER TABLE [fw].[DimCompAnPeerGroup] ADD CONSTRAINT [DF__DimCompAn__Trans__3C58AB8B] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimCompAnPeerGroup] ADD CONSTRAINT [DF__DimCompAn__Membe__3D4CCFC4] DEFAULT (newid()) FOR [MemberGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimConsolidatedFinancialReporting ------------------
---------------------------------------------
CREATE TABLE [fw].[DimConsolidatedFinancialReporting] (
    [ConsolidatedFinancialReportingID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Statement] nvarchar(100) NOT NULL,
    [Section] nvarchar(100) NOT NULL,
    [LineName] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    [Name] nvarchar(306) NOT NULL,
    PRIMARY KEY ([ConsolidatedFinancialReportingID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimConsolidatedFinancialReporting] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimConsolidatedFinancialReporting] ADD CONSTRAINT [DF__DimConsol__Membe__24E2AF8A] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimConsolidatedFinancialReporting] ADD CONSTRAINT [DF__DimConsol__State__26CAF7FC] DEFAULT ('') FOR [Statement]; GO
ALTER TABLE [fw].[DimConsolidatedFinancialReporting] ADD CONSTRAINT [DF__DimConsol__Secti__27BF1C35] DEFAULT ('') FOR [Section]; GO
ALTER TABLE [fw].[DimConsolidatedFinancialReporting] ADD CONSTRAINT [DF__DimConsol__LineN__28B3406E] DEFAULT ('') FOR [LineName]; GO
ALTER TABLE [fw].[DimConsolidatedFinancialReporting] ADD CONSTRAINT [DF__DimConsol__SortO__29A764A7] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimConsolidatedFinancialReporting] ADD CONSTRAINT [DF__DimConsol__Histo__25D6D3C3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimDataType ------------------
---------------------------------------------
CREATE TABLE [fw].[DimDataType] (
    [DataTypeID] tinyint NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [GlobalID] varchar(32) NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([DataTypeID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDataType] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimDataType] ADD CONSTRAINT [DF__DimDataTyp__Name__363E1B39] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimDataType] ADD CONSTRAINT [DF__DimDataTy__Globa__3D40E9DA] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [fw].[DimDataType] ADD CONSTRAINT [DF__DimDataTy__Membe__37323F72] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimDataType] ADD CONSTRAINT [DF__DimDataTy__Histo__382663AB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimDataType] ADD CONSTRAINT [DF__FW_DimDataType_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimDate ------------------
---------------------------------------------
CREATE TABLE [fw].[DimDate] (
    [DateID] int NOT NULL,
    [DayNumberOfWeek] tinyint NOT NULL,
    [DayNameOfWeek] nvarchar(10) NOT NULL,
    [DayNumberOfMonth] tinyint NOT NULL,
    [DayNumberOfYear] smallint NOT NULL,
    [WeekNumberOfYear] tinyint NOT NULL,
    [IsWeekDay] bit NOT NULL,
    [CalendarQuarter] tinyint NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [CalendarDateTime] smalldatetime NOT NULL,
    [CalendarYear] smallint NOT NULL,
    [CalendarMonth] tinyint NOT NULL,
    [CalendarMonthName] varchar(100) NOT NULL,
    [FiscalYear] smallint NOT NULL,
    [FiscalYearName] varchar(6) NOT NULL,
    [FiscalMonth] tinyint NOT NULL,
    [TransactionID] int NOT NULL,
    [FiscalQuarter] varchar(15) NOT NULL,
    [YearMonth] nvarchar(25) NOT NULL,
    [MonthYear] nvarchar(100) NOT NULL,
    [PremierMapping] varchar(8000) NULL,
    [DaysInMonth] int NOT NULL,
    PRIMARY KEY ([DateID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDate] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_CalendarDateTime] ON [fw].[DimDate] ([CalendarDateTime]);
GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__DaysInM__0105A55B] DEFAULT ((0)) FOR [DaysInMonth]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__FiscalQ__4E0FADA6] DEFAULT ('') FOR [FiscalQuarter]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__YearMon__11882458] DEFAULT ('') FOR [YearMonth]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__MonthYe__1CB7E171] DEFAULT ('Not Specified') FOR [MonthYear]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__FiscalM__1F65094C] DEFAULT ((0)) FOR [FiscalMonth]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__DayNumb__087F41EF] DEFAULT ((0)) FOR [DayNumberOfWeek]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__DayName__09736628] DEFAULT ((0)) FOR [DayNameOfWeek]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__DayNumb__0A678A61] DEFAULT ((0)) FOR [DayNumberOfMonth]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__DayNumb__0B5BAE9A] DEFAULT ((0)) FOR [DayNumberOfYear]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__WeekNum__0C4FD2D3] DEFAULT ((0)) FOR [WeekNumberOfYear]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__IsWeekD__0D43F70C] DEFAULT ((0)) FOR [IsWeekDay]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__Calenda__0E381B45] DEFAULT ((0)) FOR [CalendarQuarter]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__History__102063B7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF_CalendarDateTime] DEFAULT ('1900-01-01 0:00') FOR [CalendarDateTime]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__Calenda__7EC0CD8B] DEFAULT ((0)) FOR [CalendarYear]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__Calenda__7FB4F1C4] DEFAULT ((1)) FOR [CalendarMonth]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__Calenda__00A915FD] DEFAULT ('') FOR [CalendarMonthName]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__FiscalY__019D3A36] DEFAULT ((0)) FOR [FiscalYear]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__FW_DimDate_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF_FWDIMDATEMEMBERGUID] DEFAULT (newid()) FOR [MemberGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimDayType ------------------
---------------------------------------------
CREATE TABLE [fw].[DimDayType] (
    [DayTypeID] int NOT NULL,
    [DayTypeCode] nvarchar(40) NOT NULL,
    [Description] nvarchar(400) NOT NULL,
    [PrecedentOrder] int NOT NULL,
    [GlobalID] nvarchar(50) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Rollup] nvarchar(100) NOT NULL,
    [TransactionID] int NOT NULL,
    [Name] nvarchar(443) NOT NULL,
    PRIMARY KEY ([DayTypeID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDayType] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_DayTypeCode] ON [fw].[DimDayType] ([DayTypeCode]) INCLUDE ([DayTypeID]);
GO
ALTER TABLE [fw].[DimDayType] ADD CONSTRAINT [DF__DimDayTyp__DayTy__15FC65FA] DEFAULT ('') FOR [DayTypeCode]; GO
ALTER TABLE [fw].[DimDayType] ADD CONSTRAINT [DF__DimDayTyp__Prece__17E4AE6C] DEFAULT ((0)) FOR [PrecedentOrder]; GO
ALTER TABLE [fw].[DimDayType] ADD CONSTRAINT [DF__DimDayTyp__Globa__18D8D2A5] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [fw].[DimDayType] ADD CONSTRAINT [DF__DimDayTyp__Descr__16F08A33] DEFAULT ('Not Specified') FOR [Description]; GO
ALTER TABLE [fw].[DimDayType] ADD CONSTRAINT [DF__DimDayTyp__Membe__5AA69602] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimDayType] ADD CONSTRAINT [DF__DimDayTyp__Rollu__69D3CAF9] DEFAULT ('') FOR [Rollup]; GO
ALTER TABLE [fw].[DimDayType] ADD CONSTRAINT [DF__DimDayTyp__Histo__5B9ABA3B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimDayType] ADD CONSTRAINT [DF__FW_DimDayType_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimDayofStay ------------------
---------------------------------------------
CREATE TABLE [fw].[DimDayofStay] (
    [DayofStayID] int NOT NULL,
    [Name] nvarchar(50) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([DayofStayID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDayofStay] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimDayofStay] ADD CONSTRAINT [DF__DimDayofS__Histo__60C0F8B9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimDayofStay] ADD CONSTRAINT [DF__DimDayofSt__Name__5ED8B047] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimDayofStay] ADD CONSTRAINT [DF__DimDayofS__Membe__5FCCD480] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimDayofStay] ADD CONSTRAINT [DF__FW_DimDayofStay_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimDepartment ------------------
---------------------------------------------
CREATE TABLE [fw].[DimDepartment] (
    [DepartmentID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [DepartmentCode] nvarchar(100) NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [SystemID] smallint NOT NULL,
    [System] nvarchar(100) NOT NULL,
    [SystemSortOrder] int NOT NULL,
    [EntityID] int NOT NULL,
    [Entity] nvarchar(303) NULL,
    [EntitySortOrder] int NOT NULL,
    [EntityTypeOverride] smallint NOT NULL,
    [DepartmentRollup1ID] smallint NOT NULL,
    [DepartmentRollup1] nvarchar(200) NOT NULL,
    [DepartmentRollup1SortOrder] int NOT NULL,
    [DepartmentRollup2ID] smallint NOT NULL,
    [DepartmentRollup2] nvarchar(200) NOT NULL,
    [DepartmentRollup2SortOrder] int NOT NULL,
    [DepartmentRollup3ID] smallint NOT NULL,
    [DepartmentRollup3] nvarchar(200) NOT NULL,
    [DepartmentRollup3SortOrder] int NOT NULL,
    [DepartmentRollup4ID] int NOT NULL,
    [DepartmentRollup4] nvarchar(200) NOT NULL,
    [DepartmentRollup4SortOrder] int NOT NULL,
    [DepartmentRollup5ID] smallint NOT NULL,
    [DepartmentRollup5] nvarchar(200) NOT NULL,
    [DepartmentRollup5SortOrder] int NOT NULL,
    [DepartmentRollup6ID] smallint NOT NULL,
    [DepartmentRollup6] nvarchar(200) NOT NULL,
    [DepartmentRollup6SortOrder] int NOT NULL,
    [CareSettingID] int NOT NULL,
    [CareSetting] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    [IsDepartmentRollup] bit NOT NULL,
    [FunctionalAreaID] int NOT NULL,
    [FunctionalArea] nvarchar(100) NOT NULL,
    [ResearchDepartmentCategoryID] int NOT NULL,
    [ResearchDepartmentCategoryName] nvarchar(100) NOT NULL,
    [ResearchDepartmentCategorySortOrder] int NOT NULL,
    [AttributionTypeID] int NOT NULL,
    [AttributionType] nvarchar(200) NOT NULL,
    [CAPIsDefined] bit NOT NULL,
    [IsCAP] bit NOT NULL,
    [DSSIsDefined] bit NOT NULL,
    [IsDSS] bit NOT NULL,
    [DepartmentTypeOLD] nvarchar(100) NOT NULL,
    [DSSDeptGrouping] nvarchar(200) NOT NULL,
    [DSSDepartmentRollup1ID] int NOT NULL,
    [DSSDepartmentRollup1Name] nvarchar(100) NOT NULL,
    [DSSDepartmentRollup2ID] int NOT NULL,
    [DSSDepartmentRollup2Name] nvarchar(100) NOT NULL,
    [DSSDepartmentRollup3ID] int NOT NULL,
    [DSSDepartmentRollup3Name] nvarchar(100) NOT NULL,
    [IsOverhead] bit NOT NULL,
    [OBIsDefined] bit NOT NULL,
    [IsOB] bit NOT NULL,
    [IsMRPlan] bit NOT NULL,
    [IsActive] bit NOT NULL,
    [IsVariable] bit NOT NULL,
    [IsAccountFlexing] bit NOT NULL,
    [FlexingBucketGUID] uniqueidentifier NOT NULL,
    [OBGlobalStatisticsPlanID] int NOT NULL,
    [OBGlobalStatisticsPlan] nvarchar(1000) NOT NULL,
    [OBReimbursementPlanID] int NOT NULL,
    [OBReimbursementPlan] nvarchar(458) NOT NULL,
    [OBServiceLinePlanID] int NOT NULL,
    [OBServiceLinePlan] nvarchar(458) NOT NULL,
    [SPIsDefined] bit NOT NULL,
    [IsLRFP] bit NOT NULL,
    [RollingPlanID] int NOT NULL,
    [SPRollingForecastPlanName] nvarchar(200) NOT NULL,
    [OpsPlanID] int NOT NULL,
    [SPOperationsPlanName] nvarchar(200) NOT NULL,
    [BalPlanID] int NOT NULL,
    [SPBalanceSheetPlanName] nvarchar(200) NOT NULL,
    [PatientTypeRollup] tinyint NOT NULL,
    [PatientTypeRollupName] nvarchar(100) NOT NULL,
    [SPJobCodeGroup] int NOT NULL,
    [SPJobCodeGroupName] nvarchar(100) NOT NULL,
    [SPPhysicianGroup] int NOT NULL,
    [SPPhysicianGroupName] nvarchar(100) NOT NULL,
    [SPAccountRollup] int NOT NULL,
    [SPAccountRollupName] nvarchar(100) NOT NULL,
    [SPServiceLineForecastType] smallint NOT NULL,
    [ConsolidatedCode] nvarchar(100) NOT NULL,
    [IsConsolidated] bit NOT NULL,
    [TransactionID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [Name] nvarchar(203) NOT NULL,
    [SecureGroupID] int NOT NULL,
    [WorkWeekID] int NOT NULL,
    [CAPDefaultSalesTax] float NOT NULL,
    [EntityCode] nvarchar(100) NOT NULL,
    [FundID] int NOT NULL,
    [Fund] nvarchar(100) NOT NULL,
    [FundSortOrder] int NOT NULL,
    [ProjectID] int NOT NULL,
    [Project] nvarchar(100) NOT NULL,
    [ProjectSortOrder] int NOT NULL,
    [HomeDepartmentID] int NOT NULL,
    [HomeDepartment] nvarchar(100) NOT NULL,
    [HomeDepartmentSortOrder] int NOT NULL,
    [ProgramID] int NOT NULL,
    [Program] nvarchar(100) NOT NULL,
    [ProgramSortOrder] int NOT NULL,
    [PayCycleID] int NOT NULL,
    [FWIsDefined] bit NOT NULL,
    [DepartmentTypeID] int NOT NULL,
    [DepartmentType] nvarchar(200) NOT NULL,
    [DepartmentCodeRaw] nvarchar(100) NOT NULL,
    [IsPR] bit NOT NULL,
    [MRVicePresident] nvarchar(400) NOT NULL,
    [MRDirector] nvarchar(400) NOT NULL,
    [MRManager] nvarchar(400) NOT NULL,
    [IsMROrPR] int NOT NULL,
    [IsMRMetricTracking] bit NOT NULL,
    [IsHealthPlanAdmin] bit NOT NULL,
    [DepartmentRollup1Code] nvarchar(200) NOT NULL,
    [DepartmentRollup2Code] nvarchar(200) NOT NULL,
    [DepartmentRollup3Code] nvarchar(200) NOT NULL,
    [DepartmentRollup4Code] nvarchar(200) NOT NULL,
    [DepartmentRollup5Code] nvarchar(200) NOT NULL,
    [DepartmentRollup6Code] nvarchar(200) NOT NULL,
    [DSSDepartmentRollup4Name] nvarchar(100) NOT NULL,
    [DSSDepartmentRollup4ID] int NOT NULL,
    [DSSDepartmentRollup5ID] int NOT NULL,
    [DSSDepartmentRollup5Name] nvarchar(100) NOT NULL,
    [DSSDepartmentRollup6ID] int NOT NULL,
    [DSSDepartmentRollup6Name] nvarchar(200) NOT NULL,
    [DSSDepartmentRollup7ID] int NOT NULL,
    [DSSDepartmentRollup7Name] nvarchar(100) NOT NULL,
    [SPHDepartmentRollupID] int NOT NULL,
    [SPHDepartmentRollupName] nvarchar(200) NOT NULL,
    [SPHDepartmentRollupConfidenceScore] float NOT NULL,
    [SPHDepartmentTypeID] int NOT NULL,
    [SPHDepartmentType] nvarchar(200) NOT NULL,
    [IsClaimsCosting] bit NOT NULL,
    [SPHDepartmentRollupIsValidated] bit NOT NULL,
    [CompAnDepartmentID] int NOT NULL,
    [ProductivityPercentileID] int NOT NULL,
    [ProductivityPercentile] nvarchar(200) NOT NULL,
    [CompAnDepartment] nvarchar(200) NOT NULL,
    [SPHDepartmentID] int NOT NULL,
    [SPHDepartmentConfidenceScore] float NOT NULL,
    [SPHDepartmentIsValidated] bit NOT NULL,
    [SPHDepartmentName] nvarchar(200) NOT NULL,
    PRIMARY KEY ([DepartmentID])
);

CREATE NONCLUSTERED INDEX [IX_MemberGUID] ON [fw].[DimDepartment] ([MemberGUID]);
CREATE NONCLUSTERED INDEX [IX_Hierarchy] ON [fw].[DimDepartment] ([DepartmentID], [DepartmentRollup1ID], [DepartmentRollup2ID], [DepartmentRollup3ID], [DepartmentRollup4ID], [DepartmentRollup5ID], [DepartmentRollup6ID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_DepartmentCode] ON [fw].[DimDepartment] ([DepartmentCode]) INCLUDE ([DepartmentID]);
CREATE NONCLUSTERED INDEX [IX_DepartmentRollup1ID] ON [fw].[DimDepartment] ([DepartmentRollup1ID]);
CREATE NONCLUSTERED INDEX [IX_DepartmentRollup2ID] ON [fw].[DimDepartment] ([DepartmentRollup2ID]);
CREATE NONCLUSTERED INDEX [IX_DepartmentRollup3ID] ON [fw].[DimDepartment] ([DepartmentRollup3ID]);
CREATE NONCLUSTERED INDEX [IX_DepartmentRollup4ID] ON [fw].[DimDepartment] ([DepartmentRollup4ID]);
CREATE NONCLUSTERED INDEX [IX_DepartmentRollup5ID] ON [fw].[DimDepartment] ([DepartmentRollup5ID]);
CREATE NONCLUSTERED INDEX [IX_DepartmentRollup6ID] ON [fw].[DimDepartment] ([DepartmentRollup6ID]);
CREATE NONCLUSTERED INDEX [NCNU_EntityID] ON [fw].[DimDepartment] ([DepartmentID], [EntityID]);
CREATE NONCLUSTERED INDEX [NCNU_DimDepartment_IsMRorPR_DepartmentID] ON [fw].[DimDepartment] ([IsMROrPR], [DepartmentID]) INCLUDE ([Name]);
GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__CareS__459FF297] DEFAULT ('') FOR [CareSetting]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__PayCy__481E3507] DEFAULT ((0)) FOR [PayCycleID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__485769AE] DEFAULT ((0)) FOR [DSSDepartmentRollup4ID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Entit__485BCA24] DEFAULT ('') FOR [EntityCode]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SortO__71693472] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__494B8DE7] DEFAULT ((0)) FOR [DSSDepartmentRollup5ID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__IsDep__59BF8EFC] DEFAULT ((0)) FOR [IsDepartmentRollup]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__4A3FB220] DEFAULT ('') FOR [DSSDepartmentRollup5Name]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Funct__11FA2A12] DEFAULT ((0)) FOR [FunctionalAreaID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__FundI__4B24BEE4] DEFAULT ((0)) FOR [FundID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__4B33D659] DEFAULT ((0)) FOR [DSSDepartmentRollup6ID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Funct__12EE4E4B] DEFAULT ('') FOR [FunctionalArea]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepartm__Fund__4C18E31D] DEFAULT ('') FOR [Fund]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Resea__3B12E4EC] DEFAULT ((0)) FOR [ResearchDepartmentCategoryID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__FundS__4D0D0756] DEFAULT ((0)) FOR [FundSortOrder]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__4D1C1ECB] DEFAULT ((0)) FOR [DSSDepartmentRollup7ID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Resea__3C070925] DEFAULT ('') FOR [ResearchDepartmentCategoryName]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Proje__4E012B8F] DEFAULT ((0)) FOR [ProjectID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__4E104304] DEFAULT ('') FOR [DSSDepartmentRollup7Name]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Resea__3CFB2D5E] DEFAULT ((0)) FOR [ResearchDepartmentCategorySortOrder]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Proje__4EF54FC8] DEFAULT ('') FOR [Project]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Attri__4E4FD692] DEFAULT ((0)) FOR [AttributionTypeID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Proje__4FE97401] DEFAULT ((0)) FOR [ProjectSortOrder]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Attri__4F43FACB] DEFAULT ('') FOR [AttributionType]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__HomeD__50DD983A] DEFAULT ((0)) FOR [HomeDepartmentID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__CAPIs__3B6A1AE2] DEFAULT ((0)) FOR [CAPIsDefined]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__HomeD__51D1BC73] DEFAULT ('') FOR [HomeDepartment]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__HomeD__52C5E0AC] DEFAULT ((0)) FOR [HomeDepartmentSortOrder]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSIs__3C5E3F1B] DEFAULT ((0)) FOR [DSSIsDefined]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Progr__53BA04E5] DEFAULT ((0)) FOR [ProgramID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__IsDSS__3A68A7AC] DEFAULT ((0)) FOR [IsDSS]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Progr__54AE291E] DEFAULT ('') FOR [Program]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Entit__3D5D504C] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_FWDIMDEPARTMENTDEPARTMENTTYPE] DEFAULT ('Not Specified') FOR [DepartmentTypeOLD]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Progr__55A24D57] DEFAULT ((0)) FOR [ProgramSortOrder]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__6711CA7E] DEFAULT ('') FOR [DSSDeptGrouping]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__3C3D7833] DEFAULT ((0)) FOR [DSSDepartmentRollup1ID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__3D319C6C] DEFAULT ('') FOR [DSSDepartmentRollup1Name]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__3E25C0A5] DEFAULT ((0)) FOR [DSSDepartmentRollup2ID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__3F19E4DE] DEFAULT ('') FOR [DSSDepartmentRollup2Name]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__5A751CC8] DEFAULT ('') FOR [DepartmentCodeRaw]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__400E0917] DEFAULT ((0)) FOR [DSSDepartmentRollup3ID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__41022D50] DEFAULT ('') FOR [DSSDepartmentRollup3Name]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimDepartment_IsCAP] DEFAULT ((0)) FOR [IsCAP]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__IsOve__191A2EAB] DEFAULT ((0)) FOR [IsOverhead]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__OBIsD__3D526354] DEFAULT ((0)) FOR [OBIsDefined]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_FWDIMDEPARTMENTISOB] DEFAULT ((0)) FOR [IsOB]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_FWDIMDEPARTMENTISMRPLAN] DEFAULT ((0)) FOR [IsMRPlan]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__60630048] DEFAULT ((0)) FOR [DepartmentTypeID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_FWDIMDEPARTMENTISACTIVE] DEFAULT ((0)) FOR [IsActive]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__61572481] DEFAULT ('') FOR [DepartmentType]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__IsVar__5062D5C3] DEFAULT ((0)) FOR [IsVariable]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimDepartment_IsAcctFlexing] DEFAULT ((0)) FOR [IsAccountFlexing]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__OBGlo__69DEE9BB] DEFAULT ((0)) FOR [OBGlobalStatisticsPlanID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__MRVic__65137223] DEFAULT ('') FOR [MRVicePresident]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__OBGlo__6AD30DF4] DEFAULT ('') FOR [OBGlobalStatisticsPlan]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__MRDir__6607965C] DEFAULT ('') FOR [MRDirector]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__OBRei__6BC7322D] DEFAULT ((0)) FOR [OBReimbursementPlanID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__MRMan__66FBBA95] DEFAULT ('') FOR [MRManager]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__OBRei__6CBB5666] DEFAULT ('') FOR [OBReimbursementPlan]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__OBSer__6DAF7A9F] DEFAULT ((0)) FOR [OBServiceLinePlanID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__OBSer__6EA39ED8] DEFAULT ('') FOR [OBServiceLinePlan]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPIsD__3E46878D] DEFAULT ((0)) FOR [SPIsDefined]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimDepartment_FlexingBucketGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FlexingBucketGUID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimDepartment_IsLRFP] DEFAULT ((1)) FOR [IsLRFP]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_FWDIMDEPARTMENTROLLINGPLANID] DEFAULT ((0)) FOR [RollingPlanID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__IsCla__6CAD0619] DEFAULT ((0)) FOR [IsClaimsCosting]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPRol__22017ED5] DEFAULT ('') FOR [SPRollingForecastPlanName]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_FWDIMDEPARTMENTOPSPLANID] DEFAULT ((0)) FOR [OpsPlanID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPOpe__363D81AC] DEFAULT ('') FOR [SPOperationsPlanName]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__CompA__6F4D7455] DEFAULT ((0)) FOR [CompAnDepartmentID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_FWDIMDEPARTMENTBALPLANID] DEFAULT ((0)) FOR [BalPlanID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPBal__72526BB3] DEFAULT ('') FOR [SPBalanceSheetPlanName]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Patie__05630FEC] DEFAULT ((0)) FOR [PatientTypeRollup]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__46620409] DEFAULT ((0)) FOR [SPHDepartmentID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Patie__06573425] DEFAULT ('') FOR [PatientTypeRollupName]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__47562842] DEFAULT ((0)) FOR [SPHDepartmentConfidenceScore]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__JobCo__074B585E] DEFAULT ((0)) FOR [SPJobCodeGroup]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__484A4C7B] DEFAULT ((0)) FOR [SPHDepartmentIsValidated]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__JobCo__083F7C97] DEFAULT ('') FOR [SPJobCodeGroupName]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPPhy__0933A0D0] DEFAULT ((0)) FOR [SPPhysicianGroup]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPPhy__0A27C509] DEFAULT ('') FOR [SPPhysicianGroupName]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPAcc__0B1BE942] DEFAULT ((0)) FOR [SPAccountRollup]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPAcc__0C100D7B] DEFAULT ('') FOR [SPAccountRollupName]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPSer__595774EA] DEFAULT ((0)) FOR [SPServiceLineForecastType]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimDepartment_ConsolidatedCode] DEFAULT ('') FOR [ConsolidatedCode]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__IsHea__020F09F7] DEFAULT ((0)) FOR [IsHealthPlanAdmin]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimDepartment_IsConsolidated] DEFAULT ((0)) FOR [IsConsolidated]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__FWIsD__044B5B03] DEFAULT ((0)) FOR [FWIsDefined]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__4FEB6E43] DEFAULT ('') FOR [SPHDepartmentName]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__FW_DimDepartment_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__05C52EAB] DEFAULT ((0)) FOR [SPHDepartmentRollupIsValidated]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Produ__0BB4A8D9] DEFAULT ((0)) FOR [ProductivityPercentileID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__17CBA2F1] DEFAULT ((0)) FOR [SPHDepartmentRollupID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__18BFC72A] DEFAULT ('') FOR [SPHDepartmentRollupName]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__IsMRM__1988D110] DEFAULT ((0)) FOR [IsMRMetricTracking]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__19B3EB63] DEFAULT ((0)) FOR [SPHDepartmentRollupConfidenceScore]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__WorkW__20F64D92] DEFAULT ((0)) FOR [WorkWeekID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_datacap_DimCapitalDepartment_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimDepartment_IsPR] DEFAULT ((0)) FOR [IsPR]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimCapitalDepartment_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimDepartment_Code] DEFAULT ('') FOR [DepartmentCode]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimCapitalDepartment_Department] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Syste__3A80E3A1] DEFAULT ((0)) FOR [SystemID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Syste__3B7507DA] DEFAULT ('') FOR [System]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__30C9F8E0] DEFAULT ('') FOR [DepartmentRollup1Code]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Syste__3C692C13] DEFAULT ((0)) FOR [SystemSortOrder]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__4C27FA92] DEFAULT ('') FOR [DSSDepartmentRollup6Name]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__31BE1D19] DEFAULT ('') FOR [DepartmentRollup2Code]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__32B24152] DEFAULT ('') FOR [DepartmentRollup3Code]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Entit__3E517485] DEFAULT ('') FOR [Entity]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__33A6658B] DEFAULT ('') FOR [DepartmentRollup4Code]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Entit__3F4598BE] DEFAULT ((0)) FOR [EntitySortOrder]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__349A89C4] DEFAULT ('') FOR [DepartmentRollup5Code]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Entit__7898B414] DEFAULT ((-1)) FOR [EntityTypeOverride]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__358EADFD] DEFAULT ('') FOR [DepartmentRollup6Code]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__39DB38A1] DEFAULT ((0)) FOR [DepartmentRollup1ID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__3D2D71EF] DEFAULT ('') FOR [DepartmentRollup1]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Produ__37932B17] DEFAULT ('') FOR [ProductivityPercentile]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__5C6E178C] DEFAULT ((0)) FOR [DepartmentRollup1SortOrder]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__37D94B27] DEFAULT ((0)) FOR [SPHDepartmentTypeID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__CompA__38874F50] DEFAULT ('') FOR [CompAnDepartment]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__7313B5FD] DEFAULT ((0)) FOR [DepartmentRollup2ID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__3E219628] DEFAULT ('') FOR [DepartmentRollup2]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__5D623BC5] DEFAULT ((0)) FOR [DepartmentRollup2SortOrder]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__043E41FF] DEFAULT ((0)) FOR [DepartmentRollup3ID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__3F15BA61] DEFAULT ('') FOR [DepartmentRollup3]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__5E565FFE] DEFAULT ((0)) FOR [DepartmentRollup3SortOrder]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__05326638] DEFAULT ((0)) FOR [DepartmentRollup4ID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__4009DE9A] DEFAULT ('') FOR [DepartmentRollup4]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__5F4A8437] DEFAULT ((0)) FOR [DepartmentRollup4SortOrder]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__06268A71] DEFAULT ((0)) FOR [DepartmentRollup5ID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__40FE02D3] DEFAULT ('') FOR [DepartmentRollup5]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__603EA870] DEFAULT ((0)) FOR [DepartmentRollup5SortOrder]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__071AAEAA] DEFAULT ((0)) FOR [DepartmentRollup6ID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__41F2270C] DEFAULT ('') FOR [DepartmentRollup6]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__CAPDe__457F5D79] DEFAULT ((0)) FOR [CAPDefaultSalesTax]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__6132CCA9] DEFAULT ((0)) FOR [DepartmentRollup6SortOrder]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__CareS__44ABCE5E] DEFAULT ((0)) FOR [CareSettingID]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__471B8EB7] DEFAULT ('') FOR [SPHDepartmentType]; GO
ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__47634575] DEFAULT ('') FOR [DSSDepartmentRollup4Name]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimDepartmentPH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimDepartmentPH] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [DepartmentPHID] tinyint NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Version] timestamp NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([DepartmentPHID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_DimDepartmentPH] ON [fw].[DimDepartmentPH] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimDepartmentPH] ADD CONSTRAINT [DF_DimDepartmentPH_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimDepartmentPH] ADD CONSTRAINT [DF_DimDepartmentPH_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimDepartmentPH] ADD CONSTRAINT [DF_DimDepartmentPH_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimDepartmentPH] ADD CONSTRAINT [DF__FW_DimDepartmentPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimDepartmentRollup1 ------------------
---------------------------------------------
CREATE TABLE [fw].[DimDepartmentRollup1] (
    [DepartmentRollup1ID] smallint NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Code] nvarchar(200) NOT NULL,
    [SecureGroupID] int NOT NULL,
    [SortOrder] int NOT NULL,
    [TransactionID] int NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [Name] nvarchar(303) NOT NULL,
    [EliminationsDepartmentID] int NOT NULL,
    PRIMARY KEY ([DepartmentRollup1ID])
);

CREATE NONCLUSTERED INDEX [IX_DepartmentRollup1ID] ON [fw].[DimDepartmentRollup1] ([DepartmentRollup1ID]);
CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDepartmentRollup1] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimDepartmentRollup1] ADD CONSTRAINT [DF__DimDepart__Histo__0A612FA9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimDepartmentRollup1] ADD CONSTRAINT [DF__DimDepart__Elimi__518DFE68] DEFAULT ((0)) FOR [EliminationsDepartmentID]; GO
ALTER TABLE [fw].[DimDepartmentRollup1] ADD CONSTRAINT [DF__DimDepart__SortO__52E4AD52] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimDepartmentRollup1] ADD CONSTRAINT [DF__DimDepart__Membe__096D0B70] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimDepartmentRollup1] ADD CONSTRAINT [DF__DimDepartm__Code__0B5553E2] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimDepartmentRollup1] ADD CONSTRAINT [DF__FW_DimDepartmentRollup1_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimDepartmentRollup1] ADD CONSTRAINT [DF__DimDepart__Descr__780914CE] DEFAULT ('') FOR [Description]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimDepartmentRollup2 ------------------
---------------------------------------------
CREATE TABLE [fw].[DimDepartmentRollup2] (
    [DepartmentRollup2ID] smallint NOT NULL,
    [Code] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [SecureGroupID] int NOT NULL,
    [SortOrder] int NOT NULL,
    [TransactionID] int NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [Name] nvarchar(303) NOT NULL,
    [EliminationsDepartmentID] int NOT NULL,
    PRIMARY KEY ([DepartmentRollup2ID])
);

CREATE NONCLUSTERED INDEX [IX_DepartmentRollup2ID] ON [fw].[DimDepartmentRollup2] ([DepartmentRollup2ID]);
CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDepartmentRollup2] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimDepartmentRollup2] ADD CONSTRAINT [DF__DimDepart__Histo__16C7068E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimDepartmentRollup2] ADD CONSTRAINT [DF__DimDepart__SortO__4A4F6751] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimDepartmentRollup2] ADD CONSTRAINT [DF__DimDepart__Elimi__528222A1] DEFAULT ((0)) FOR [EliminationsDepartmentID]; GO
ALTER TABLE [fw].[DimDepartmentRollup2] ADD CONSTRAINT [DF__DimDepartm__Code__14DEBE1C] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimDepartmentRollup2] ADD CONSTRAINT [DF__DimDepart__Membe__15D2E255] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimDepartmentRollup2] ADD CONSTRAINT [DF__FW_DimDepartmentRollup2_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimDepartmentRollup2] ADD CONSTRAINT [DF__DimDepart__Descr__78FD3907] DEFAULT ('') FOR [Description]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimDepartmentRollup3 ------------------
---------------------------------------------
CREATE TABLE [fw].[DimDepartmentRollup3] (
    [DepartmentRollup3ID] smallint NOT NULL,
    [Code] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [SecureGroupID] int NOT NULL,
    [SortOrder] int NOT NULL,
    [TransactionID] int NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [EliminationsDepartmentID] int NOT NULL,
    PRIMARY KEY ([DepartmentRollup3ID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDepartmentRollup3] ([MemberGUID]);
CREATE NONCLUSTERED INDEX [IX_DepartmentRollup3ID] ON [fw].[DimDepartmentRollup3] ([DepartmentRollup3ID]);
GO
ALTER TABLE [fw].[DimDepartmentRollup3] ADD CONSTRAINT [DF__DimDepart__SortO__41BA2150] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimDepartmentRollup3] ADD CONSTRAINT [DF__DimDepart__Elimi__537646DA] DEFAULT ((0)) FOR [EliminationsDepartmentID]; GO
ALTER TABLE [fw].[DimDepartmentRollup3] ADD CONSTRAINT [DF__DimDepart__Histo__26FD6E57] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimDepartmentRollup3] ADD CONSTRAINT [DF__DimDepartm__Code__251525E5] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimDepartmentRollup3] ADD CONSTRAINT [DF__DimDepart__Membe__26094A1E] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimDepartmentRollup3] ADD CONSTRAINT [DF__FW_DimDepartmentRollup3_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimDepartmentRollup3] ADD CONSTRAINT [DF__DimDepart__Descr__79F15D40] DEFAULT ('') FOR [Description]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimDepartmentRollup4 ------------------
---------------------------------------------
CREATE TABLE [fw].[DimDepartmentRollup4] (
    [DepartmentRollup4ID] int NOT NULL,
    [Code] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [SecureGroupID] int NOT NULL,
    [SortOrder] int NOT NULL,
    [TransactionID] int NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [EliminationsDepartmentID] int NOT NULL,
    PRIMARY KEY ([DepartmentRollup4ID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDepartmentRollup4] ([MemberGUID]);
CREATE NONCLUSTERED INDEX [IX_DepartmentRollup4ID] ON [fw].[DimDepartmentRollup4] ([DepartmentRollup4ID]);
GO
ALTER TABLE [fw].[DimDepartmentRollup4] ADD CONSTRAINT [DF__DimDepart__Histo__3363453C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimDepartmentRollup4] ADD CONSTRAINT [DF__DimDepart__SortO__3924DB4F] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimDepartmentRollup4] ADD CONSTRAINT [DF__DimDepart__Elimi__546A6B13] DEFAULT ((0)) FOR [EliminationsDepartmentID]; GO
ALTER TABLE [fw].[DimDepartmentRollup4] ADD CONSTRAINT [DF__DimDepartm__Code__317AFCCA] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimDepartmentRollup4] ADD CONSTRAINT [DF__DimDepart__Membe__326F2103] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimDepartmentRollup4] ADD CONSTRAINT [DF__FW_DimDepartmentRollup4_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimDepartmentRollup4] ADD CONSTRAINT [DF__DimDepart__Descr__7AE58179] DEFAULT ('') FOR [Description]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimDepartmentRollup5 ------------------
---------------------------------------------
CREATE TABLE [fw].[DimDepartmentRollup5] (
    [DepartmentRollup5ID] smallint NOT NULL,
    [Code] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [SecureGroupID] int NOT NULL,
    [SortOrder] int NOT NULL,
    [TransactionID] int NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [EliminationsDepartmentID] int NOT NULL,
    PRIMARY KEY ([DepartmentRollup5ID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDepartmentRollup5] ([MemberGUID]);
CREATE NONCLUSTERED INDEX [IX_DepartmentRollup5ID] ON [fw].[DimDepartmentRollup5] ([DepartmentRollup5ID]);
GO
ALTER TABLE [fw].[DimDepartmentRollup5] ADD CONSTRAINT [DF__DimDepartm__Code__3DE0D3AF] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimDepartmentRollup5] ADD CONSTRAINT [DF__DimDepart__Membe__3ED4F7E8] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimDepartmentRollup5] ADD CONSTRAINT [DF__DimDepart__SortO__308F954E] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimDepartmentRollup5] ADD CONSTRAINT [DF__DimDepart__Elimi__555E8F4C] DEFAULT ((0)) FOR [EliminationsDepartmentID]; GO
ALTER TABLE [fw].[DimDepartmentRollup5] ADD CONSTRAINT [DF__DimDepart__Histo__3FC91C21] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimDepartmentRollup5] ADD CONSTRAINT [DF__FW_DimDepartmentRollup5_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimDepartmentRollup5] ADD CONSTRAINT [DF__DimDepart__Descr__7BD9A5B2] DEFAULT ('') FOR [Description]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimDepartmentRollup6 ------------------
---------------------------------------------
CREATE TABLE [fw].[DimDepartmentRollup6] (
    [DepartmentRollup6ID] smallint NOT NULL,
    [Code] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [SecureGroupID] int NOT NULL,
    [SortOrder] int NOT NULL,
    [TransactionID] int NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [EliminationsDepartmentID] int NOT NULL,
    PRIMARY KEY ([DepartmentRollup6ID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDepartmentRollup6] ([MemberGUID]);
CREATE NONCLUSTERED INDEX [IX_DepartmentRollup6ID] ON [fw].[DimDepartmentRollup6] ([DepartmentRollup6ID]);
GO
ALTER TABLE [fw].[DimDepartmentRollup6] ADD CONSTRAINT [DF__DimDepartm__Code__4A46AA94] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimDepartmentRollup6] ADD CONSTRAINT [DF__DimDepart__Membe__4B3ACECD] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimDepartmentRollup6] ADD CONSTRAINT [DF__DimDepart__SortO__27FA4F4D] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimDepartmentRollup6] ADD CONSTRAINT [DF__DimDepart__Elimi__5652B385] DEFAULT ((0)) FOR [EliminationsDepartmentID]; GO
ALTER TABLE [fw].[DimDepartmentRollup6] ADD CONSTRAINT [DF__DimDepart__Histo__4C2EF306] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimDepartmentRollup6] ADD CONSTRAINT [DF__FW_DimDepartmentRollup6_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimDepartmentRollup6] ADD CONSTRAINT [DF__DimDepart__Descr__7CCDC9EB] DEFAULT ('') FOR [Description]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimDepartmentType ------------------
---------------------------------------------
CREATE TABLE [fw].[DimDepartmentType] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [DepartmentTypeID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [TransactionID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [Rollup] nvarchar(1000) NOT NULL,
    PRIMARY KEY ([DepartmentTypeID])
);
GO
ALTER TABLE [fw].[DimDepartmentType] ADD CONSTRAINT [DF__DimDepart__Histo__59B602B9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimDepartmentType] ADD CONSTRAINT [DF__DimDepartm__Name__5B9E4B2B] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimDepartmentType] ADD CONSTRAINT [DF__DimDepart__Trans__5C926F64] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimDepartmentType] ADD CONSTRAINT [DF__DimDepart__Membe__5D86939D] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimDepartmentType] ADD CONSTRAINT [DF__DimDepart__Rollu__5E7AB7D6] DEFAULT ('') FOR [Rollup]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimEmployee ------------------
---------------------------------------------
CREATE TABLE [fw].[DimEmployee] (
    [EmployeeID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [NameLast] nvarchar(200) NOT NULL,
    [NameFirst] nvarchar(200) NOT NULL,
    [Number] nvarchar(200) NOT NULL,
    [JobCodeID] int NOT NULL,
    [JobCode] nvarchar(151) NOT NULL,
    [JobCodeCode] nvarchar(100) NOT NULL,
    [Code] nvarchar(200) NOT NULL,
    [OBIsDefined] bit NOT NULL,
    [WageRate] money NOT NULL,
    [IsProvider] bit NOT NULL,
    [ProviderID] int NOT NULL,
    [IsVariable] bit NOT NULL,
    [HireDate] datetime NOT NULL,
    [IsActive] bit NOT NULL,
    [Status] nvarchar(100) NOT NULL,
    [NextReview] datetime NOT NULL,
    [TransactionID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [WorkWeekOverrideID] int NOT NULL,
    [HomeDepartmentID] int NOT NULL,
    [HomeDepartment] nvarchar(203) NOT NULL,
    [HomeDepartmentCode] nvarchar(100) NOT NULL,
    [NameFull] nvarchar(401) NOT NULL,
    [EmployeeCohortID] int NOT NULL,
    [EmployeeCohortName] nvarchar(100) NOT NULL,
    [EmployeeCohortContractDate] datetime NOT NULL,
    [EmployeeCohortMeritType] nvarchar(100) NOT NULL,
    [StandardHours] nvarchar(100) NOT NULL,
    [FWIsDefined] bit NOT NULL,
    [TerminationDate] datetime NOT NULL,
    [AdjustedHireDate] datetime NOT NULL,
    [FTETotal] float NOT NULL,
    [HomeAccountID] int NOT NULL,
    [HomeAccount] nvarchar(100) NOT NULL,
    [HomeAccountCode] nvarchar(100) NOT NULL,
    [EmployeeClass] nvarchar(100) NOT NULL,
    [Name] nvarchar(707) NOT NULL,
    [NPI] nvarchar(50) NOT NULL,
    [PositionControlNumber] nvarchar(100) NOT NULL,
    PRIMARY KEY ([EmployeeID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimEmployee] ([MemberGUID]);
CREATE NONCLUSTERED INDEX [NCNU_IsProvider] ON [fw].[DimEmployee] ([EmployeeID], [IsProvider]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Code] ON [fw].[DimEmployee] ([Code]) INCLUDE ([EmployeeID]);
CREATE NONCLUSTERED INDEX [CORE_HomeDepartmentID_inc] ON [fw].[DimEmployee] ([HomeDepartmentID]) INCLUDE ([Name]);
GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__FWIsD__081BEBE7] DEFAULT ((0)) FOR [FWIsDefined]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Emplo__100E1AB7] DEFAULT ((0)) FOR [EmployeeCohortID]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Emplo__11023EF0] DEFAULT ('') FOR [EmployeeCohortName]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Emplo__11F66329] DEFAULT (getdate()) FOR [EmployeeCohortContractDate]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Emplo__12EA8762] DEFAULT ('') FOR [EmployeeCohortMeritType]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Stand__13DEAB9B] DEFAULT ('40') FOR [StandardHours]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__WorkW__24C6DE76] DEFAULT ((0)) FOR [WorkWeekOverrideID]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF_DimEmployee_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__NameL__4D6EC6B0] DEFAULT ('') FOR [NameLast]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__NameF__4C7AA277] DEFAULT ('') FOR [NameFirst]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Numbe__574A0949] DEFAULT ('') FOR [Number]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__JobCo__59F6619E] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__JobCo__690C57C1] DEFAULT ('') FOR [JobCode]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Posit__454AB6E3] DEFAULT ('') FOR [PositionControlNumber]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__JobCo__150BA0E7] DEFAULT ('') FOR [JobCodeCode]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__CodeN__1170E584] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__OBIsD__18F14064] DEFAULT ((0)) FOR [OBIsDefined]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__WageR__58E0795C] DEFAULT ((0)) FOR [WageRate]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__IsPro__5C19DD28] DEFAULT ((0)) FOR [IsProvider]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Provi__72A7A338] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__IsVar__6A007BFA] DEFAULT ((0)) FOR [IsVariable]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF_FWDIMEMPLOYEEHIREDATE] DEFAULT (getdate()) FOR [HireDate]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__IsAct__5BBEE049] DEFAULT ((1)) FOR [IsActive]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF_DimEmployee_Status] DEFAULT ('') FOR [Status]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF_FWDIMEMPLOYEENEXTREVIEW] DEFAULT (getdate()) FOR [NextReview]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__FW_DimEmployee_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF_DimEmployee_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__HomeD__5F943537] DEFAULT ((0)) FOR [HomeDepartmentID]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__HomeD__60885970] DEFAULT ('') FOR [HomeDepartment]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Termi__61221A57] DEFAULT ('1900-01-01 0:00') FOR [TerminationDate]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__HomeD__617C7DA9] DEFAULT ('') FOR [HomeDepartmentCode]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Adjus__62163E90] DEFAULT ('1900-01-01 0:00') FOR [AdjustedHireDate]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__FTETo__630A62C9] DEFAULT ((0)) FOR [FTETotal]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__HomeA__63FE8702] DEFAULT ((0)) FOR [HomeAccountID]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmployee__NPI__648666AC] DEFAULT ('') FOR [NPI]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__HomeA__64F2AB3B] DEFAULT ('') FOR [HomeAccount]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__HomeA__65E6CF74] DEFAULT ('') FOR [HomeAccountCode]; GO
ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Emplo__66DAF3AD] DEFAULT ('') FOR [EmployeeClass]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimEmployeeCohort ------------------
---------------------------------------------
CREATE TABLE [fw].[DimEmployeeCohort] (
    [EmployeeCohortID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Description] nvarchar(200) NOT NULL,
    [Code] nvarchar(100) NOT NULL,
    [SortOrder] nvarchar(100) NOT NULL,
    [MeritType] nvarchar(100) NOT NULL,
    [ContractDate] datetime NOT NULL,
    PRIMARY KEY ([EmployeeCohortID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimEmployeeCohort] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploy__Histo__755A247B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploye__Name__7371DC09] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploy__Membe__74660042] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploy__Trans__764E48B4] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploy__Descr__77426CED] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploye__Code__78369126] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploy__SortO__792AB55F] DEFAULT ('') FOR [SortOrder]; GO
ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploy__Merit__7A1ED998] DEFAULT ('') FOR [MeritType]; GO
ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploy__Contr__7C07220A] DEFAULT (getdate()) FOR [ContractDate]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimEmployeePH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimEmployeePH] (
    [EmployeePHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([EmployeePHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimEmployeePH] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimEmployeePH] ADD CONSTRAINT [DF__DimEmploy__Membe__64A40467] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimEmployeePH] ADD CONSTRAINT [DF__DimEmploye__Name__63AFE02E] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimEmployeePH] ADD CONSTRAINT [DF__FW_DimEmployeePH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimEntity ------------------
---------------------------------------------
CREATE TABLE [fw].[DimEntity] (
    [EntityID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [Code] nvarchar(200) NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    [EntityType] smallint NOT NULL,
    [IsActive] bit NOT NULL,
    [CAPIsDefined] bit NOT NULL,
    [DSSIsDefined] bit NOT NULL,
    [OBIsDefined] bit NOT NULL,
    [OBBenefitsDepartmentID] int NOT NULL,
    [OBBenefitsDepartment] nvarchar(203) NOT NULL,
    [OBHasGlobalStatisticsPlan] bit NOT NULL,
    [OBHasReimbursementPlan] bit NOT NULL,
    [OBHasServiceLinePlan] bit NOT NULL,
    [OBIsUsingProviderComp] bit NOT NULL,
    [SPIsDefined] bit NOT NULL,
    [SPGrossChargesPatientTypeRollup] smallint NOT NULL,
    [SPGrossChargesPayorGroup] smallint NOT NULL,
    [SPContractualsPatientTypeRollup] smallint NOT NULL,
    [SPContractualsPayorGroup] smallint NOT NULL,
    [SPIPVolumesPatientTypeRollup] smallint NOT NULL,
    [SPIPVolumesPayorGroup] smallint NOT NULL,
    [SPIPDaysPatientTypeRollup] smallint NOT NULL,
    [SPIPDaysPayorGroup] smallint NOT NULL,
    [SPOPVolumesPatientTypeRollup] smallint NOT NULL,
    [SPOPVolumesPayorGroup] smallint NOT NULL,
    [SPFTEsJobCodeGroup] smallint NOT NULL,
    [SPSalariesJobCodeGroup] smallint NOT NULL,
    [SPClinicGrossChargesPayorGroup] smallint NOT NULL,
    [SPClinicContractualsPayorGroup] smallint NOT NULL,
    [SPClinicPrimaryVolumePhysicianGroup] smallint NOT NULL,
    [SPClinicSecondaryVolumePhysicianGroup] smallint NOT NULL,
    [SPClinicFTEsPhysicianGroup] smallint NOT NULL,
    [SPClinicSalariesPhysicianGroup] smallint NOT NULL,
    [SPServiceLineForecastType] smallint NOT NULL,
    [SPOperationsSLDrivenModelID] int NOT NULL,
    [SPRollingForecastSLDrivenModelID] int NOT NULL,
    [TransactionID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(303) NOT NULL,
    [SecureGroupID] int NOT NULL,
    [WorkWeekID] int NOT NULL,
    [CAPDefaultSalesTax] float NOT NULL,
    [PayCycleID] int NOT NULL,
    [FWIsDefined] bit NOT NULL,
    [EliminationsDepartmentID] int NOT NULL,
    [CompAnPeerGroupID] int NOT NULL,
    PRIMARY KEY ([EntityID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimEntity] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [CORE_CodeUnique] ON [fw].[DimEntity] ([Code]);
GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__FWIsD__0633A375] DEFAULT ((0)) FOR [FWIsDefined]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__Membe__30F77967] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__Code__33D3E612] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__Descr__34C80A4B] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__Histo__31EB9DA0] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SortO__35BC2E84] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__Entit__0E6D5739] DEFAULT ((0)) FOR [EntityType]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__IsAct__56439C10] DEFAULT ((1)) FOR [IsActive]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__CAPIs__35F4660A] DEFAULT ((0)) FOR [CAPIsDefined]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__DSSIs__36E88A43] DEFAULT ((0)) FOR [DSSIsDefined]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__OBIsD__37DCAE7C] DEFAULT ((0)) FOR [OBIsDefined]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__OBBen__6A84FC7E] DEFAULT ('') FOR [OBBenefitsDepartment]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__OBHas__6F97C311] DEFAULT ((0)) FOR [OBHasGlobalStatisticsPlan]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__OBHas__337982C0] DEFAULT ((0)) FOR [OBHasReimbursementPlan]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__OBHas__346DA6F9] DEFAULT ((0)) FOR [OBHasServiceLinePlan]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__OBIsU__2E02373A] DEFAULT ((0)) FOR [OBIsUsingProviderComp]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPIsD__38D0D2B5] DEFAULT ((0)) FOR [SPIsDefined]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__WorkW__20022959] DEFAULT ((0)) FOR [WorkWeekID]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPGro__0F617B72] DEFAULT ((0)) FOR [SPGrossChargesPatientTypeRollup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPGro__1149C3E4] DEFAULT ((0)) FOR [SPGrossChargesPayorGroup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPCon__10559FAB] DEFAULT ((0)) FOR [SPContractualsPatientTypeRollup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPCon__123DE81D] DEFAULT ((0)) FOR [SPContractualsPayorGroup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPIPV__13320C56] DEFAULT ((0)) FOR [SPIPVolumesPatientTypeRollup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPIPV__1426308F] DEFAULT ((0)) FOR [SPIPVolumesPayorGroup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPIPD__151A54C8] DEFAULT ((0)) FOR [SPIPDaysPatientTypeRollup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPIPD__160E7901] DEFAULT ((0)) FOR [SPIPDaysPayorGroup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPOPV__17029D3A] DEFAULT ((0)) FOR [SPOPVolumesPatientTypeRollup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPOPV__17F6C173] DEFAULT ((0)) FOR [SPOPVolumesPayorGroup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPFTE__1EA3BF02] DEFAULT ((0)) FOR [SPFTEsJobCodeGroup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPSal__1DAF9AC9] DEFAULT ((0)) FOR [SPSalariesJobCodeGroup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPCli__1BC75257] DEFAULT ((0)) FOR [SPClinicGrossChargesPayorGroup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPCli__1CBB7690] DEFAULT ((0)) FOR [SPClinicContractualsPayorGroup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPCli__1F97E33B] DEFAULT ((0)) FOR [SPClinicPrimaryVolumePhysicianGroup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPCli__208C0774] DEFAULT ((0)) FOR [SPClinicSecondaryVolumePhysicianGroup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPCli__19DF09E5] DEFAULT ((0)) FOR [SPClinicFTEsPhysicianGroup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPCli__1AD32E1E] DEFAULT ((0)) FOR [SPClinicSalariesPhysicianGroup]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPSer__52AA775B] DEFAULT ((0)) FOR [SPServiceLineForecastType]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPOpe__0CD7E447] DEFAULT ((0)) FOR [SPOperationsSLDrivenModelID]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__OBBen__5D2B0160] DEFAULT ((0)) FOR [OBBenefitsDepartmentID]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPRol__0DCC0880] DEFAULT ((0)) FOR [SPRollingForecastSLDrivenModelID]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__Trans__32DFC1D9] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__CompA__3E40F3FD] DEFAULT ((0)) FOR [CompAnPeerGroupID]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__CAPDe__448B3940] DEFAULT ((0)) FOR [CAPDefaultSalesTax]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__PayCy__472A10CE] DEFAULT ((0)) FOR [PayCycleID]; GO
ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__Elimi__5099DA2F] DEFAULT ((0)) FOR [EliminationsDepartmentID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimEntityPH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimEntityPH] (
    [EntityPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([EntityPHID])
);
GO
ALTER TABLE [fw].[DimEntityPH] ADD CONSTRAINT [DF__DimEntityPH_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimEntityPH] ADD CONSTRAINT [DF__DimEntityPH_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimEntityPH] ADD CONSTRAINT [DF__DimEntityPH_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimEntityPH] ADD CONSTRAINT [DF__DimEntityPH_TransactionID] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimFiscalMonth ------------------
---------------------------------------------
CREATE TABLE [fw].[DimFiscalMonth] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [SortOrder] tinyint NOT NULL,
    [FiscalMonthCode] nvarchar(20) NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Abbreviation] nvarchar(3) NOT NULL,
    [DaysInMonth] int NOT NULL,
    [YTDDaysInMonth] int NOT NULL,
    [QuarterID] tinyint NOT NULL,
    [MonthColumnName] nvarchar(7) NOT NULL,
    [Version] timestamp NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [DaysInLeapYearMonth] int NOT NULL,
    [YTDDaysInLeapYearMonth] int NOT NULL,
    [IsReal] bit NOT NULL,
    PRIMARY KEY ([FiscalMonthID])
);

CREATE NONCLUSTERED INDEX [IX_Name] ON [fw].[DimFiscalMonth] ([Name]);
CREATE NONCLUSTERED INDEX [IX_FiscalMonthCode] ON [fw].[DimFiscalMonth] ([FiscalMonthCode]);
CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimFiscalMonth] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_DimFiscalMonth_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_DimFiscalMonth_CalendarMonthID] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_DimFiscalMonth_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_DimFiscalMonth_Abbreviation] DEFAULT ('') FOR [Abbreviation]; GO
ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_FWDIMFISCALMONTHFISCALMONTHCODE] DEFAULT ('0') FOR [FiscalMonthCode]; GO
ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_DimFiscalMonth_DaysInMonth] DEFAULT ((0)) FOR [DaysInMonth]; GO
ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_DimFiscalMonth_YTDDaysInMonth] DEFAULT ((0)) FOR [YTDDaysInMonth]; GO
ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF__DimFiscal__Quart__6B860C20] DEFAULT ((0)) FOR [QuarterID]; GO
ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_DimFiscalMonth_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF__DimFiscal__IsRea__4EA04A0D] DEFAULT ((0)) FOR [IsReal]; GO
ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF__DimFiscal__DaysI__5551D9DC] DEFAULT ((0)) FOR [DaysInLeapYearMonth]; GO
ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF__DimFiscal__YTDDa__5645FE15] DEFAULT ((0)) FOR [YTDDaysInLeapYearMonth]; GO
ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_FWDIMFISCALMONTHFISCALMONTHID] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF__FW_DimFiscalMonth_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimFiscalTime ------------------
---------------------------------------------
CREATE TABLE [fw].[DimFiscalTime] (
    [FiscalTimeID] int NOT NULL,
    [FiscalTime] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [YearMonth] nvarchar(25) NOT NULL,
    [FiscalYearMonth] nvarchar(12) NOT NULL,
    [CountFromCurrentMonth] int NOT NULL,
    [StartDate] datetime NOT NULL,
    [EndDate] datetime NOT NULL,
    PRIMARY KEY ([FiscalTimeID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimFiscalTime] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Fisca__07354875] DEFAULT ('') FOR [FiscalTime]; GO
ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Membe__08296CAE] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Trans__0A11B520] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Fisca__0B05D959] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Fisca__0BF9FD92] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__YearM__0CEE21CB] DEFAULT ('') FOR [YearMonth]; GO
ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Histo__091D90E7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Fisca__4F8782DD] DEFAULT ('') FOR [FiscalYearMonth]; GO
ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Count__72BC7BD8] DEFAULT ((0)) FOR [CountFromCurrentMonth]; GO
ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Start__73B0A011] DEFAULT (getdate()) FOR [StartDate]; GO
ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__EndDa__74A4C44A] DEFAULT (getdate()) FOR [EndDate]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimFiscalYear ------------------
---------------------------------------------
CREATE TABLE [fw].[DimFiscalYear] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [Name] nvarchar(20) NOT NULL,
    [SortOrder] nvarchar(10) NOT NULL,
    [Version] timestamp NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [IsSP] bit NOT NULL,
    [TransactionID] int NOT NULL,
    [IsCAP] bit NOT NULL,
    PRIMARY KEY ([FiscalYearID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_MemberGUID] ON [fw].[DimFiscalYear] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimFiscalYear] ADD CONSTRAINT [DF__DimFiscalY__IsSP__01014914] DEFAULT ((0)) FOR [IsSP]; GO
ALTER TABLE [fw].[DimFiscalYear] ADD CONSTRAINT [DF_FWDIMFISCALYEARFISCALYEARID] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fw].[DimFiscalYear] ADD CONSTRAINT [DF_DimFiscalYear_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimFiscalYear] ADD CONSTRAINT [DF_DimFiscalYear_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimFiscalYear] ADD CONSTRAINT [DF_DimFiscalYear_SortOrder] DEFAULT ('') FOR [SortOrder]; GO
ALTER TABLE [fw].[DimFiscalYear] ADD CONSTRAINT [DF_DimFiscalYear_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimFiscalYear] ADD CONSTRAINT [DF__DimFiscal__IsCAP__4F946E46] DEFAULT ((0)) FOR [IsCAP]; GO
ALTER TABLE [fw].[DimFiscalYear] ADD CONSTRAINT [DF__FW_DimFiscalYear_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimFiscalYearPH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimFiscalYearPH] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [FiscalYearPHID] tinyint NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Version] timestamp NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([FiscalYearPHID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_DimFiscalYearPH] ON [fw].[DimFiscalYearPH] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimFiscalYearPH] ADD CONSTRAINT [DF__FW_DimFiscalYearPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimFiscalYearPH] ADD CONSTRAINT [DF_DimFiscalYearPH_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimFiscalYearPH] ADD CONSTRAINT [DF_DimFiscalYearPH_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimFiscalYearPH] ADD CONSTRAINT [DF_DimFiscalYearPH_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimFlag ------------------
---------------------------------------------
CREATE TABLE [fw].[DimFlag] (
    [FlagID] int NOT NULL,
    [Name] nvarchar(203) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Code] nvarchar(100) NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    PRIMARY KEY ([FlagID])
);

CREATE NONCLUSTERED INDEX [NCU_Code] ON [fw].[DimFlag] ([Code]);
GO
ALTER TABLE [fw].[DimFlag] ADD CONSTRAINT [DF__DimFlag__MemberG__1A867D5D] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimFlag] ADD CONSTRAINT [DF__DimFlag__History__1B7AA196] DEFAULT (newid()) FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimFlag] ADD CONSTRAINT [DF__DimFlag__Transac__1C6EC5CF] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimFlag] ADD CONSTRAINT [DF__DimFlag__Code__1D62EA08] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimFlag] ADD CONSTRAINT [DF__DimFlag__Descrip__1E570E41] DEFAULT ('') FOR [Description]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimFlexJobCodeGroup ------------------
---------------------------------------------
CREATE TABLE [fw].[DimFlexJobCodeGroup] (
    [FlexJobCodeGroupID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Code] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    PRIMARY KEY ([FlexJobCodeGroupID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimFlexJobCodeGroup] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimFlexJobCodeGroup] ADD CONSTRAINT [DF__DimFlexJo__Histo__3F076A14] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimFlexJobCodeGroup] ADD CONSTRAINT [DF__DimFlexJob__Name__3D1F21A2] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimFlexJobCodeGroup] ADD CONSTRAINT [DF__DimFlexJo__Membe__3E1345DB] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimFlexJobCodeGroup] ADD CONSTRAINT [DF__DimFlexJo__Trans__3FFB8E4D] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimFlexJobCodeGroup] ADD CONSTRAINT [DF__DimFlexJob__Code__40EFB286] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimFlexJobCodeGroup] ADD CONSTRAINT [DF__DimFlexJo__SortO__41E3D6BF] DEFAULT ((0)) FOR [SortOrder]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimForecastDetail ------------------
---------------------------------------------
CREATE TABLE [fw].[DimForecastDetail] (
    [ForecastDetailID] int NOT NULL,
    [ForecastDetailCode] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Description] nvarchar(200) NOT NULL,
    [Name] nvarchar(403) NOT NULL,
    [OBForecastDetailID] int NOT NULL,
    [CAPForecastDetailID] int NOT NULL,
    [SPCostComponentID] int NOT NULL,
    [SPAccountRollupID] int NOT NULL,
    [SPIsDefined] bit NOT NULL,
    [CPIsDefined] bit NOT NULL,
    [OBIsDefined] bit NOT NULL,
    PRIMARY KEY ([ForecastDetailID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimForecastDetail] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__Histo__790F4C0E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__CPIsD__6D695A8F] DEFAULT ((0)) FOR [CPIsDefined]; GO
ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__OBIsD__6E5D7EC8] DEFAULT ((0)) FOR [OBIsDefined]; GO
ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__Forec__7727039C] DEFAULT ('') FOR [ForecastDetailCode]; GO
ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__Membe__781B27D5] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__Trans__7A037047] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__Descr__7AF79480] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__OBFor__7BEBB8B9] DEFAULT ((0)) FOR [OBForecastDetailID]; GO
ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__CAPFo__7CDFDCF2] DEFAULT ((0)) FOR [CAPForecastDetailID]; GO
ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__SPCos__7DD4012B] DEFAULT ((0)) FOR [SPCostComponentID]; GO
ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__SPAcc__7EC82564] DEFAULT ((0)) FOR [SPAccountRollupID]; GO
ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__SPIsD__7FBC499D] DEFAULT ((0)) FOR [SPIsDefined]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimFramework ------------------
---------------------------------------------
CREATE TABLE [fw].[DimFramework] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [FrameworkID] tinyint NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [Abbreviation] nvarchar(10) NOT NULL,
    [FrameworkSchemaName] nvarchar(10) NOT NULL,
    [ClientSchemaName] nvarchar(10) NOT NULL,
    [TransactionID] int NOT NULL,
    [IsLatestDataModel] bit NOT NULL,
    [Dependencies] nvarchar(100) NOT NULL,
    PRIMARY KEY ([FrameworkID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimFramework] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF__FW_DimFramework_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF_DimFramework_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF_DimFramework_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF_DimFramework_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF_DimFramework_Dependencies] DEFAULT ('') FOR [Dependencies]; GO
ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF_DimFramework_Abbreviation] DEFAULT ('') FOR [Abbreviation]; GO
ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF_DimFramework_FrameworkSchemaName] DEFAULT ('') FOR [FrameworkSchemaName]; GO
ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF_DimFramework_ClientSchemaName] DEFAULT ('') FOR [ClientSchemaName]; GO
ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF_DimFramework_IsLatestDataModel] DEFAULT ((0)) FOR [IsLatestDataModel]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimFunctionalArea ------------------
---------------------------------------------
CREATE TABLE [fw].[DimFunctionalArea] (
    [FunctionalAreaID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([FunctionalAreaID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimFunctionalArea] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimFunctionalArea] ADD CONSTRAINT [DF__DimFunctio__Name__0A59084A] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimFunctionalArea] ADD CONSTRAINT [DF__DimFuncti__Membe__0B4D2C83] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimFunctionalArea] ADD CONSTRAINT [DF__DimFuncti__Trans__0D3574F5] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimFunctionalArea] ADD CONSTRAINT [DF__DimFuncti__Histo__0C4150BC] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimFund ------------------
---------------------------------------------
CREATE TABLE [fw].[DimFund] (
    [FundID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [SortOrder] int NOT NULL,
    [Code] nvarchar(100) NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [Name] nvarchar(203) NOT NULL,
    PRIMARY KEY ([FundID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimFund] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimFund] ADD CONSTRAINT [DF__DimFund__History__78B67F6A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimFund] ADD CONSTRAINT [DF__DimFund__MemberG__77C25B31] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimFund] ADD CONSTRAINT [DF__DimFund__Transac__79AAA3A3] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimFund] ADD CONSTRAINT [DF__DimFund__SortOrd__7A9EC7DC] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimFund] ADD CONSTRAINT [DF__DimFund__Code__7B92EC15] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimFund] ADD CONSTRAINT [DF__DimFund__Descrip__7C87104E] DEFAULT ('') FOR [Description]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimHomeDepartment ------------------
---------------------------------------------
CREATE TABLE [fw].[DimHomeDepartment] (
    [HomeDepartmentID] int NOT NULL,
    [Name] nvarchar(203) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [SortOrder] int NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [Code] nvarchar(100) NOT NULL,
    PRIMARY KEY ([HomeDepartmentID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimHomeDepartment] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimHomeDepartment] ADD CONSTRAINT [DF__DimHomeDe__Histo__466009C7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimHomeDepartment] ADD CONSTRAINT [DF__DimHomeDe__Membe__456BE58E] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimHomeDepartment] ADD CONSTRAINT [DF__DimHomeDe__Trans__47542E00] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimHomeDepartment] ADD CONSTRAINT [DF__DimHomeDe__SortO__48485239] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimHomeDepartment] ADD CONSTRAINT [DF__DimHomeDe__Descr__493C7672] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimHomeDepartment] ADD CONSTRAINT [DF__DimHomeDep__Code__4A309AAB] DEFAULT ('') FOR [Code]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimInitiative ------------------
---------------------------------------------
CREATE TABLE [fw].[DimInitiative] (
    [InitiativeID] int NOT NULL,
    [Name] nvarchar(400) NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [InitiativeStatusID] int NOT NULL,
    [InitiativeStatus] nvarchar(200) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [Author] nvarchar(200) NOT NULL,
    [CostLeaderGUID] uniqueidentifier NOT NULL,
    [CostLeader] nvarchar(200) NOT NULL,
    [OwnerGUID] uniqueidentifier NOT NULL,
    [Owner] nvarchar(200) NOT NULL,
    [ExecutiveSponsorGUID] uniqueidentifier NOT NULL,
    [ExecutiveSponsor] nvarchar(200) NOT NULL,
    [Workstream] nvarchar(200) NOT NULL,
    [Description] nvarchar(max) NOT NULL,
    [SourceOfSavingsId] int NOT NULL,
    [SourceOfSavings] nvarchar(200) NOT NULL,
    [DateCreated] datetime NOT NULL,
    [EffectiveDate] datetime NOT NULL,
    [GoalStartDate] datetime NOT NULL,
    [GoalEndDate] datetime NOT NULL,
    [AnnualGoal] decimal NOT NULL,
    [SavingsEstimate] decimal NOT NULL,
    [InitiativeRollup1] nvarchar(400) NOT NULL,
    [InitiativeRollup1Id] int NOT NULL,
    [InitiativeRollup2] nvarchar(400) NOT NULL,
    [InitiativeRollup2Id] int NOT NULL,
    [InitiativeRollup3] nvarchar(400) NOT NULL,
    [InitiativeRollup3Id] int NOT NULL,
    PRIMARY KEY ([InitiativeID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimInitiative] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitiat__Name__58137294] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Membe__590796CD] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Histo__59FBBB06] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Trans__5AEFDF3F] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Initi__5BE40378] DEFAULT ((0)) FOR [InitiativeStatusID]; GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Initi__5CD827B1] DEFAULT ('') FOR [InitiativeStatus]; GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Autho__5DCC4BEA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Autho__5EC07023] DEFAULT ('') FOR [Author]; GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__CostL__5FB4945C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CostLeaderGUID]; GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__CostL__60A8B895] DEFAULT ('') FOR [CostLeader]; GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Owner__619CDCCE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OwnerGUID]; GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Owner__62910107] DEFAULT ('') FOR [Owner]; GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Execu__63852540] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ExecutiveSponsorGUID]; GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Execu__64794979] DEFAULT ('') FOR [ExecutiveSponsor]; GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Works__656D6DB2] DEFAULT ('') FOR [Workstream]; GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Descr__666191EB] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Sourc__6755B624] DEFAULT ((0)) FOR [SourceOfSavingsId]; GO
ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Sourc__6849DA5D] DEFAULT ('') FOR [SourceOfSavings]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimInitiativeStatus ------------------
---------------------------------------------
CREATE TABLE [fw].[DimInitiativeStatus] (
    [InitiativeStatusID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([InitiativeStatusID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimInitiativeStatus] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimInitiativeStatus] ADD CONSTRAINT [DF__DimInitia__Histo__4466DD39] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimInitiativeStatus] ADD CONSTRAINT [DF__DimInitiat__Name__427E94C7] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimInitiativeStatus] ADD CONSTRAINT [DF__DimInitia__Membe__4372B900] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimInitiativeStatus] ADD CONSTRAINT [DF__DimInitia__Trans__455B0172] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimJobCode ------------------
---------------------------------------------
CREATE TABLE [fw].[DimJobCode] (
    [JobCodeID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(151) NOT NULL,
    [JobCode] nvarchar(20) NOT NULL,
    [Description] nvarchar(128) NOT NULL,
    [JobCodeGroupID] int NOT NULL,
    [IsVariable] bit NOT NULL,
    [IsActive] bit NOT NULL,
    [IsProvider] bit NOT NULL,
    [IsAgency] bit NOT NULL,
    [DSSIsDefined] bit NOT NULL,
    [DSSCostingRollup] nvarchar(100) NOT NULL,
    [DSSRate] money NOT NULL,
    [OBIsDefined] bit NOT NULL,
    [FlexBucketGUID] uniqueidentifier NOT NULL,
    [SPIsDefined] bit NOT NULL,
    [Rollup] nvarchar(128) NOT NULL,
    [Variability] float NOT NULL,
    [TransactionID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [WorkWeekOverrideID] int NOT NULL,
    [FlexJobCodeGroupID] int NOT NULL,
    [DSSCostingRollup2] nvarchar(100) NOT NULL,
    [DSSCostingRollup3] nvarchar(100) NOT NULL,
    [FWIsDefined] bit NOT NULL,
    [IsPatientCare] bit NOT NULL,
    [IsBedside] bit NOT NULL,
    [IsLicensed] bit NOT NULL,
    [ManagementLevel] nvarchar(100) NOT NULL,
    [SkillMix] nvarchar(100) NOT NULL,
    [DSSJobCodeRollup1ID] int NOT NULL,
    [DSSJobCodeRollup1] varchar(200) NOT NULL,
    [DSSJobCodeRollup2] nvarchar(200) NOT NULL,
    [DSSJobCodeRollup2ID] int NOT NULL,
    [PRIsDefined] bit NOT NULL,
    [CIIsDefined] bit NOT NULL,
    [IsPR] bit NOT NULL,
    [DSSCostComponent] varchar(200) NOT NULL,
    [DSSJobCodeRollup3ID] int NOT NULL,
    [DSSJobCodeRollup3] nvarchar(100) NOT NULL,
    [IsDaily] bit NOT NULL,
    [DSSCostComponentID] int NOT NULL,
    [SPHJobCodeRollupID] int NOT NULL,
    [SPHJobCodeRollupName] nvarchar(200) NOT NULL,
    [SPHJobCodeRollupConfidenceScore] float NOT NULL,
    [SPHVariability] decimal NOT NULL,
    [SPHJobCodeRollupIsValidated] bit NOT NULL,
    [StaffingCategoryID] int NOT NULL,
    PRIMARY KEY ([JobCodeID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_MemberGUID_JC] ON [fw].[DimJobCode] ([MemberGUID]);
CREATE NONCLUSTERED INDEX [IX_JobCodeID] ON [fw].[DimJobCode] ([JobCodeID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_JobCode] ON [fw].[DimJobCode] ([JobCode]) INCLUDE ([JobCodeID]);
CREATE NONCLUSTERED INDEX [NCNU_StaffingReconciliation] ON [fw].[DimJobCode] ([JobCodeID], [JobCodeGroupID], [IsProvider]);
GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__Histo__54DD0E89] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__PRIsD__03C2E1CC] DEFAULT ((0)) FOR [PRIsDefined]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__CIIsD__04B70605] DEFAULT ((0)) FOR [CIIsDefined]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__Staff__055B1A57] DEFAULT ((0)) FOR [StaffingCategoryID]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__SPHJo__08A19B56] DEFAULT ((0)) FOR [SPHJobCodeRollupIsValidated]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__FWIsD__09101020] DEFAULT ((0)) FOR [FWIsDefined]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSJo__15C19676] DEFAULT ('') FOR [DSSJobCodeRollup2]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__WorkW__21EA71CB] DEFAULT ((-1)) FOR [WorkWeekOverrideID]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSJo__22276D5B] DEFAULT ((0)) FOR [DSSJobCodeRollup2ID]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSJo__28747837] DEFAULT ((0)) FOR [DSSJobCodeRollup1ID]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSJo__29689C70] DEFAULT ('') FOR [DSSJobCodeRollup1]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF_DimJobCode_FlexBucketGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FlexBucketGUID]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSCo__380A2AD4] DEFAULT ('') FOR [DSSCostingRollup2]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__SPHVa__38CD6F60] DEFAULT ((0)) FOR [SPHVariability]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSCo__38FE4F0D] DEFAULT ('') FOR [DSSCostingRollup3]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF_DimJobCode_IsPR] DEFAULT ((1)) FOR [IsPR]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSJo__431391A4] DEFAULT ((0)) FOR [DSSJobCodeRollup3ID]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__FlexJ__43CC1F31] DEFAULT ((0)) FOR [FlexJobCodeGroupID]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSJo__4407B5DD] DEFAULT ('') FOR [DSSJobCodeRollup3]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSCo__55674C09] DEFAULT ('') FOR [DSSCostComponent]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__IsPat__5C5D653A] DEFAULT ((0)) FOR [IsPatientCare]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__IsBed__5D518973] DEFAULT ((0)) FOR [IsBedside]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__IsLic__5E45ADAC] DEFAULT ((0)) FOR [IsLicensed]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSCo__5EA8342E] DEFAULT ((0)) FOR [DSSCostComponentID]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__Manag__5F39D1E5] DEFAULT ('') FOR [ManagementLevel]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__Skill__602DF61E] DEFAULT ('') FOR [SkillMix]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__SPHJo__616F9240] DEFAULT ((0)) FOR [SPHJobCodeRollupID]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__SPHJo__6263B679] DEFAULT ('Not Specified') FOR [SPHJobCodeRollupName]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__SPHJo__6357DAB2] DEFAULT ((0)) FOR [SPHJobCodeRollupConfidenceScore]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__Membe__53E8EA50] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCode__Code__5200A1DE] DEFAULT ('') FOR [JobCode]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCode__Name__510C7DA5] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__JobCo__7C53D2CB] DEFAULT ((0)) FOR [JobCodeGroupID]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__IsVar__47CD8FC2] DEFAULT ((0)) FOR [IsVariable]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF_DimJobCode_IsActive] DEFAULT ((1)) FOR [IsActive]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__IsPro__3C5A7832] DEFAULT ((0)) FOR [IsProvider]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__IsAge__3BF12F35] DEFAULT ((0)) FOR [IsAgency]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSIs__3F3AABC6] DEFAULT ((0)) FOR [DSSIsDefined]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSCo__0B332816] DEFAULT ('') FOR [DSSCostingRollup]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSRa__0C274C4F] DEFAULT ((0)) FOR [DSSRate]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__OBIsD__402ECFFF] DEFAULT ((0)) FOR [OBIsDefined]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__SPIsD__4122F438] DEFAULT ((0)) FOR [SPIsDefined]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF_DimJobCode_Category] DEFAULT ('') FOR [Rollup]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF_DimJobCode_Variability] DEFAULT ((0)) FOR [Variability]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__FW_DimJobCode_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF_DimJobCode_IsDaily] DEFAULT ((1)) FOR [IsDaily]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimJobCodeGroup ------------------
---------------------------------------------
CREATE TABLE [fw].[DimJobCodeGroup] (
    [JobCodeGroupID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Category] nvarchar(200) NOT NULL,
    [SortOrder] int NOT NULL,
    [IsCapital] bit NOT NULL,
    [IsDSS] bit NOT NULL,
    [IsMR] bit NOT NULL,
    [IsOB] bit NOT NULL,
    [IsSP] bit NOT NULL,
    [SPStaffType] nvarchar(100) NOT NULL,
    [SPSalariesFinancialReportingID] int NOT NULL,
    [SPSalariesFinancialReporting] varchar(4000) NOT NULL,
    [SPFTEsFinancialReportingID] int NOT NULL,
    [SPFTEsFinancialReporting] varchar(200) NOT NULL,
    [CAPFinancialReportingID] int NOT NULL,
    [CAPFinancialReporting] nvarchar(2000) NOT NULL,
    [TransactionID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [SPDefaultVolumeDriver] nvarchar(400) NOT NULL,
    [WorkWeekOverrideID] int NOT NULL,
    PRIMARY KEY ([JobCodeGroupID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimJobCodeGroup] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimJobCodeGroup] ([Name]);
GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__FW_DimJobCodeGroup_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__Membe__70E2201F] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCode__Name__71D64458] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__Categ__178A1950] DEFAULT ('') FOR [Category]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__SortO__187E3D89] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__IsCap__21B1D6B1] DEFAULT ((0)) FOR [IsCapital]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__IsDSS__248E435C] DEFAULT ((0)) FOR [IsDSS]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCode__IsMR__239A1F23] DEFAULT ((0)) FOR [IsMR]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCode__IsOB__22A5FAEA] DEFAULT ((0)) FOR [IsOB]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCode__IsSP__20BDB278] DEFAULT ((0)) FOR [IsSP]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__SPSta__7685EADC] DEFAULT ('') FOR [SPStaffType]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__SPFin__777A0F15] DEFAULT ((0)) FOR [SPSalariesFinancialReportingID]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__SPSal__02AE5E6E] DEFAULT ('') FOR [SPSalariesFinancialReporting]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__SPFTE__03A282A7] DEFAULT ((0)) FOR [SPFTEsFinancialReportingID]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__SPFTE__0496A6E0] DEFAULT ('') FOR [SPFTEsFinancialReporting]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__CAPFi__3291B063] DEFAULT ((0)) FOR [CAPFinancialReportingID]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__SPDef__2232F3E0] DEFAULT ('') FOR [SPDefaultVolumeDriver]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__CAPFi__3385D49C] DEFAULT ('') FOR [CAPFinancialReporting]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__Histo__72CA6891] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__WorkW__79340BA9] DEFAULT ((-1)) FOR [WorkWeekOverrideID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimJobCodeGroupPH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimJobCodeGroupPH] (
    [JobCodeGroupPHID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([JobCodeGroupPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimJobCodeGroupPH] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimJobCodeGroupPH] ADD CONSTRAINT [DF__FW_DimJobCodeGroupPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimJobCodeGroupPH] ADD CONSTRAINT [DF__DimJobCod__Membe__778F1DAE] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimJobCodeGroupPH] ADD CONSTRAINT [DF__DimJobCode__Name__788341E7] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimJobCodeGroupPH] ADD CONSTRAINT [DF__DimJobCod__Histo__79776620] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimJobCodePH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimJobCodePH] (
    [JobCodePHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([JobCodePHID])
);

CREATE NONCLUSTERED INDEX [IX_JobCodePHID] ON [fw].[DimJobCodePH] ([JobCodePHID]);
CREATE NONCLUSTERED INDEX [IX_MemberGUID] ON [fw].[DimJobCodePH] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimJobCodePH] ADD CONSTRAINT [DF__FW_DimJobCodePH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimJobCodePH] ADD CONSTRAINT [DF__DimJobCode__Name__0DA619FA] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimJobCodePH] ADD CONSTRAINT [DF__DimJobCod__Membe__0E9A3E33] DEFAULT (newid()) FOR [MemberGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimLineNumber ------------------
---------------------------------------------
CREATE TABLE [fw].[DimLineNumber] (
    [LineNumberID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([LineNumberID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimLineNumber] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimLineNumber] ADD CONSTRAINT [DF__FW_DimLineNumber_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimLineNumber] ADD CONSTRAINT [DF__DimLineNu__Membe__36E78D22] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimLineNumber] ADD CONSTRAINT [DF__DimLineNu__Histo__37DBB15B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimManufacturer ------------------
---------------------------------------------
CREATE TABLE [fw].[DimManufacturer] (
    [ManufacturerID] int NOT NULL,
    [Name] nvarchar(203) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Code] nvarchar(100) NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    PRIMARY KEY ([ManufacturerID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimManufacturer] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimManufacturer] ADD CONSTRAINT [DF__DimManufa__Membe__317C5D7F] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimManufacturer] ADD CONSTRAINT [DF__DimManufa__Trans__3364A5F1] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimManufacturer] ADD CONSTRAINT [DF__DimManufac__Code__3458CA2A] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimManufacturer] ADD CONSTRAINT [DF__DimManufa__Descr__354CEE63] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimManufacturer] ADD CONSTRAINT [DF__DimManufa__Histo__327081B8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimMedicalSurgical ------------------
---------------------------------------------
CREATE TABLE [fw].[DimMedicalSurgical] (
    [MedicalSurgicalID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Code] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    PRIMARY KEY ([MedicalSurgicalID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimMedicalSurgical] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimMedicalSurgical] ([Name]);
GO
ALTER TABLE [fw].[DimMedicalSurgical] ADD CONSTRAINT [DF__DimMedica__Histo__7A099935] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimMedicalSurgical] ADD CONSTRAINT [DF__DimMedical__Name__782150C3] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimMedicalSurgical] ADD CONSTRAINT [DF__DimMedica__Membe__791574FC] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimMedicalSurgical] ADD CONSTRAINT [DF__DimMedica__Trans__7AFDBD6E] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimMedicalSurgical] ADD CONSTRAINT [DF__DimMedical__Code__7BF1E1A7] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimMedicalSurgical] ADD CONSTRAINT [DF__DimMedica__SortO__7CE605E0] DEFAULT ((0)) FOR [SortOrder]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimModelingServiceLine ------------------
---------------------------------------------
CREATE TABLE [fw].[DimModelingServiceLine] (
    [ModelingServiceLineID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(912) NOT NULL,
    [PatientClassID] int NOT NULL,
    [PatientClass] nvarchar(200) NOT NULL,
    [PatientClassCode] nvarchar(100) NOT NULL,
    [PatientClassSortOrder] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [AgeCohort] nvarchar(200) NOT NULL,
    [AgeCohortCode] nvarchar(100) NOT NULL,
    [AgeCohortSortOrder] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLine] nvarchar(303) NOT NULL,
    [ServiceLineCode] nvarchar(100) NOT NULL,
    [ServiceLineSortOrder] int NOT NULL,
    [ServiceLineRollup] nvarchar(200) NOT NULL,
    [ServiceLineRollupSortOrder] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [MedicalSurgical] nvarchar(200) NOT NULL,
    [MedicalSurgicalCode] nvarchar(100) NOT NULL,
    [MedicalSurgicalSortOrder] int NOT NULL,
    [SortOrder] varchar(49) NULL,
    [TransactionID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ModelingServiceLineID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimModelingServiceLine] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Membe__37D1C184] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Patie__3BA25268] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Patie__43437430] DEFAULT ('') FOR [PatientClass]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Patie__44379869] DEFAULT ('') FOR [PatientClassCode]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Patie__452BBCA2] DEFAULT ((0)) FOR [PatientClassSortOrder]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__AgeCo__3C9676A1] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__AgeCo__4DC102A3] DEFAULT ('') FOR [AgeCohort]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__AgeCo__4EB526DC] DEFAULT ('') FOR [AgeCohortCode]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__AgeCo__4FA94B15] DEFAULT ((0)) FOR [AgeCohortSortOrder]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Servi__3D8A9ADA] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Servi__461FE0DB] DEFAULT ('') FOR [ServiceLine]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Servi__47140514] DEFAULT ('') FOR [ServiceLineCode]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Servi__4808294D] DEFAULT ((0)) FOR [ServiceLineSortOrder]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Servi__48FC4D86] DEFAULT ('') FOR [ServiceLineRollup]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Histo__38C5E5BD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Servi__49F071BF] DEFAULT ((0)) FOR [ServiceLineRollupSortOrder]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Medic__3E7EBF13] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Medic__4AE495F8] DEFAULT ('') FOR [MedicalSurgical]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Medic__4BD8BA31] DEFAULT ('') FOR [MedicalSurgicalCode]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Medic__4CCCDE6A] DEFAULT ((0)) FOR [MedicalSurgicalSortOrder]; GO
ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Trans__39BA09F6] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimModelingServiceLinePH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimModelingServiceLinePH] (
    [ModelingServiceLinePHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([ModelingServiceLinePHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimModelingServiceLinePH] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimModelingServiceLinePH] ([Name]);
GO
ALTER TABLE [fw].[DimModelingServiceLinePH] ADD CONSTRAINT [DF__DimModelin__Name__09D5ECAA] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimModelingServiceLinePH] ADD CONSTRAINT [DF__DimModeli__Membe__0ACA10E3] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimModelingServiceLinePH] ADD CONSTRAINT [DF__DimModeli__Trans__0CB25955] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimModelingServiceLinePH] ADD CONSTRAINT [DF__DimModeli__Histo__0BBE351C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimOpportunity ------------------
---------------------------------------------
CREATE TABLE [fw].[DimOpportunity] (
    [OpportunityKey] nvarchar(20) NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [EntityID] int NOT NULL,
    [SourceOfSavingsID] int NOT NULL,
    [SourceOfSavings] nvarchar(200) NOT NULL,
    [IsHidden] bit NOT NULL,
    [HasInitiative] bit NOT NULL,
    [InitiativeGUID] uniqueidentifier NOT NULL,
    [Initiative] nvarchar(400) NOT NULL,
    [InitiativeStatusID] int NOT NULL,
    [InitiativeStatus] nvarchar(200) NOT NULL,
    [Owner] nvarchar(130) NOT NULL,
    [CostLeader] nvarchar(130) NOT NULL,
    [ExecutiveSponsor] nvarchar(130) NOT NULL,
    [Workstream] nvarchar(200) NOT NULL,
    [DateCreated] datetime NOT NULL,
    [BaselineStartDate] datetime NOT NULL,
    [BaselineEndDate] datetime NOT NULL,
    [SavingsIdentified] decimal NOT NULL,
    [SavingsGoal] decimal NOT NULL,
    [AnnualGoal] decimal NOT NULL,
    [SavingsEstimate] decimal NOT NULL,
    [InitiativeRollup1Id] int NOT NULL,
    [InitiativeRollup1] nvarchar(400) NOT NULL,
    [InitiativeRollup2Id] int NOT NULL,
    [InitiativeRollup2] nvarchar(400) NOT NULL,
    [InitiativeRollup3Id] int NOT NULL,
    [InitiativeRollup3] nvarchar(400) NOT NULL,
    PRIMARY KEY ([OpportunityKey])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimOpportunity] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Oppor__41300D3C] DEFAULT ('') FOR [OpportunityKey]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpportu__Name__42243175] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Membe__431855AE] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Histo__440C79E7] DEFAULT (CONVERT([uniqueidentifier],0x00)) FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Trans__45009E20] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Entit__45F4C259] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Sourc__46E8E692] DEFAULT ((0)) FOR [SourceOfSavingsID]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Sourc__47DD0ACB] DEFAULT ('') FOR [SourceOfSavings]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__IsHid__48D12F04] DEFAULT ((0)) FOR [IsHidden]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__HasIn__49C5533D] DEFAULT ((0)) FOR [HasInitiative]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Initi__4AB97776] DEFAULT (CONVERT([uniqueidentifier],0x00)) FOR [InitiativeGUID]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Initi__4BAD9BAF] DEFAULT ('') FOR [Initiative]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Initi__4CA1BFE8] DEFAULT ((0)) FOR [InitiativeStatusID]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Initi__4D95E421] DEFAULT ('') FOR [InitiativeStatus]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Owner__4E8A085A] DEFAULT ('') FOR [Owner]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__CostL__4F7E2C93] DEFAULT ('') FOR [CostLeader]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Execu__507250CC] DEFAULT ('') FOR [ExecutiveSponsor]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Works__51667505] DEFAULT ('') FOR [Workstream]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Savin__525A993E] DEFAULT ((0)) FOR [SavingsIdentified]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Savin__534EBD77] DEFAULT ((0)) FOR [SavingsGoal]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Annua__5442E1B0] DEFAULT ((0)) FOR [AnnualGoal]; GO
ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Savin__553705E9] DEFAULT ((0)) FOR [SavingsEstimate]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPatientClass ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPatientClass] (
    [PatientClassID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [Code] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [IsActive] bit NOT NULL,
    [IncludeInAdjustedCalculations] bit NOT NULL,
    [OBServiceLinePrimaryVolumeAccountID] int NOT NULL,
    PRIMARY KEY ([PatientClassID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPatientClass] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimPatientClass] ([Name]);
GO
ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatient__Name__1DDC1A00] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatient__Code__1ED03E39] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatien__SortO__1FC46272] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatien__OBSer__20890BE2] DEFAULT ((0)) FOR [OBServiceLinePrimaryVolumeAccountID]; GO
ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatien__Membe__20B886AB] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatien__Trans__22A0CF1D] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatien__IsAct__554F77D7] DEFAULT ((0)) FOR [IsActive]; GO
ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatien__Histo__21ACAAE4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatien__Inclu__6AF4A033] DEFAULT ((0)) FOR [IncludeInAdjustedCalculations]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPatientReimbursementGroup ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPatientReimbursementGroup] (
    [PatientReimbursementGroupID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [CareSettingID] int NOT NULL,
    [PatientClass] nvarchar(200) NOT NULL,
    [PatientClassCode] nvarchar(100) NOT NULL,
    [PatientClassSortOrder] int NOT NULL,
    [CareSetting] nvarchar(200) NOT NULL,
    [CareSettingCode] nvarchar(100) NOT NULL,
    [CareSettingSortOrder] int NOT NULL,
    [Name] nvarchar(403) NOT NULL,
    [Code] nvarchar(203) NOT NULL,
    [SortOrder] varchar(203) NULL,
    PRIMARY KEY ([PatientReimbursementGroupID])
);

CREATE NONCLUSTERED INDEX [NCNU_MemberGUID] ON [fw].[DimPatientReimbursementGroup] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_PreventDuplicates] ON [fw].[DimPatientReimbursementGroup] ([PatientClassID], [CareSettingID]);
GO
ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__Histo__57BEA2D2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__Membe__56CA7E99] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__Trans__58B2C70B] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__Patie__5B8F33B6] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__CareS__5C8357EF] DEFAULT ((0)) FOR [CareSettingID]; GO
ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__Patie__660CC229] DEFAULT ('') FOR [PatientClass]; GO
ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__Patie__6700E662] DEFAULT ('') FOR [PatientClassCode]; GO
ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__Patie__67F50A9B] DEFAULT ((0)) FOR [PatientClassSortOrder]; GO
ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__CareS__68E92ED4] DEFAULT ('') FOR [CareSetting]; GO
ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__CareS__69DD530D] DEFAULT ('') FOR [CareSettingCode]; GO
ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__CareS__6AD17746] DEFAULT ((0)) FOR [CareSettingSortOrder]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPatientReimbursementGroupPH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPatientReimbursementGroupPH] (
    [PatientReimbursementGroupPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([PatientReimbursementGroupPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPatientReimbursementGroupPH] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimPatientReimbursementGroupPH] ADD CONSTRAINT [DF__DimPatien__Histo__2E878315] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimPatientReimbursementGroupPH] ADD CONSTRAINT [DF__DimPatient__Name__2C9F3AA3] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimPatientReimbursementGroupPH] ADD CONSTRAINT [DF__DimPatien__Membe__2D935EDC] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPatientReimbursementGroupPH] ADD CONSTRAINT [DF__DimPatien__Trans__2F7BA74E] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPatientType ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPatientType] (
    [Code] nvarchar(50) NOT NULL,
    [PatientTypeID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [PatientTypeRollupID] tinyint NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [Name] nvarchar(153) NOT NULL,
    [DSSRollup] nvarchar(100) NOT NULL,
    PRIMARY KEY ([PatientTypeID])
);

CREATE UNIQUE NONCLUSTERED INDEX [NCU_PatientTypeCode] ON [fw].[DimPatientType] ([Code]) INCLUDE ([PatientTypeID]);
CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPatientType] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimPatientType] ADD CONSTRAINT [DF__DimPatien__Descr__03F78862] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimPatientType] ADD CONSTRAINT [DF__DimPatient__Code__0451B9EA] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimPatientType] ADD CONSTRAINT [DF__FW_DimPatientType_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimPatientType] ADD CONSTRAINT [DF__DimPatien__Membe__063A025C] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPatientType] ADD CONSTRAINT [DF__DimPatien__DSSRo__54A1A578] DEFAULT ('') FOR [DSSRollup]; GO
ALTER TABLE [fw].[DimPatientType] ADD CONSTRAINT [DF__DimPatien__Histo__496564B9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimPatientType] ADD CONSTRAINT [DF__fw_DimPatientType_PatientTypeRollupID] DEFAULT ((0)) FOR [PatientTypeRollupID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPatientTypeRollup ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPatientTypeRollup] (
    [PatientTypeRollupID] tinyint NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Type] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    [IsCapital] bit NOT NULL,
    [IsDSS] bit NOT NULL,
    [IsMR] bit NOT NULL,
    [IsOB] bit NOT NULL,
    [IsSP] bit NOT NULL,
    [SPChargesFinancialReportingID] int NOT NULL,
    [SPChargesFinancialReporting] nvarchar(100) NOT NULL,
    [SPContractualsFinancialReportingID] int NOT NULL,
    [SPContractualsFinancialReporting] nvarchar(100) NOT NULL,
    [SPPrimaryStatisticFinancialReportingID] int NOT NULL,
    [SPPrimaryStatisticFinancialReporting] nvarchar(100) NOT NULL,
    [SPPrimaryStatisticFinancialReportingLineName] nvarchar(100) NOT NULL,
    [SPSecondaryStatisticFinancialReportingID] int NOT NULL,
    [SPSecondaryStatisticFinancialReporting] nvarchar(100) NOT NULL,
    [SPSecondaryStatisticFinancialReportingLineName] nvarchar(100) NOT NULL,
    [SPTertiaryStatisticFinancialReportingID] int NOT NULL,
    [SPTertiaryStatisticFinancialReporting] nvarchar(100) NOT NULL,
    [SPTertiaryStatisticFinancialReportingLineName] nvarchar(100) NOT NULL,
    [CAPChargesFinancialReportingID] int NOT NULL,
    [CAPChargesFinancialReporting] nvarchar(100) NOT NULL,
    [CAPContractualsFinancialReportingID] int NOT NULL,
    [CAPContractualsFinancialReporting] nvarchar(100) NOT NULL,
    [CAPPrimaryStatisticFinancialReportingID] int NOT NULL,
    [CAPPrimaryStatisticFinancialReporting] nvarchar(100) NOT NULL,
    [CAPSecondaryStatisticFinancialReportingID] int NOT NULL,
    [CAPSecondaryStatisticFinancialReporting] nvarchar(100) NOT NULL,
    [TransactionID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [CareSettingID] int NOT NULL,
    [CareSettingName] nvarchar(200) NOT NULL,
    [PatientClassID] int NOT NULL,
    [PatientClassName] nvarchar(200) NOT NULL,
    [CAPPrimaryStatisticFinancialReportingLineName] nvarchar(100) NOT NULL,
    [CAPSecondaryStatisticFinancialReportingLineName] nvarchar(100) NOT NULL,
    [Sg2PatientTypeRollup] nvarchar(400) NOT NULL,
    PRIMARY KEY ([PatientTypeRollupID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPatientTypeRollup] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimPatientTypeRollup] ([Name]);
GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__FW_DimPatientTypeRollup_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Sg2Pa__184B9135] DEFAULT ('') FOR [Sg2PatientTypeRollup]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CareS__260DA665] DEFAULT ((0)) FOR [CareSettingID]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CareS__2701CA9E] DEFAULT ('') FOR [CareSettingName]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPPr__27C5A8B7] DEFAULT ('') FOR [CAPPrimaryStatisticFinancialReportingLineName]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Patie__27F5EED7] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPSe__28B9CCF0] DEFAULT ('') FOR [CAPSecondaryStatisticFinancialReportingLineName]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Patie__28EA1310] DEFAULT ('') FOR [PatientClassName]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__PatientTy__Membe__12B81536] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__PatientTyp__Name__11C3F0FD] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatient__Type__7714F095] DEFAULT ('') FOR [Type]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__SortO__047D9F94] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__IsCap__195BEE45] DEFAULT ((0)) FOR [IsCapital]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__IsDSS__1C385AF0] DEFAULT ((0)) FOR [IsDSS]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Histo__69D2344B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatient__IsMR__1B4436B7] DEFAULT ((0)) FOR [IsMR]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatient__IsOB__1A50127E] DEFAULT ((0)) FOR [IsOB]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatient__IsSP__1867CA0C] DEFAULT ((0)) FOR [IsSP]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Charg__22257319] DEFAULT ((0)) FOR [SPChargesFinancialReportingID]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Charg__26EA2836] DEFAULT ('') FOR [SPChargesFinancialReporting]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Contr__23199752] DEFAULT ((0)) FOR [SPContractualsFinancialReportingID]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Contr__27DE4C6F] DEFAULT ('') FOR [SPContractualsFinancialReporting]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Prima__240DBB8B] DEFAULT ((0)) FOR [SPPrimaryStatisticFinancialReportingID]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Prima__28D270A8] DEFAULT ('') FOR [SPPrimaryStatisticFinancialReporting]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Prima__0B4CFAB9] DEFAULT ('') FOR [SPPrimaryStatisticFinancialReportingLineName]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Secon__2501DFC4] DEFAULT ((0)) FOR [SPSecondaryStatisticFinancialReportingID]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Secon__29C694E1] DEFAULT ('') FOR [SPSecondaryStatisticFinancialReporting]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Secon__0C411EF2] DEFAULT ('') FOR [SPSecondaryStatisticFinancialReportingLineName]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Terti__25F603FD] DEFAULT ((0)) FOR [SPTertiaryStatisticFinancialReportingID]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Terti__2ABAB91A] DEFAULT ('') FOR [SPTertiaryStatisticFinancialReporting]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Terti__0D35432B] DEFAULT ('') FOR [SPTertiaryStatisticFinancialReportingLineName]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPCh__271FFDB7] DEFAULT ((0)) FOR [CAPChargesFinancialReportingID]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPCh__2AF08E9B] DEFAULT ('') FOR [CAPChargesFinancialReporting]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPCo__281421F0] DEFAULT ((0)) FOR [CAPContractualsFinancialReportingID]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPCo__2BE4B2D4] DEFAULT ('') FOR [CAPContractualsFinancialReporting]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPPr__29084629] DEFAULT ((0)) FOR [CAPPrimaryStatisticFinancialReportingID]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPPr__2CD8D70D] DEFAULT ('') FOR [CAPPrimaryStatisticFinancialReporting]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPSe__29FC6A62] DEFAULT ((0)) FOR [CAPSecondaryStatisticFinancialReportingID]; GO
ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPSe__2DCCFB46] DEFAULT ('') FOR [CAPSecondaryStatisticFinancialReporting]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPatientTypeRollupPH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPatientTypeRollupPH] (
    [PatientTypeRollupPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([PatientTypeRollupPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPatientTypeRollupPH] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimPatientTypeRollupPH] ADD CONSTRAINT [DF__FW_DimPatientTypeRollupPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimPatientTypeRollupPH] ADD CONSTRAINT [DF__DimPatien__Histo__1D60BDFC] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimPatientTypeRollupPH] ADD CONSTRAINT [DF__DimPatient__Name__1B78758A] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimPatientTypeRollupPH] ADD CONSTRAINT [DF__DimPatien__Membe__1C6C99C3] DEFAULT (newid()) FOR [MemberGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPayCode ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPayCode] (
    [PayCodeID] smallint NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(203) NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [PayCode] nvarchar(100) NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [PayCodeGroup] nvarchar(100) NOT NULL,
    [PayCodeGroupSortOrder] int NOT NULL,
    [PayClass] nvarchar(100) NOT NULL,
    [ProductiveClass] nvarchar(200) NOT NULL,
    [IsAccrued] bit NOT NULL,
    [IsHoursIgnored] bit NOT NULL,
    [IsDollarsIgnored] bit NOT NULL,
    [DSSIsDefined] bit NOT NULL,
    [DSSCostingRollup] nvarchar(50) NOT NULL,
    [OBIsDefined] bit NOT NULL,
    [OBForecastDetailID] int NOT NULL,
    [SPIsDefined] bit NOT NULL,
    [ImportIDAlt] nvarchar(100) NOT NULL,
    [IsPayCodeGroup] bit NOT NULL,
    [Rollup] nvarchar(100) NOT NULL,
    [SubRollup] nvarchar(100) NOT NULL,
    [FlexBucketGUID] uniqueidentifier NOT NULL,
    [Variability] money NOT NULL,
    [ReportingCategory] nvarchar(100) NOT NULL,
    [TransactionID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [DSSCostingRollup2] nvarchar(100) NOT NULL,
    [FWIsDefined] bit NOT NULL,
    [DSSPayCodeRollup2ID] int NOT NULL,
    [DSSPayCodeRollup2] nvarchar(100) NOT NULL,
    [DSSPayCodeRollup1] nvarchar(200) NOT NULL,
    [DSSPayCodeRollup1ID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [SPHPayCodeRollupName] nvarchar(100) NOT NULL,
    [SPHProductiveClass] nvarchar(100) NOT NULL,
    [ProviderLineItem] nvarchar(200) NOT NULL,
    [SPHPayCodeRollupIsValidated] bit NOT NULL,
    [SPHPayCodeRollupID] int NOT NULL,
    [SPHPayCodeRollupConfidenceScore] float NOT NULL,
    PRIMARY KEY ([PayCodeID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_PayCode] ON [fw].[DimPayCode] ([PayCode]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_MemberGUID] ON [fw].[DimPayCode] ([MemberGUID]);
CREATE NONCLUSTERED INDEX [NCNU_StaffingReconciliation] ON [fw].[DimPayCode] ([PayCodeID], [PayCodeGroupID], [IsDollarsIgnored], [IsHoursIgnored]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_PayCode] ON [fw].[DimPayCode] ([PayCode]) INCLUDE ([PayCodeID]);
GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__Provi__0327EDCB] DEFAULT ('') FOR [ProviderLineItem]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__SPHPa__0995BF8F] DEFAULT ((0)) FOR [SPHPayCodeRollupIsValidated]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__FWIsD__0A043459] DEFAULT ((0)) FOR [FWIsDefined]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__Provi__0A8781C3] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__DSSPa__16B5BAAF] DEFAULT ('') FOR [DSSPayCodeRollup1]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__DSSPa__240FB5CD] DEFAULT ((0)) FOR [DSSPayCodeRollup1ID]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__DSSPa__31D2F9E8] DEFAULT ((0)) FOR [DSSPayCodeRollup2ID]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__DSSPa__32C71E21] DEFAULT ('') FOR [DSSPayCodeRollup2]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__DSSCo__39F27346] DEFAULT ('') FOR [DSSCostingRollup2]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__SPHPa__3BC08152] DEFAULT ('') FOR [SPHPayCodeRollupName]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__SPHPr__3CB4A58B] DEFAULT ('') FOR [SPHProductiveClass]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__SPHPa__3DD47DA4] DEFAULT ((0)) FOR [SPHPayCodeRollupID]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__SPHPa__3EC8A1DD] DEFAULT ((0)) FOR [SPHPayCodeRollupConfidenceScore]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_Description] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_ImportID1] DEFAULT ('') FOR [PayCode]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_PayCodeGroupID] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__PayCo__2ECB0F56] DEFAULT ('') FOR [PayCodeGroup]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__PayCo__2FBF338F] DEFAULT ((0)) FOR [PayCodeGroupSortOrder]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__PayCl__30B357C8] DEFAULT ('') FOR [PayClass]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__Produ__2DD6EB1D] DEFAULT ('') FOR [ProductiveClass]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__IsAcc__27BF4DFF] DEFAULT ((1)) FOR [IsAccrued]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_IsHoursIgnored] DEFAULT ((0)) FOR [IsHoursIgnored]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__IsDol__2451AB60] DEFAULT ((0)) FOR [IsDollarsIgnored]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__DSSIs__5DBF32E6] DEFAULT ((0)) FOR [DSSIsDefined]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__DSSCo__7377A163] DEFAULT ('') FOR [DSSCostingRollup]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__OBIsD__5EB3571F] DEFAULT ((0)) FOR [OBIsDefined]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__OBFor__1DC70B67] DEFAULT ((0)) FOR [OBForecastDetailID]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__SPIsD__5FA77B58] DEFAULT ((0)) FOR [SPIsDefined]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_ImportID2] DEFAULT ('') FOR [ImportIDAlt]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_IsPayCodeGroup] DEFAULT ((0)) FOR [IsPayCodeGroup]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_Rollup1] DEFAULT ('') FOR [Rollup]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_Rollup2] DEFAULT ('') FOR [SubRollup]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__FlexB__254BC6BD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FlexBucketGUID]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__Varia__02228611] DEFAULT ((0)) FOR [Variability]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__Repor__2B0CC343] DEFAULT ('') FOR [ReportingCategory]; GO
ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__FW_DimPayCode_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPayCodeGroup ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPayCodeGroup] (
    [PayCodeGroupID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    [PayCodeGroupCode] nvarchar(100) NOT NULL,
    [PayClass] nvarchar(100) NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [IsVariable] bit NOT NULL,
    [IsOvertime] bit NOT NULL,
    [IsAgency] bit NOT NULL,
    [IsExcludedFromBenefits] bit NOT NULL,
    [WageRateMultiplier] decimal NOT NULL,
    [DefaultPayCodeID] int NOT NULL,
    [ReportingCategory] nvarchar(100) NOT NULL,
    [AccountID] int NOT NULL,
    [TransactionID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [IsDirect] bit NOT NULL,
    [IsPremium] bit NOT NULL,
    PRIMARY KEY ([PayCodeGroupID])
);

CREATE UNIQUE NONCLUSTERED INDEX [UQ__DimPayCo__A67B38530990CDEA] ON [fw].[DimPayCodeGroup] ([MemberGUID]);
CREATE NONCLUSTERED INDEX [IX_PayCodeGroupID] ON [fw].[DimPayCodeGroup] ([PayCodeGroupID]);
GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__Histo__0D615ECE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__IsDir__3A42B4F7] DEFAULT ((0)) FOR [IsDirect]; GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__IsPre__5FA0B8DD] DEFAULT ((0)) FOR [IsPremium]; GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__Membe__0B79165C] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCode__Name__0C6D3A95] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF_DimPayCodeGroup_PayCodeSortOrder] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF_DimPayCodeGroup_PayCodeGroupCode] DEFAULT ('') FOR [PayCodeGroupCode]; GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF_DimPayCodeGroup_PayClass] DEFAULT ('') FOR [PayClass]; GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__Produ__281D4670] DEFAULT ((0)) FOR [ProductiveClassID]; GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__IsVar__1D17A25A] DEFAULT ((0)) FOR [IsVariable]; GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__IsOve__38209E51] DEFAULT ((0)) FOR [IsOvertime]; GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__IsAge__372C7A18] DEFAULT ((0)) FOR [IsAgency]; GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__IsExc__46C2F80C] DEFAULT ((0)) FOR [IsExcludedFromBenefits]; GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__WageR__58D2C29C] DEFAULT ((1)) FOR [WageRateMultiplier]; GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__Defau__54D2B6EF] DEFAULT ((0)) FOR [DefaultPayCodeID]; GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__Repor__30C59C99] DEFAULT ('') FOR [ReportingCategory]; GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF_DimPayCodeGroup_AccountID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__FW_DimPayCodeGroup_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPayCodeGroupPH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPayCodeGroupPH] (
    [PayCodeGroupPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([PayCodeGroupPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPayCodeGroupPH] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimPayCodeGroupPH] ADD CONSTRAINT [DF__DimPayCod__Histo__5DB1E3E9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimPayCodeGroupPH] ADD CONSTRAINT [DF__DimPayCode__Name__5BC99B77] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimPayCodeGroupPH] ADD CONSTRAINT [DF__DimPayCod__Membe__5CBDBFB0] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPayCodeGroupPH] ADD CONSTRAINT [DF__DimPayCod__Trans__5EA60822] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPayCycle ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPayCycle] (
    [PayCycleID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Code] nvarchar(200) NOT NULL,
    [SortOrder] int NOT NULL,
    [AccrualMethod] nvarchar(100) NOT NULL,
    [PeriodDays] tinyint NOT NULL,
    [FirstPayPeriodStartDate] datetime NOT NULL,
    [CurrentPayPeriodID] smallint NOT NULL,
    PRIMARY KEY ([PayCycleID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPayCycle] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCyc__Curre__2D778DC8] DEFAULT ((0)) FOR [CurrentPayPeriodID]; GO
ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCyc__Histo__3F88EF06] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCycl__Name__3DA0A694] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCyc__Membe__3E94CACD] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCyc__Trans__407D133F] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCycl__Code__41713778] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCyc__SortO__42655BB1] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCyc__Accru__43597FEA] DEFAULT ('') FOR [AccrualMethod]; GO
ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCyc__Perio__444DA423] DEFAULT ((0)) FOR [PeriodDays]; GO
ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCyc__First__4541C85C] DEFAULT (getdate()) FOR [FirstPayPeriodStartDate]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPayPeriod ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPayPeriod] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [PayPeriodID] smallint NOT NULL,
    [PayPeriodCode] nvarchar(100) NULL,
    [PeriodNumber] tinyint NOT NULL,
    [PeriodStartCalendarDate] datetime NULL,
    [PeriodEndCalendarDate] datetime NOT NULL,
    [PeriodDays] tinyint NOT NULL,
    [FiscalMonthIDStart] int NULL,
    [FiscalMonthIDSecond] int NULL,
    [CalendarDaysStart] int NULL,
    [CalendarDaysSecond] int NULL,
    [PeriodDaysStart] int NULL,
    [PeriodDaysSecond] int NULL,
    [PeriodWeightStart] numeric NULL,
    [PeriodWeightSecond] numeric NULL,
    [DaysInPeriodWeightStart] numeric NULL,
    [DaysInPeriodWeightSecond] numeric NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [FiscalYearIDStart] int NOT NULL,
    [FiscalYearIDSecond] int NOT NULL,
    [Name] nvarchar(350) NULL,
    [TransactionID] int NOT NULL,
    [WorkingDays] tinyint NOT NULL,
    [WorkingDaysInPeriodStart] int NULL,
    [WorkingDaysInPeriodSecond] int NULL,
    [WorkingDaysInPeriodWeightStart] float NULL,
    [WorkingDaysInPeriodWeightSecond] float NULL,
    [PayCycleID] int NOT NULL,
    [Code] nvarchar(350) NOT NULL,
    [PayCycleName] nvarchar(200) NOT NULL,
    [PayCycleCode] nvarchar(200) NOT NULL,
    [PayCycleSortOrder] int NOT NULL,
    [AccrualMethod] nvarchar(100) NOT NULL,
    [IsCurrentPayPeriod] bit NOT NULL,
    [CountFromCurrentPayPeriod] int NOT NULL,
    PRIMARY KEY ([PayPeriodID])
);

CREATE UNIQUE NONCLUSTERED INDEX [UQ__DimDimPa__A67B38536BC073E1] ON [fw].[DimPayPeriod] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF_FWDIMPAYPERIODPERIODNUMBER] DEFAULT ((0)) FOR [PeriodNumber]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF_FWDIMPAYPERIODWORKINGDAYS] DEFAULT ((10)) FOR [WorkingDays]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__FW_DimPayPeriod_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__Count__290C08E3] DEFAULT ((0)) FOR [CountFromCurrentPayPeriod]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__Fisca__2B38DEE6] DEFAULT ((0)) FOR [FiscalYearIDStart]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__Fisca__2C2D031F] DEFAULT ((0)) FOR [FiscalYearIDSecond]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF_DimPayPeriod_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__IsCur__48EEC890] DEFAULT ((0)) FOR [IsCurrentPayPeriod]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__PayCy__49125940] DEFAULT ((0)) FOR [PayCycleID]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPeri__Code__4A067D79] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF_DimPayPeriod_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF_DimPayPeriod_PeriodEndCalendarDate] DEFAULT (getdate()) FOR [PeriodEndCalendarDate]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF_DimPayPeriod_DaysInPayPeriod] DEFAULT ((14)) FOR [PeriodDays]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPeri__Name__627E58A2] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__PayCy__63C64F7C] DEFAULT ('') FOR [PayCycleName]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__PayCy__64BA73B5] DEFAULT ('') FOR [PayCycleCode]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__PayCy__65AE97EE] DEFAULT ((0)) FOR [PayCycleSortOrder]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__Accru__66A2BC27] DEFAULT ('') FOR [AccrualMethod]; GO
ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF_FWDIMPAYPERIODPAYPERIODCODE] DEFAULT ('') FOR [PayPeriodCode]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPayor ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPayor] (
    [PayorID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(253) NOT NULL,
    [Description] nvarchar(200) NOT NULL,
    [DescriptionLong] nvarchar(200) NOT NULL,
    [PayorCode] nvarchar(50) NOT NULL,
    [PayorGroupID] int NOT NULL,
    [FinancialClassID] int NOT NULL,
    [FinancialClass] nvarchar(30) NOT NULL,
    [IsDSS] bit NOT NULL,
    [IsOB] bit NOT NULL,
    [TransactionID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [OBDefaultInpatientReimbursementMethod] nvarchar(100) NOT NULL,
    [OBDefaultOutpatientReimbursementMethod] nvarchar(100) NOT NULL,
    PRIMARY KEY ([PayorID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPayor] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [FK_DimPayor_PayorGroup] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO
ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__Member__2B6B870B] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__Descri__777F9E76] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__Descri__7873C2AF] DEFAULT ('') FOR [DescriptionLong]; GO
ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__PayorC__7967E6E8] DEFAULT ('') FOR [PayorCode]; GO
ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__PayorG__7A6B8A59] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__Financ__7A5C0B21] DEFAULT ((0)) FOR [FinancialClassID]; GO
ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF_DimPayor_FinancialClass] DEFAULT ('') FOR [FinancialClass]; GO
ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__IsDSS__07A5ED7A] DEFAULT ((0)) FOR [IsDSS]; GO
ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__IsOB__06B1C941] DEFAULT ((0)) FOR [IsOB]; GO
ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__FW_DimPayor_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__OBDefa__42167EE4] DEFAULT ('Per IP Volume') FOR [OBDefaultInpatientReimbursementMethod]; GO
ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__OBDefa__430AA31D] DEFAULT ('Per OP Volume') FOR [OBDefaultOutpatientReimbursementMethod]; GO
ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__Histor__7B502F5A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPayorGroup ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPayorGroup] (
    [PayorGroupID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Category] nvarchar(200) NOT NULL,
    [ReimbursementType] nvarchar(200) NOT NULL,
    [PayorGroupCode] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    [IsCapital] bit NOT NULL,
    [CAPChargesFinancialReportingID] int NOT NULL,
    [CAPChargesFinancialReporting] varchar(4000) NOT NULL,
    [CAPContractualsFinancialReportingID] int NOT NULL,
    [CAPContractualsFinancialReporting] varchar(200) NOT NULL,
    [IsDSS] bit NOT NULL,
    [IsOB] bit NOT NULL,
    [IsMR] bit NOT NULL,
    [IsSP] bit NOT NULL,
    [SPHCRType] nvarchar(100) NOT NULL,
    [SPHCRPayorID] int NOT NULL,
    [SPHCRPayor] nvarchar(200) NOT NULL,
    [SPChargesFinancialReportingID] int NOT NULL,
    [SPChargesFinancialReporting] varchar(200) NOT NULL,
    [SPContractualsFinancialReportingID] int NOT NULL,
    [SPContractualsFinancialReporting] varchar(200) NOT NULL,
    [SPDefaultInpatientReimbursementMethod] nvarchar(100) NOT NULL,
    [SPDefaultOutpatientReimbursementMethod] nvarchar(100) NOT NULL,
    [SPDefaultClinicReimbursementMethod] nvarchar(100) NOT NULL,
    [SPCMISamplingSourceType] int NOT NULL,
    [SPCMISamplingAccountID] int NOT NULL,
    [TransactionID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [OBDefaultInpatientReimbursementMethod] nvarchar(100) NOT NULL,
    [OBDefaultOutpatientReimbursementMethod] nvarchar(100) NOT NULL,
    PRIMARY KEY ([PayorGroupID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPayorGroup] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimPayorGroup] ([Name]);
GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__Membe__4F812C54] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorGr__Name__5075508D] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__Categ__79059230] DEFAULT ('') FOR [Category]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__Reimb__79F9B669] DEFAULT ('') FOR [ReimbursementType]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__Payor__545B539E] DEFAULT ('') FOR [PayorGroupCode]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SortO__00A6B3F8] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__IsCap__2A471CB2] DEFAULT ((0)) FOR [IsCapital]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__CAPCh__665478E7] DEFAULT ((0)) FOR [CAPChargesFinancialReportingID]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__CAPCh__67489D20] DEFAULT ('') FOR [CAPChargesFinancialReporting]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__CAPCo__683CC159] DEFAULT ((0)) FOR [CAPContractualsFinancialReportingID]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__CAPCo__6930E592] DEFAULT ('') FOR [CAPContractualsFinancialReporting]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__IsDSS__2D23895D] DEFAULT ((0)) FOR [IsDSS]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorGr__IsOB__2B3B40EB] DEFAULT ((0)) FOR [IsOB]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorGr__IsMR__2C2F6524] DEFAULT ((0)) FOR [IsMR]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorGr__IsSP__2952F879] DEFAULT ((0)) FOR [IsSP]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPHCR__79625787] DEFAULT ('') FOR [SPHCRType]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPHCR__50158FA4] DEFAULT ((0)) FOR [SPHCRPayorID]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPHCR__4F216B6B] DEFAULT ('') FOR [SPHCRPayor]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPCha__262CA4D5] DEFAULT ((0)) FOR [SPChargesFinancialReportingID]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPCha__2AF159F2] DEFAULT ('') FOR [SPChargesFinancialReporting]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPCon__2720C90E] DEFAULT ((0)) FOR [SPContractualsFinancialReportingID]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPCon__2BE57E2B] DEFAULT ('') FOR [SPContractualsFinancialReporting]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPDef__18A989A6] DEFAULT ('Per Diem') FOR [SPDefaultInpatientReimbursementMethod]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPDef__199DADDF] DEFAULT ('% of Charge') FOR [SPDefaultOutpatientReimbursementMethod]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPDef__1A91D218] DEFAULT ('% of Charge') FOR [SPDefaultClinicReimbursementMethod]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPCMI__6A7A0F86] DEFAULT ((0)) FOR [SPCMISamplingSourceType]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPCMI__6B6E33BF] DEFAULT ((0)) FOR [SPCMISamplingAccountID]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__FW_DimPayorGroup_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__Histo__516974C6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__OBDef__61CE5608] DEFAULT ('Per Diem') FOR [OBDefaultInpatientReimbursementMethod]; GO
ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__OBDef__62C27A41] DEFAULT ('% of Charge') FOR [OBDefaultOutpatientReimbursementMethod]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPayorGroupPH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPayorGroupPH] (
    [PayorGroupPHID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([PayorGroupPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPayorGroupPH] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimPayorGroupPH] ADD CONSTRAINT [DF__FW_DimPayorGroupPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimPayorGroupPH] ADD CONSTRAINT [DF__DimPayorG__Membe__562E29E3] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPayorGroupPH] ADD CONSTRAINT [DF__DimPayorGr__Name__57224E1C] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimPayorGroupPH] ADD CONSTRAINT [DF__DimPayorG__Histo__58167255] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPayorPH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPayorPH] (
    [PayorPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([PayorPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPayorPH] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimPayorPH] ADD CONSTRAINT [DF__FW_DimPayorPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimPayorPH] ADD CONSTRAINT [DF__DimPayorPH__Name__31246061] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimPayorPH] ADD CONSTRAINT [DF__DimPayorP__Membe__3218849A] DEFAULT (newid()) FOR [MemberGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPhysicianGroup ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPhysicianGroup] (
    [PhysicianGroupID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Category] nvarchar(200) NOT NULL,
    [Subcategory] nvarchar(200) NOT NULL,
    [PhysicianType] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    [IsCapital] bit NOT NULL,
    [IsDSS] bit NOT NULL,
    [IsMR] bit NOT NULL,
    [IsOB] bit NOT NULL,
    [IsSP] bit NOT NULL,
    [SPSalariesFinancialReportingID] int NOT NULL,
    [SPSalariesFinancialReporting] nvarchar(100) NOT NULL,
    [SPFTEsFinancialReportingID] int NOT NULL,
    [SPFTEsFinancialReporting] varchar(200) NOT NULL,
    [TransactionID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [SPSalariesVolumeDriverID] int NOT NULL,
    [SPSalariesVolumeDriver] nvarchar(100) NOT NULL,
    [SPPhysicianBenefitsTypeID] int NOT NULL,
    [SPPhysicianBenefitsType] nvarchar(100) NOT NULL,
    [WorkWeekOverrideID] int NOT NULL,
    PRIMARY KEY ([PhysicianGroupID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPhysicianGroup] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimPhysicianGroup] ([Name]);
GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__FW_DimPhysicianGroup_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__SPSal__28CD1311] DEFAULT ((0)) FOR [SPSalariesVolumeDriverID]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__SPSal__29C1374A] DEFAULT ('') FOR [SPSalariesVolumeDriver]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__SPPhy__2AB55B83] DEFAULT ((0)) FOR [SPPhysicianBenefitsTypeID]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__SPPhy__2BA97FBC] DEFAULT ('') FOR [SPPhysicianBenefitsType]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__Membe__0F1C8E7C] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__Physi__3A7100D5] DEFAULT ('Not specified') FOR [Name]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__Categ__26CC5CE0] DEFAULT ('') FOR [Category]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__Subca__27C08119] DEFAULT ('') FOR [Subcategory]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__Physi__7B4A9FF9] DEFAULT ('') FOR [PhysicianType]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__SortO__28B4A552] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__IsCap__48BCEFF1] DEFAULT ((1)) FOR [IsCapital]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__IsDSS__4B995C9C] DEFAULT ((1)) FOR [IsDSS]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysici__IsMR__4AA53863] DEFAULT ((1)) FOR [IsMR]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysici__IsOB__49B1142A] DEFAULT ((1)) FOR [IsOB]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysici__IsSP__47C8CBB8] DEFAULT ((1)) FOR [IsSP]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__Salar__71F4DB05] DEFAULT ((0)) FOR [SPSalariesFinancialReportingID]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__Salar__72E8FF3E] DEFAULT ('') FOR [SPSalariesFinancialReporting]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__SPFTE__0773138B] DEFAULT ((0)) FOR [SPFTEsFinancialReportingID]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__SPFTE__086737C4] DEFAULT ('') FOR [SPFTEsFinancialReporting]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__Histo__3B65250E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__WorkW__7A282FE2] DEFAULT ((-1)) FOR [WorkWeekOverrideID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPhysicianGroupPH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPhysicianGroupPH] (
    [PhysicianGroupPHID] int NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([PhysicianGroupPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPhysicianGroupPH] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimPhysicianGroupPH] ADD CONSTRAINT [DF__DimPhysic__Membe__1010B2B5] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPhysicianGroupPH] ADD CONSTRAINT [DF__FW_DimPhysicianGroupPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimPhysicianGroupPH] ADD CONSTRAINT [DF__DimPhysic__Physi__4029DA2B] DEFAULT ('Not specified') FOR [Name]; GO
ALTER TABLE [fw].[DimPhysicianGroupPH] ADD CONSTRAINT [DF__DimPhysic__Histo__411DFE64] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPhysicianPH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPhysicianPH] (
    [PhysicianPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([PhysicianPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPhysicianPH] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimPhysicianPH] ADD CONSTRAINT [DF__DimPhysic__Histo__4C8063A2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimPhysicianPH] ADD CONSTRAINT [DF__DimPhysici__Name__4A981B30] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimPhysicianPH] ADD CONSTRAINT [DF__DimPhysic__Membe__4B8C3F69] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPhysicianPH] ADD CONSTRAINT [DF__DimPhysic__Trans__4D7487DB] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPhysicianSpecialty ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPhysicianSpecialty] (
    [PhysicianSpecialtyID] int NOT NULL,
    [Name] nvarchar(203) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [PhysicianSpecialtyCode] nvarchar(100) NOT NULL,
    [SpecialtyGroup] nvarchar(100) NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [RVUTarget] nvarchar(100) NOT NULL,
    PRIMARY KEY ([PhysicianSpecialtyID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPhysicianSpecialty] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimPhysicianSpecialty] ADD CONSTRAINT [DF__DimPhysic__Membe__0F775562] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPhysicianSpecialty] ADD CONSTRAINT [DF__DimPhysic__Trans__115F9DD4] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimPhysicianSpecialty] ADD CONSTRAINT [DF__DimPhysic__Physi__1253C20D] DEFAULT ('') FOR [PhysicianSpecialtyCode]; GO
ALTER TABLE [fw].[DimPhysicianSpecialty] ADD CONSTRAINT [DF__DimPhysic__Speci__1347E646] DEFAULT ('') FOR [SpecialtyGroup]; GO
ALTER TABLE [fw].[DimPhysicianSpecialty] ADD CONSTRAINT [DF__DimPhysic__Descr__143C0A7F] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimPhysicianSpecialty] ADD CONSTRAINT [DF__DimPhysic__Histo__106B799B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimPhysicianSpecialty] ADD CONSTRAINT [DF__DimPhysic__RVUTa__5F933816] DEFAULT ('') FOR [RVUTarget]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPositionType ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPositionType] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [PositionTypeID] int NOT NULL,
    [Name] nvarchar(255) NOT NULL,
    [TransactionID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [PositionTypeAssignmentTypeID] int NOT NULL,
    PRIMARY KEY ([PositionTypeID])
);
GO
ALTER TABLE [fw].[DimPositionType] ADD CONSTRAINT [DF__DimPositi__Histo__3F33B352] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimPositionType] ADD CONSTRAINT [DF__DimPositio__Name__411BFBC4] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimPositionType] ADD CONSTRAINT [DF__DimPositi__Trans__42101FFD] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimPositionType] ADD CONSTRAINT [DF__DimPositi__Membe__43044436] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimPositionType] ADD CONSTRAINT [DF__DimPositi__Posit__43F8686F] DEFAULT ((1)) FOR [PositionTypeAssignmentTypeID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimPositionTypeAssignmentType ------------------
---------------------------------------------
CREATE TABLE [fw].[DimPositionTypeAssignmentType] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [PositionTypeAssignmentTypeID] int NOT NULL,
    [Name] nvarchar(255) NOT NULL,
    [TransactionID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([PositionTypeAssignmentTypeID])
);
GO
ALTER TABLE [fw].[DimPositionTypeAssignmentType] ADD CONSTRAINT [DF__DimPositi__Histo__397AD9FC] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimPositionTypeAssignmentType] ADD CONSTRAINT [DF__DimPositio__Name__3B63226E] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimPositionTypeAssignmentType] ADD CONSTRAINT [DF__DimPositi__Trans__3C5746A7] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimPositionTypeAssignmentType] ADD CONSTRAINT [DF__DimPositi__Membe__3D4B6AE0] DEFAULT (newid()) FOR [MemberGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimProductiveClass ------------------
---------------------------------------------
CREATE TABLE [fw].[DimProductiveClass] (
    [ProductiveClassID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [SortOrder] int NOT NULL,
    PRIMARY KEY ([ProductiveClassID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimProductiveClass] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimProductiveClass] ADD CONSTRAINT [DF__FW_DimProductiveClass_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimProductiveClass] ADD CONSTRAINT [DF__DimProduc__Histo__1D9FB7FD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimProductiveClass] ADD CONSTRAINT [DF__DimProduct__Name__1BB76F8B] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimProductiveClass] ADD CONSTRAINT [DF__DimProduc__Membe__1CAB93C4] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimProductiveClass] ADD CONSTRAINT [DF_DimProductiveClass_SortOrder] DEFAULT ((0)) FOR [SortOrder]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimProgram ------------------
---------------------------------------------
CREATE TABLE [fw].[DimProgram] (
    [ProgramID] int NOT NULL,
    [Name] nvarchar(203) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Code] nvarchar(100) NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    PRIMARY KEY ([ProgramID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimProgram] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimProgram] ADD CONSTRAINT [DF__DimProgra__Membe__3629A1FE] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimProgram] ADD CONSTRAINT [DF__DimProgra__Histo__371DC637] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimProgram] ADD CONSTRAINT [DF__DimProgra__Trans__3811EA70] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimProgram] ADD CONSTRAINT [DF__DimProgram__Code__39060EA9] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimProgram] ADD CONSTRAINT [DF__DimProgra__Descr__39FA32E2] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimProgram] ADD CONSTRAINT [DF__DimProgra__SortO__3AEE571B] DEFAULT ((0)) FOR [SortOrder]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimProject ------------------
---------------------------------------------
CREATE TABLE [fw].[DimProject] (
    [ProjectID] int NOT NULL,
    [Name] nvarchar(203) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [SortOrder] int NOT NULL,
    [Code] nvarchar(100) NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    PRIMARY KEY ([ProjectID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimProject] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimProject] ADD CONSTRAINT [DF__DimProjec__Histo__3EBEE7FF] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimProject] ADD CONSTRAINT [DF__DimProjec__Membe__3DCAC3C6] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimProject] ADD CONSTRAINT [DF__DimProjec__Trans__3FB30C38] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimProject] ADD CONSTRAINT [DF__DimProjec__SortO__40A73071] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimProject] ADD CONSTRAINT [DF__DimProject__Code__419B54AA] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimProject] ADD CONSTRAINT [DF__DimProjec__Descr__428F78E3] DEFAULT ('') FOR [Description]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimProvider ------------------
---------------------------------------------
CREATE TABLE [fw].[DimProvider] (
    [ProviderID] int NOT NULL,
    [Type] nvarchar(100) NOT NULL,
    [NameFirst] nvarchar(100) NOT NULL,
    [NameLast] nvarchar(100) NOT NULL,
    [ProviderName] nvarchar(202) NOT NULL,
    [ProviderCode] nvarchar(100) NOT NULL,
    [PhysicianSpecialtyID] int NOT NULL,
    [StateLicenseNumber] nvarchar(100) NOT NULL,
    [NPI] nvarchar(100) NOT NULL,
    [GroupAffiliaition] nvarchar(100) NOT NULL,
    [DSSIsDefined] bit NOT NULL,
    [OBIsDefined] bit NOT NULL,
    [OBIsActive] bit NOT NULL,
    [IsEmployee] bit NOT NULL,
    [OBVolumeTarget1] decimal NOT NULL,
    [OBVolumeTarget2] decimal NOT NULL,
    [OBTier1Threshold] decimal NOT NULL,
    [OBTier2Threshold] decimal NOT NULL,
    [OBTier3Threshold] decimal NOT NULL,
    [OBTier4Threshold] int NOT NULL,
    [OBTier5Threshold] int NOT NULL,
    [OBTier6Threshold] int NOT NULL,
    [OBTier1Rate] money NOT NULL,
    [OBTier2Rate] money NOT NULL,
    [OBTier3Rate] money NOT NULL,
    [OBTier4Rate] money NOT NULL,
    [OBTier5Rate] money NOT NULL,
    [OBTier6Rate] money NOT NULL,
    [BasePay] money NOT NULL,
    [PayRate] money NOT NULL,
    [CompensationMethod] nvarchar(100) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [WorkWeekOverrideID] int NOT NULL,
    [IsPhysician] int NOT NULL,
    [Name] nvarchar(304) NOT NULL,
    [IsVariable] bit NOT NULL,
    [OBVolumeTarget3] decimal NOT NULL,
    PRIMARY KEY ([ProviderID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimProvider] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__Histo__2690903B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__WorkW__22DE9604] DEFAULT ((-1)) FOR [WorkWeekOverrideID]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBVol__46C02E44] DEFAULT ((0)) FOR [OBVolumeTarget3]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__IsVar__47BE741E] DEFAULT ((0)) FOR [IsVariable]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvide__Type__296CFCE6] DEFAULT ('') FOR [Type]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__NameF__423CA363] DEFAULT ('') FOR [NameFirst]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__NameL__4330C79C] DEFAULT ('') FOR [NameLast]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__Provi__2E31B203] DEFAULT ('') FOR [ProviderCode]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__Physi__310E1EAE] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__State__320242E7] DEFAULT ('') FOR [StateLicenseNumber]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvider__NPI__32F66720] DEFAULT ('') FOR [NPI]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__Group__33EA8B59] DEFAULT ('') FOR [GroupAffiliaition]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__DSSIs__00B5CB6D] DEFAULT ((0)) FOR [DSSIsDefined]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBIsD__7FC1A734] DEFAULT ((0)) FOR [OBIsDefined]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBIsA__2D3D8DCA] DEFAULT ((1)) FOR [OBIsActive]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__IsEmp__3019FA75] DEFAULT ((0)) FOR [IsEmployee]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBVol__2B6B1F48] DEFAULT ((0)) FOR [OBVolumeTarget1]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBVol__2C5F4381] DEFAULT ((0)) FOR [OBVolumeTarget2]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__7CE53A89] DEFAULT ((0)) FOR [OBTier1Threshold]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__7DD95EC2] DEFAULT ((0)) FOR [OBTier2Threshold]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__7ECD82FB] DEFAULT ((0)) FOR [OBTier3Threshold]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__55703EBF] DEFAULT ((0)) FOR [OBTier4Threshold]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__566462F8] DEFAULT ((0)) FOR [OBTier5Threshold]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OTTie__57588731] DEFAULT ((0)) FOR [OBTier6Threshold]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__Thres__2B554558] DEFAULT ((0)) FOR [OBTier1Rate]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__7AFCF217] DEFAULT ((0)) FOR [OBTier2Rate]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__7BF11650] DEFAULT ((0)) FOR [OBTier3Rate]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__5293D214] DEFAULT ((0)) FOR [OBTier4Rate]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__5387F64D] DEFAULT ((0)) FOR [OBTier5Rate]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__547C1A86] DEFAULT ((0)) FOR [OBTier6Rate]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__BaseP__2878D8AD] DEFAULT ((0)) FOR [BasePay]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__PayRa__2C496991] DEFAULT ((0)) FOR [PayRate]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__Compe__2A61211F] DEFAULT ('') FOR [CompensationMethod]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__Membe__259C6C02] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__Trans__2784B474] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimProviderPH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimProviderPH] (
    [ProviderPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([ProviderPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimProviderPH] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimProviderPH] ADD CONSTRAINT [DF__DimProvide__Name__39A364AF] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimProviderPH] ADD CONSTRAINT [DF__DimProvid__Membe__3A9788E8] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimProviderPH] ADD CONSTRAINT [DF__DimProvid__Trans__3C7FD15A] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimProviderPH] ADD CONSTRAINT [DF__DimProvid__Histo__3B8BAD21] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimQuarter ------------------
---------------------------------------------
CREATE TABLE [fw].[DimQuarter] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [QuarterID] tinyint NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([QuarterID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimQuarter] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimQuarter] ADD CONSTRAINT [DF__FW_DimQuarter_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimQuarter] ADD CONSTRAINT [DF_DimQuarter_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimQuarter] ADD CONSTRAINT [DF_DimQuarter_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimQuarter] ADD CONSTRAINT [DF_DimQuarter_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimReportDetailType ------------------
---------------------------------------------
CREATE TABLE [fw].[DimReportDetailType] (
    [ReportDetailTypeID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [TableName] nvarchar(200) NOT NULL,
    PRIMARY KEY ([ReportDetailTypeID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimReportDetailType] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimReportDetailType] ADD CONSTRAINT [DF__DimReport__Histo__78A799BF] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimReportDetailType] ADD CONSTRAINT [DF__DimReportD__Name__76BF514D] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimReportDetailType] ADD CONSTRAINT [DF__DimReport__Membe__77B37586] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimReportDetailType] ADD CONSTRAINT [DF__DimReport__Trans__799BBDF8] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimReportDetailType] ADD CONSTRAINT [DF__DimReport__Table__7A8FE231] DEFAULT ('') FOR [TableName]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimResearchDepartmentCategory ------------------
---------------------------------------------
CREATE TABLE [fw].[DimResearchDepartmentCategory] (
    [ResearchDepartmentCategoryID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [SortOrder] int NOT NULL,
    PRIMARY KEY ([ResearchDepartmentCategoryID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimResearchDepartmentCategory] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimResearchDepartmentCategory] ADD CONSTRAINT [DF__DimResear__Histo__7DD4CC82] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimResearchDepartmentCategory] ADD CONSTRAINT [DF__DimResearc__Name__7BEC8410] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimResearchDepartmentCategory] ADD CONSTRAINT [DF__DimResear__Membe__7CE0A849] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimResearchDepartmentCategory] ADD CONSTRAINT [DF__DimResear__Trans__7EC8F0BB] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimResearchDepartmentCategory] ADD CONSTRAINT [DF__DimResear__SortO__7FBD14F4] DEFAULT ((0)) FOR [SortOrder]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimRowNumber ------------------
---------------------------------------------
CREATE TABLE [fw].[DimRowNumber] (
    [RowNumberID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowNumberID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimRowNumber] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimRowNumber] ([Name]);
GO
ALTER TABLE [fw].[DimRowNumber] ADD CONSTRAINT [DF__FW_DimRowNumber_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimRowNumber] ADD CONSTRAINT [DF__DimRowNumb__Name__58B36098] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimRowNumber] ADD CONSTRAINT [DF__DimRowNum__Membe__59A784D1] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimRowNumber] ADD CONSTRAINT [DF__DimRowNum__Histo__5A9BA90A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimSPHAccountRollup ------------------
---------------------------------------------
CREATE TABLE [fw].[DimSPHAccountRollup] (
    [SPHAccountRollupID] int NOT NULL,
    [TransactionID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Statement] nvarchar(200) NOT NULL,
    [Category] nvarchar(200) NOT NULL,
    [Section] nvarchar(200) NOT NULL,
    [SortOrder] int NOT NULL,
    [IsStandard] bit NOT NULL,
    [SPHCostComponent] nvarchar(400) NOT NULL,
    [SPHCostComponentRollup] nvarchar(400) NOT NULL,
    [SPHAccountRollupCode] nvarchar(100) NOT NULL,
    [LineItem] nvarchar(200) NOT NULL,
    [Name] nvarchar(606) NOT NULL,
    PRIMARY KEY ([SPHAccountRollupID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimSPHAccountRollup] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__Trans__318AA99D] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__Membe__327ECDD6] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__State__34671648] DEFAULT ('Not Specified') FOR [Statement]; GO
ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__Categ__355B3A81] DEFAULT ('Not Specified') FOR [Category]; GO
ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__Secti__374382F3] DEFAULT ('') FOR [Section]; GO
ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__SortO__3837A72C] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__IsSta__392BCB65] DEFAULT ((0)) FOR [IsStandard]; GO
ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__SPHAc__2723C071] DEFAULT ('') FOR [SPHAccountRollupCode]; GO
ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__SPHCo__2A153BB5] DEFAULT ('') FOR [SPHCostComponent]; GO
ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__SPHCo__2B095FEE] DEFAULT ('') FOR [SPHCostComponentRollup]; GO
ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__LineI__6809E33B] DEFAULT ('Not Specified') FOR [LineItem]; GO
ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__Histo__3372F20F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimSPHDepartment ------------------
---------------------------------------------
CREATE TABLE [fw].[DimSPHDepartment] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [SPHDepartmentID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [TransactionID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [SPHDepartmentCode] nvarchar(100) NOT NULL,
    [SPHDepartmentRollup] nvarchar(200) NOT NULL,
    PRIMARY KEY ([SPHDepartmentID])
);

CREATE UNIQUE NONCLUSTERED INDEX [NCU_SPHDepartmentCode] ON [fw].[DimSPHDepartment] ([SPHDepartmentCode]) INCLUDE ([SPHDepartmentID]);
GO
ALTER TABLE [fw].[DimSPHDepartment] ADD CONSTRAINT [DF__DimSPHDep__Histo__3FB5067A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimSPHDepartment] ADD CONSTRAINT [DF__DimSPHDepa__Name__419D4EEC] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimSPHDepartment] ADD CONSTRAINT [DF__DimSPHDep__Trans__42917325] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimSPHDepartment] ADD CONSTRAINT [DF__DimSPHDep__Membe__4385975E] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimSPHDepartment] ADD CONSTRAINT [DF__DimSPHDep__SPHDe__4479BB97] DEFAULT ('') FOR [SPHDepartmentCode]; GO
ALTER TABLE [fw].[DimSPHDepartment] ADD CONSTRAINT [DF__DimSPHDep__SPHDe__456DDFD0] DEFAULT ('') FOR [SPHDepartmentRollup]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimSPHDepartmentRollup ------------------
---------------------------------------------
CREATE TABLE [fw].[DimSPHDepartmentRollup] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [SPHDepartmentRollupID] int NOT NULL,
    [TransactionID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [SortOrder] int NOT NULL,
    [IsStandard] bit NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [SPHDepartmentRollupCode] nvarchar(100) NOT NULL,
    PRIMARY KEY ([SPHDepartmentRollupID])
);
GO
ALTER TABLE [fw].[DimSPHDepartmentRollup] ADD CONSTRAINT [DF__DimSPHDep__Trans__1212C99B] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimSPHDepartmentRollup] ADD CONSTRAINT [DF__DimSPHDep__Membe__1306EDD4] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimSPHDepartmentRollup] ADD CONSTRAINT [DF__DimSPHDep__SortO__13FB120D] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimSPHDepartmentRollup] ADD CONSTRAINT [DF__DimSPHDep__IsSta__14EF3646] DEFAULT ((0)) FOR [IsStandard]; GO
ALTER TABLE [fw].[DimSPHDepartmentRollup] ADD CONSTRAINT [DF__DimSPHDepa__Name__15E35A7F] DEFAULT ('Not Specified') FOR [Name]; GO
ALTER TABLE [fw].[DimSPHDepartmentRollup] ADD CONSTRAINT [DF__DimSPHDep__Histo__102A8129] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimSPHDepartmentRollup] ADD CONSTRAINT [DF__DimSPHDep__SPHDe__5A195492] DEFAULT ('') FOR [SPHDepartmentRollupCode]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimSPHDepartmentType ------------------
---------------------------------------------
CREATE TABLE [fw].[DimSPHDepartmentType] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [SPHDepartmentTypeID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [TransactionID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [SPHDepartmentTypeCode] nvarchar(100) NOT NULL,
    [IsStandard] bit NOT NULL,
    PRIMARY KEY ([SPHDepartmentTypeID])
);
GO
ALTER TABLE [fw].[DimSPHDepartmentType] ADD CONSTRAINT [DF__DimSPHDepa__Name__3408BA43] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimSPHDepartmentType] ADD CONSTRAINT [DF__DimSPHDep__Trans__34FCDE7C] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimSPHDepartmentType] ADD CONSTRAINT [DF__DimSPHDep__Membe__35F102B5] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimSPHDepartmentType] ADD CONSTRAINT [DF__DimSPHDep__SPHDe__5B0D78CB] DEFAULT ('') FOR [SPHDepartmentTypeCode]; GO
ALTER TABLE [fw].[DimSPHDepartmentType] ADD CONSTRAINT [DF__DimSPHDep__Histo__322071D1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimSPHDepartmentType] ADD CONSTRAINT [DF__DimSPHDep__IsSta__5CF5C13D] DEFAULT ((0)) FOR [IsStandard]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimSPHJobCodeRollup ------------------
---------------------------------------------
CREATE TABLE [fw].[DimSPHJobCodeRollup] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [SPHJobCodeRollupID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [TransactionID] int NOT NULL,
    [SortOrder] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [IsStandard] bit NOT NULL,
    [SPHJobCodeRollupCode] nvarchar(100) NOT NULL,
    [SPHCostComponent] nvarchar(400) NOT NULL,
    PRIMARY KEY ([SPHJobCodeRollupID])
);
GO
ALTER TABLE [fw].[DimSPHJobCodeRollup] ADD CONSTRAINT [DF__DimSPHJob__SPHJo__2817E4AA] DEFAULT ('') FOR [SPHJobCodeRollupCode]; GO
ALTER TABLE [fw].[DimSPHJobCodeRollup] ADD CONSTRAINT [DF__DimSPHJob__SPHCo__47909003] DEFAULT ('') FOR [SPHCostComponent]; GO
ALTER TABLE [fw].[DimSPHJobCodeRollup] ADD CONSTRAINT [DF__DimSPHJob__Histo__59CE7078] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimSPHJobCodeRollup] ADD CONSTRAINT [DF__DimSPHJobC__Name__5BB6B8EA] DEFAULT ('Not Specified') FOR [Name]; GO
ALTER TABLE [fw].[DimSPHJobCodeRollup] ADD CONSTRAINT [DF__DimSPHJob__Trans__5CAADD23] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimSPHJobCodeRollup] ADD CONSTRAINT [DF__DimSPHJob__SortO__5D9F015C] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimSPHJobCodeRollup] ADD CONSTRAINT [DF__DimSPHJob__Membe__5E932595] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimSPHJobCodeRollup] ADD CONSTRAINT [DF__DimSPHJob__IsSta__5F8749CE] DEFAULT ((0)) FOR [IsStandard]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimSPHPayCodeRollup ------------------
---------------------------------------------
CREATE TABLE [fw].[DimSPHPayCodeRollup] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [SPHPayCodeRollupID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [TransactionID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [SPHProductiveClass] nvarchar(200) NOT NULL,
    [SortOrder] int NOT NULL,
    [IsStandard] bit NOT NULL,
    [SPHPayCodeRollupCode] nvarchar(100) NOT NULL,
    PRIMARY KEY ([SPHPayCodeRollupID])
);

CREATE UNIQUE NONCLUSTERED INDEX [NCU_SPHPayCodeRollupCode] ON [fw].[DimSPHPayCodeRollup] ([SPHPayCodeRollupCode]) INCLUDE ([SPHPayCodeRollupID]);
GO
ALTER TABLE [fw].[DimSPHPayCodeRollup] ADD CONSTRAINT [DF__DimSPHPay__Histo__3142F2DF] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimSPHPayCodeRollup] ADD CONSTRAINT [DF__DimSPHPayC__Name__332B3B51] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimSPHPayCodeRollup] ADD CONSTRAINT [DF__DimSPHPay__Trans__341F5F8A] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimSPHPayCodeRollup] ADD CONSTRAINT [DF__DimSPHPay__Membe__351383C3] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimSPHPayCodeRollup] ADD CONSTRAINT [DF__DimSPHPay__SPHPr__3607A7FC] DEFAULT ('') FOR [SPHProductiveClass]; GO
ALTER TABLE [fw].[DimSPHPayCodeRollup] ADD CONSTRAINT [DF__DimSPHPay__SortO__36FBCC35] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimSPHPayCodeRollup] ADD CONSTRAINT [DF__DimSPHPay__IsSta__37EFF06E] DEFAULT ((0)) FOR [IsStandard]; GO
ALTER TABLE [fw].[DimSPHPayCodeRollup] ADD CONSTRAINT [DF__DimSPHPay__SPHPa__38E414A7] DEFAULT ('') FOR [SPHPayCodeRollupCode]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimSecureGroup ------------------
---------------------------------------------
CREATE TABLE [fw].[DimSecureGroup] (
    [SecureGroupID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([SecureGroupID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimSecureGroup] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimSecureGroup] ADD CONSTRAINT [DF__FW_DimSecureGroup_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimSecureGroup] ADD CONSTRAINT [DF__DimSecureG__Name__1BDFF60F] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimSecureGroup] ADD CONSTRAINT [DF__DimSecure__Membe__1CD41A48] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimSecureGroup] ADD CONSTRAINT [DF__DimSecure__Histo__1DC83E81] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimServiceLine ------------------
---------------------------------------------
CREATE TABLE [fw].[DimServiceLine] (
    [ServiceLineID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(303) NOT NULL,
    [RollupID] int NOT NULL,
    [Rollup] nvarchar(100) NOT NULL,
    [RollupSortOrder] int NOT NULL,
    [ProductLine] nvarchar(200) NOT NULL,
    [Code] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    [TransactionID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ServiceLineID])
);

CREATE UNIQUE NONCLUSTERED INDEX [NCU_PreventDuplicates] ON [fw].[DimServiceLine] ([RollupID], [ProductLine]);
CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimServiceLine] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__DimServic__Membe__3C4FF2FD] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__DimServic__Rollu__1E11EF81] DEFAULT ((0)) FOR [RollupID]; GO
ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__DimServic__Rollu__11669219] DEFAULT ('Not Specified') FOR [Rollup]; GO
ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__DimServic__Rollu__23CAC8D7] DEFAULT ((0)) FOR [RollupSortOrder]; GO
ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__DimServic__Produ__1F0613BA] DEFAULT ('') FOR [ProductLine]; GO
ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__DimService__Code__288F7DF4] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__DimServic__SortO__1FFA37F3] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__FW_DimServiceLine_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__DimServic__Histo__3D441736] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimServiceLine2 ------------------
---------------------------------------------
CREATE TABLE [fw].[DimServiceLine2] (
    [ServiceLine2ID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [PatientTypeID] int NOT NULL,
    [TransactionID] int NOT NULL,
    [Rollup] nvarchar(100) NOT NULL,
    [Rollup2] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    PRIMARY KEY ([ServiceLine2ID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimServiceLine2] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimServiceLine2] ADD CONSTRAINT [DF__DimService__Name__7B78B5DE] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimServiceLine2] ADD CONSTRAINT [DF__DimServic__Membe__7C6CDA17] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimServiceLine2] ADD CONSTRAINT [DF__DimServic__Patie__7E552289] DEFAULT ((0)) FOR [PatientTypeID]; GO
ALTER TABLE [fw].[DimServiceLine2] ADD CONSTRAINT [DF__DimServic__Rollu__153722FD] DEFAULT ('Not Specified') FOR [Rollup]; GO
ALTER TABLE [fw].[DimServiceLine2] ADD CONSTRAINT [DF__DimServic__Rollu__17A9DEE8] DEFAULT ('Not Specified') FOR [Rollup2]; GO
ALTER TABLE [fw].[DimServiceLine2] ADD CONSTRAINT [DF__FW_DimServiceLine2_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimServiceLine2] ADD CONSTRAINT [DF__DimServic__SortO__25F7FE3F] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimServiceLine2] ADD CONSTRAINT [DF__DimServic__Histo__7D60FE50] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimServiceLine3 ------------------
---------------------------------------------
CREATE TABLE [fw].[DimServiceLine3] (
    [ServiceLine3ID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [PatientTypeID] int NOT NULL,
    [TransactionID] int NOT NULL,
    [Rollup] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    PRIMARY KEY ([ServiceLine3ID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimServiceLine3] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimServiceLine3] ADD CONSTRAINT [DF__DimServic__Histo__05F64451] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimServiceLine3] ADD CONSTRAINT [DF__DimService__Name__040DFBDF] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimServiceLine3] ADD CONSTRAINT [DF__DimServic__Membe__05022018] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimServiceLine3] ADD CONSTRAINT [DF__DimServic__Patie__06EA688A] DEFAULT ((0)) FOR [PatientTypeID]; GO
ALTER TABLE [fw].[DimServiceLine3] ADD CONSTRAINT [DF__DimServic__Rollu__1907B3E1] DEFAULT ('Not Specified') FOR [Rollup]; GO
ALTER TABLE [fw].[DimServiceLine3] ADD CONSTRAINT [DF__FW_DimServiceLine3_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimServiceLine3] ADD CONSTRAINT [DF__DimServic__SortO__26EC2278] DEFAULT ((0)) FOR [SortOrder]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimServiceLine4 ------------------
---------------------------------------------
CREATE TABLE [fw].[DimServiceLine4] (
    [ServiceLine4ID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [PatientTypeID] int NOT NULL,
    [TransactionID] int NOT NULL,
    [Rollup] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    [Rollup2] nvarchar(100) NOT NULL,
    PRIMARY KEY ([ServiceLine4ID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimServiceLine4] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimServiceLine4] ADD CONSTRAINT [DF__FW_DimServiceLine4_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimServiceLine4] ADD CONSTRAINT [DF__DimServic__Rollu__1CD844C5] DEFAULT ('Not Specified') FOR [Rollup]; GO
ALTER TABLE [fw].[DimServiceLine4] ADD CONSTRAINT [DF__DimService__Name__0CA341E0] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimServiceLine4] ADD CONSTRAINT [DF__DimServic__Membe__0D976619] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimServiceLine4] ADD CONSTRAINT [DF__DimServic__Patie__0F7FAE8B] DEFAULT ((0)) FOR [PatientTypeID]; GO
ALTER TABLE [fw].[DimServiceLine4] ADD CONSTRAINT [DF__DimServic__SortO__27E046B1] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimServiceLine4] ADD CONSTRAINT [DF__DimServic__Rollu__2BB0D795] DEFAULT ('Not Specified') FOR [Rollup2]; GO
ALTER TABLE [fw].[DimServiceLine4] ADD CONSTRAINT [DF__DimServic__Histo__0E8B8A52] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimServiceLine5 ------------------
---------------------------------------------
CREATE TABLE [fw].[DimServiceLine5] (
    [ServiceLine5ID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [PatientTypeID] int NOT NULL,
    [TransactionID] int NOT NULL,
    [Rollup] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    PRIMARY KEY ([ServiceLine5ID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimServiceLine5] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimServiceLine5] ADD CONSTRAINT [DF__FW_DimServiceLine5_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimServiceLine5] ADD CONSTRAINT [DF__DimServic__Rollu__20A8D5A9] DEFAULT ('Not Specified') FOR [Rollup]; GO
ALTER TABLE [fw].[DimServiceLine5] ADD CONSTRAINT [DF__DimServic__SortO__28D46AEA] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimServiceLine5] ADD CONSTRAINT [DF__DimService__Name__153887E1] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimServiceLine5] ADD CONSTRAINT [DF__DimServic__Membe__162CAC1A] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimServiceLine5] ADD CONSTRAINT [DF__DimServic__Patie__1814F48C] DEFAULT ((0)) FOR [PatientTypeID]; GO
ALTER TABLE [fw].[DimServiceLine5] ADD CONSTRAINT [DF__DimServic__Histo__1720D053] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimServiceLine6 ------------------
---------------------------------------------
CREATE TABLE [fw].[DimServiceLine6] (
    [ServiceLine6ID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [PatientTypeID] int NOT NULL,
    [TransactionID] int NOT NULL,
    [Rollup] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    PRIMARY KEY ([ServiceLine6ID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimServiceLine6] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimServiceLine6] ADD CONSTRAINT [DF__FW_DimServiceLine6_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimServiceLine6] ADD CONSTRAINT [DF__DimServic__SortO__29C88F23] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimServiceLine6] ADD CONSTRAINT [DF__DimService__Name__1DCDCDE2] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimServiceLine6] ADD CONSTRAINT [DF__DimServic__Membe__1EC1F21B] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimServiceLine6] ADD CONSTRAINT [DF__DimServic__Patie__20AA3A8D] DEFAULT ((0)) FOR [PatientTypeID]; GO
ALTER TABLE [fw].[DimServiceLine6] ADD CONSTRAINT [DF__DimServic__Rollu__2479668D] DEFAULT ('Not Specified') FOR [Rollup]; GO
ALTER TABLE [fw].[DimServiceLine6] ADD CONSTRAINT [DF__DimServic__Histo__1FB61654] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimServiceLineRollup ------------------
---------------------------------------------
CREATE TABLE [fw].[DimServiceLineRollup] (
    [ServiceLineRollupID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [SortOrder] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([ServiceLineRollupID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimServiceLineRollup] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimServiceLineRollup] ([Name]);
GO
ALTER TABLE [fw].[DimServiceLineRollup] ADD CONSTRAINT [DF__DimServic__Histo__3EF2F508] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimServiceLineRollup] ADD CONSTRAINT [DF__DimService__Name__3C16885D] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimServiceLineRollup] ADD CONSTRAINT [DF__DimServic__SortO__3D0AAC96] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimServiceLineRollup] ADD CONSTRAINT [DF__DimServic__Membe__3DFED0CF] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimServiceLineRollup] ADD CONSTRAINT [DF__DimServic__Trans__3FE71941] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimServiceLineRollupPH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimServiceLineRollupPH] (
    [ServiceLineRollupPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([ServiceLineRollupPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimServiceLineRollupPH] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimServiceLineRollupPH] ADD CONSTRAINT [DF__DimService__Name__4F5F3252] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimServiceLineRollupPH] ADD CONSTRAINT [DF__DimServic__Membe__5053568B] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimServiceLineRollupPH] ADD CONSTRAINT [DF__DimServic__Trans__523B9EFD] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimServiceLineRollupPH] ADD CONSTRAINT [DF__DimServic__Histo__51477AC4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimSourceOfSavings ------------------
---------------------------------------------
CREATE TABLE [fw].[DimSourceOfSavings] (
    [SourceOfSavingsID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([SourceOfSavingsID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimSourceOfSavings] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimSourceOfSavings] ADD CONSTRAINT [DF__DimSourceO__Name__38F52A8D] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimSourceOfSavings] ADD CONSTRAINT [DF__DimSource__Membe__39E94EC6] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimSourceOfSavings] ADD CONSTRAINT [DF__DimSource__Trans__3BD19738] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimSourceOfSavings] ADD CONSTRAINT [DF__DimSource__Histo__3ADD72FF] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimStaffingCategory ------------------
---------------------------------------------
CREATE TABLE [fw].[DimStaffingCategory] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [StaffingCategoryID] int NOT NULL,
    [TransactionID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [StaffingCategoryCode] nvarchar(100) NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [Name] nvarchar(203) NOT NULL,
    PRIMARY KEY ([StaffingCategoryID])
);

CREATE UNIQUE NONCLUSTERED INDEX [NCU_StaffingCategoryCode] ON [fw].[DimStaffingCategory] ([StaffingCategoryCode]) INCLUDE ([StaffingCategoryID]);
GO
ALTER TABLE [fw].[DimStaffingCategory] ADD CONSTRAINT [DF__DimStaffi__Trans__018A8973] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimStaffingCategory] ADD CONSTRAINT [DF__DimStaffi__Membe__027EADAC] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimStaffingCategory] ADD CONSTRAINT [DF__DimStaffi__Staff__0372D1E5] DEFAULT ((0)) FOR [StaffingCategoryCode]; GO
ALTER TABLE [fw].[DimStaffingCategory] ADD CONSTRAINT [DF__DimStaffi__Descr__0466F61E] DEFAULT ('Not Specified') FOR [Description]; GO
ALTER TABLE [fw].[DimStaffingCategory] ADD CONSTRAINT [DF__DimStaffi__Histo__7FA24101] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimStrataDecisionServiceLine ------------------
---------------------------------------------
CREATE TABLE [fw].[DimStrataDecisionServiceLine] (
    [StrataDecisionServiceLineID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [PatientTypeID] int NOT NULL,
    PRIMARY KEY ([StrataDecisionServiceLineID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimStrataDecisionServiceLine] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimStrataDecisionServiceLine] ADD CONSTRAINT [DF__DimStrata__Histo__367EA7B9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimStrataDecisionServiceLine] ADD CONSTRAINT [DF__DimStrataD__Name__34965F47] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimStrataDecisionServiceLine] ADD CONSTRAINT [DF__DimStrata__Membe__358A8380] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimStrataDecisionServiceLine] ADD CONSTRAINT [DF__DimStrata__Trans__3772CBF2] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimStrataDecisionServiceLine] ADD CONSTRAINT [DF__DimStrata__Patie__3866F02B] DEFAULT ((0)) FOR [PatientTypeID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimSystem ------------------
---------------------------------------------
CREATE TABLE [fw].[DimSystem] (
    [SystemID] smallint NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Code] nvarchar(200) NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [SecureGroupID] int NOT NULL,
    [SortOrder] int NOT NULL,
    [EliminationsDepartmentID] int NOT NULL,
    PRIMARY KEY ([SystemID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimSystem] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimSystem] ADD CONSTRAINT [DF__DimSystem__Histo__2491A282] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimSystem] ADD CONSTRAINT [DF__DimSystem__Membe__239D7E49] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimSystem] ADD CONSTRAINT [DF__DimSystem__Trans__2585C6BB] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimSystem] ADD CONSTRAINT [DF__DimSystem__Code__2679EAF4] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [fw].[DimSystem] ADD CONSTRAINT [DF__DimSystem__Descr__276E0F2D] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[DimSystem] ADD CONSTRAINT [DF__DimSystem__SortO__28623366] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimSystem] ADD CONSTRAINT [DF__DimSystem__Elimi__4FA5B5F6] DEFAULT ((0)) FOR [EliminationsDepartmentID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimTime ------------------
---------------------------------------------
CREATE TABLE [fw].[DimTime] (
    [TimeID] int NOT NULL,
    [Name] varchar(5) NOT NULL,
    [Hour] varchar(2) NOT NULL,
    [Minute] varchar(2) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    [StandardTime] nvarchar(100) NOT NULL,
    PRIMARY KEY ([TimeID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimTime] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimTime] ADD CONSTRAINT [DF__DimTime__MemberG__14E518D4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimTime] ADD CONSTRAINT [DF__DimTime__History__15D93D0D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimTime] ADD CONSTRAINT [DF__DimTime__Standar__1AB09A8F] DEFAULT ('12:00 AM') FOR [StandardTime]; GO
ALTER TABLE [fw].[DimTime] ADD CONSTRAINT [DF__FW_DimTime_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimTime] ADD CONSTRAINT [DF__fw_DimTime_Minute] DEFAULT ('') FOR [Minute]; GO
ALTER TABLE [fw].[DimTime] ADD CONSTRAINT [DF__fw_DimTime_Hour] DEFAULT ('') FOR [Hour]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimTimeClass ------------------
---------------------------------------------
CREATE TABLE [fw].[DimTimeClass] (
    [TimeClassID] tinyint NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [TimeClassCode] nvarchar(3) NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [GlobalID] varchar(64) NOT NULL,
    [IsSP] bit NOT NULL,
    [SortOrder] int NOT NULL,
    [TransactionID] int NOT NULL,
    [SPIsISForecast] bit NOT NULL,
    PRIMARY KEY ([TimeClassID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_MemberGUID] ON [fw].[DimTimeClass] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_TimeClassCode] ON [fw].[DimTimeClass] ([TimeClassCode]);
CREATE NONCLUSTERED INDEX [IX_Name] ON [fw].[DimTimeClass] ([Name]);
GO
ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF__DimTimeCla__IsSP__08A26ADC] DEFAULT ((0)) FOR [IsSP]; GO
ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF__FW_DimTimeClass_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF_DimTimeClass_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF__DimTimeCl__Globa__4C832D6A] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF_FWDIMTIMECLASSNAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF__DimTimeCl__SortO__6BD12204] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF__DimTimeCl__SPIsI__70E4B3EE] DEFAULT ((0)) FOR [SPIsISForecast]; GO
ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF_DimTimeClass_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF_DimTimeClass_Code] DEFAULT ('A') FOR [TimeClassCode]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimTimeClassPH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimTimeClassPH] (
    [TimeClassPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([TimeClassPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimTimeClassPH] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimTimeClassPH] ADD CONSTRAINT [DF__DimTimeCla__Name__148821B3] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimTimeClassPH] ADD CONSTRAINT [DF__FW_DimTimeClassPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimTimeClassPH] ADD CONSTRAINT [DF__DimTimeCl__Membe__157C45EC] DEFAULT (newid()) FOR [MemberGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimUnit ------------------
---------------------------------------------
CREATE TABLE [fw].[DimUnit] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [UnitID] smallint NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Abbreviation] nvarchar(10) NOT NULL,
    [Version] timestamp NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [SortOrder] nvarchar(5) NOT NULL,
    [TransactionID] int NOT NULL,
    [IsActive] bit NOT NULL,
    PRIMARY KEY ([UnitID])
);

CREATE UNIQUE NONCLUSTERED INDEX [MGUID_Unit_data_DimUnit] ON [fw].[DimUnit] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimUnit] ADD CONSTRAINT [DF_data.DimUnit_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimUnit] ADD CONSTRAINT [DF__FW_DimUnit_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimUnit] ADD CONSTRAINT [DF__DimUnit__IsActiv__298B2BD0] DEFAULT ((1)) FOR [IsActive]; GO
ALTER TABLE [fw].[DimUnit] ADD CONSTRAINT [DF_FWDIMUNITSORTORDER] DEFAULT ('') FOR [SortOrder]; GO
ALTER TABLE [fw].[DimUnit] ADD CONSTRAINT [DF_DimUnit_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimUnit] ADD CONSTRAINT [DF_data.DimUnit_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimUnit] ADD CONSTRAINT [DF_data.DimUnit_Abbreviation] DEFAULT ('') FOR [Abbreviation]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimUnitType ------------------
---------------------------------------------
CREATE TABLE [fw].[DimUnitType] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [DisplayFormat] nvarchar(50) NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [GlobalID] varchar(32) NOT NULL,
    [SPDisplayFormat] nvarchar(100) NOT NULL,
    [CapitalDisplayFormat] nvarchar(100) NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([UnitTypeID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimUnitType] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimUnitType] ADD CONSTRAINT [DF__FW_DimUnitType_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimUnitType] ADD CONSTRAINT [DF_DimUnitType_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimUnitType] ADD CONSTRAINT [DF__DimUnitTy__SPDis__2CAAC128] DEFAULT ('') FOR [SPDisplayFormat]; GO
ALTER TABLE [fw].[DimUnitType] ADD CONSTRAINT [DF__DimUnitTy__Capit__2D9EE561] DEFAULT ('') FOR [CapitalDisplayFormat]; GO
ALTER TABLE [fw].[DimUnitType] ADD CONSTRAINT [DF__DimUnitTy__Membe__7BBC73E9] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimUnitType] ADD CONSTRAINT [DF__DimUnitTy__Globa__5AD14CC1] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [fw].[DimUnitType] ADD CONSTRAINT [DF__DimUnitTyp__Name__7AC84FB0] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimUnitType] ADD CONSTRAINT [DF__DimUnitTy__Displ__79D42B77] DEFAULT ('') FOR [DisplayFormat]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimVariability ------------------
---------------------------------------------
CREATE TABLE [fw].[DimVariability] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [VariabilityID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [TransactionID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([VariabilityID])
);
GO
ALTER TABLE [fw].[DimVariability] ADD CONSTRAINT [DF__DimVariab__Membe__00F16219] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimVariability] ADD CONSTRAINT [DF__DimVariab__Histo__7D20D135] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimVariability] ADD CONSTRAINT [DF__DimVariabi__Name__7F0919A7] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimVariability] ADD CONSTRAINT [DF__DimVariab__Trans__7FFD3DE0] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimWorkWeek ------------------
---------------------------------------------
CREATE TABLE [fw].[DimWorkWeek] (
    [WorkWeekID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [WorkWeekCode] nvarchar(200) NOT NULL,
    [Type] nvarchar(100) NOT NULL,
    [SortOrder] nvarchar(100) NOT NULL,
    [Hours] numeric NOT NULL,
    PRIMARY KEY ([WorkWeekID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimWorkWeek] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimWorkWeek] ADD CONSTRAINT [DF__DimWorkWee__Name__0CEF54E5] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimWorkWeek] ADD CONSTRAINT [DF__DimWorkWe__Membe__0DE3791E] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimWorkWeek] ADD CONSTRAINT [DF__DimWorkWe__Trans__0FCBC190] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimWorkWeek] ADD CONSTRAINT [DF__DimWorkWe__WorkW__10BFE5C9] DEFAULT ('') FOR [WorkWeekCode]; GO
ALTER TABLE [fw].[DimWorkWeek] ADD CONSTRAINT [DF__DimWorkWe__Histo__0ED79D57] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[DimWorkWeek] ADD CONSTRAINT [DF__DimWorkWee__Type__6CA280E4] DEFAULT ('All') FOR [Type]; GO
ALTER TABLE [fw].[DimWorkWeek] ADD CONSTRAINT [DF_dimworkweek_hours] DEFAULT ((40)) FOR [Hours]; GO
ALTER TABLE [fw].[DimWorkWeek] ADD CONSTRAINT [DF__DimWorkWe__SortO__7D049C8D] DEFAULT ('') FOR [SortOrder]; GO

---------------------------------------------

---------------------------------------------
-- fw.DimWorkWeekPH ------------------
---------------------------------------------
CREATE TABLE [fw].[DimWorkWeekPH] (
    [WorkWeekPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([WorkWeekPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimWorkWeekPH] ([MemberGUID]);
GO
ALTER TABLE [fw].[DimWorkWeekPH] ADD CONSTRAINT [DF__DimWorkWee__Name__149076AD] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[DimWorkWeekPH] ADD CONSTRAINT [DF__DimWorkWe__Membe__15849AE6] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[DimWorkWeekPH] ADD CONSTRAINT [DF__DimWorkWe__Trans__176CE358] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[DimWorkWeekPH] ADD CONSTRAINT [DF__DimWorkWe__Histo__1678BF1F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactChargeBasedStatistics ------------------
---------------------------------------------
CREATE TABLE [fw].[FactChargeBasedStatistics] (
    [RowID] int NOT NULL,
    [DateID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [Value] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [fw].[FactChargeBasedStatistics] ([IsDeleted], [DateID], [DepartmentID], [AccountID], [RowID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [fw].[FactChargeBasedStatistics] ([IsDeleted], [DateID], [DepartmentID], [AccountID], [RowID]);
GO
ALTER TABLE [fw].[FactChargeBasedStatistics] ADD CONSTRAINT [DF__FactCharg__Value__0786EF0A] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fw].[FactChargeBasedStatistics] ADD CONSTRAINT [DF__FactCharg__IsDel__087B1343] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactChargeBasedStatistics] ADD CONSTRAINT [DF__FactCharg__Trans__0A635BB5] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[FactChargeBasedStatistics] ADD CONSTRAINT [DF__FactCharg__Histo__096F377C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactChargeBasedStatisticsDailyKeys ------------------
---------------------------------------------
CREATE TABLE [fw].[FactChargeBasedStatisticsDailyKeys] (
    [DepartmentID] int NOT NULL,
    [PayPeriodID] smallint NOT NULL,
    [DateID] int NOT NULL,
    [AccountID] int NOT NULL,
    PRIMARY KEY ([DateID], [DepartmentID], [AccountID])
);
GO

---------------------------------------------

---------------------------------------------
-- fw.FactChargeBasedStatisticsMonthly ------------------
---------------------------------------------
CREATE TABLE [fw].[FactChargeBasedStatisticsMonthly] (
    [RowID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [Value] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Version] timestamp NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fw].[FactChargeBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactChargeBasedStatisticsByPostDate_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[FactChargeBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactChargeBasedStatisticsByPostDate_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fw].[FactChargeBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactChargeBasedStatisticsByPostDate_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fw].[FactChargeBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactChargeBasedStatisticsByPostDate_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactChargeBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactChargeBasedStatisticsByPostDate_AccountID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[FactChargeBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactChargeBasedStatisticsByPostDate_Value] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fw].[FactChargeBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactChargeBasedStatisticsByPostDate_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactChargeBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactChargeBasedStatisticsByPostDate_TransactionID] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactChargeBasedStatisticsPayPeriodKeys ------------------
---------------------------------------------
CREATE TABLE [fw].[FactChargeBasedStatisticsPayPeriodKeys] (
    [DepartmentID] int NOT NULL,
    [PayPeriodID] smallint NOT NULL,
    [AccountID] int NOT NULL,
    PRIMARY KEY ([PayPeriodID], [DepartmentID], [AccountID])
);
GO

---------------------------------------------

---------------------------------------------
-- fw.FactClinicaltoGLDepartmentMapping ------------------
---------------------------------------------
CREATE TABLE [fw].[FactClinicaltoGLDepartmentMapping] (
    [RowID] int NOT NULL,
    [ClinicalDepartmentID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ClinicalDepartmentCode] nvarchar(100) NOT NULL,
    [GLDepartmentCode] nvarchar(100) NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fw].[FactClinicaltoGLDepartmentMapping] ADD CONSTRAINT [DF__FactClini__Histo__1572B9A9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[FactClinicaltoGLDepartmentMapping] ADD CONSTRAINT [DF__FactClini__Clini__12964CFE] DEFAULT ('') FOR [ClinicalDepartmentCode]; GO
ALTER TABLE [fw].[FactClinicaltoGLDepartmentMapping] ADD CONSTRAINT [DF__FactClini__GLDep__138A7137] DEFAULT ('') FOR [GLDepartmentCode]; GO
ALTER TABLE [fw].[FactClinicaltoGLDepartmentMapping] ADD CONSTRAINT [DF__FactClini__IsDel__147E9570] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactClinicaltoGLDepartmentMapping] ADD CONSTRAINT [DF__FactClini__Trans__1666DDE2] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactEliminationsAccountMapping ------------------
---------------------------------------------
CREATE TABLE [fw].[FactEliminationsAccountMapping] (
    [RowID] int NOT NULL,
    [RevenueAccountCode] nvarchar(100) NOT NULL,
    [ExpenseAccountCode] nvarchar(100) NOT NULL,
    [PlugAccountID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fw].[FactEliminationsAccountMapping] ADD CONSTRAINT [DF__FactElimi__Reven__38233220] DEFAULT ('') FOR [RevenueAccountCode]; GO
ALTER TABLE [fw].[FactEliminationsAccountMapping] ADD CONSTRAINT [DF__FactElimi__Expen__39175659] DEFAULT ('') FOR [ExpenseAccountCode]; GO
ALTER TABLE [fw].[FactEliminationsAccountMapping] ADD CONSTRAINT [DF__FactElimi__PlugA__3A0B7A92] DEFAULT ((0)) FOR [PlugAccountID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactEncounterBasedStatistics ------------------
---------------------------------------------
CREATE TABLE [fw].[FactEncounterBasedStatistics] (
    [RowID] bigint NOT NULL,
    [DateID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [Value] decimal NOT NULL,
    [StatisticID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fw].[FactEncounterBasedStatistics] ADD CONSTRAINT [DF_FactEncounterBasedStatistics_DateID] DEFAULT ((0)) FOR [DateID]; GO
ALTER TABLE [fw].[FactEncounterBasedStatistics] ADD CONSTRAINT [DF_FactEncounterBasedStatistics_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactEncounterBasedStatistics] ADD CONSTRAINT [DF_FactEncounterBasedStatistics_AccountID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[FactEncounterBasedStatistics] ADD CONSTRAINT [DF_FactEncounterBasedStatistics_Value] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fw].[FactEncounterBasedStatistics] ADD CONSTRAINT [DF_FactEncounterBasedStatistics_StatisticID] DEFAULT ((0)) FOR [StatisticID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactEncounterBasedStatisticsMonthly ------------------
---------------------------------------------
CREATE TABLE [fw].[FactEncounterBasedStatisticsMonthly] (
    [RowID] bigint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [Value] decimal NOT NULL,
    [StatisticID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fw].[FactEncounterBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactEncounterBasedStatisticsMonthly_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fw].[FactEncounterBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactEncounterBasedStatisticsMonthly_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fw].[FactEncounterBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactEncounterBasedStatisticsMonthly_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactEncounterBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactEncounterBasedStatisticsMonthly_AccountID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[FactEncounterBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactEncounterBasedStatisticsMonthly_Value] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fw].[FactEncounterBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactEncounterBasedStatisticsMonthly_StatisticID] DEFAULT ((0)) FOR [StatisticID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactGLSampled ------------------
---------------------------------------------
CREATE TABLE [fw].[FactGLSampled] (
    [RowID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [Units] decimal NOT NULL,
    [UnitsYTD] decimal NOT NULL,
    [UnitsPriorYear] decimal NOT NULL,
    [UnitsPriorYTD] decimal NOT NULL,
    [Dollars] decimal NOT NULL,
    [DollarsYTD] decimal NOT NULL,
    [DollarsPriorYear] decimal NOT NULL,
    [DollarsPriorYTD] decimal NOT NULL,
    [TransactionID] int NULL,
    [IsSystemGenerated] bit NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_FactGLSampled] ON [fw].[FactGLSampled] ([AccountID], [DepartmentID], [FiscalYearID], [FiscalMonthID], [TimeClassID]);
CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactGLSampled] ([IsDeleted]);
GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [FK_FactGLSampled_DimAccount] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [FK_FactGLSampled_DimFiscalMonth] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [FK_FactGLSampled_DimFiscalYear] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [FK_FactGLSampled_DimTimeClass] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_DollarsPriorYTD] DEFAULT ((0)) FOR [DollarsPriorYTD]; GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF__FW_FactGLSampled_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_Units] DEFAULT ((0)) FOR [Units]; GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_UnitsYTD] DEFAULT ((0)) FOR [UnitsYTD]; GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_UnitsPriorYear] DEFAULT ((0)) FOR [UnitsPriorYear]; GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_UnitsPriorYTD] DEFAULT ((0)) FOR [UnitsPriorYTD]; GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_AccountID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_Dollars] DEFAULT ((0)) FOR [Dollars]; GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_DollarsYTD] DEFAULT ((0)) FOR [DollarsYTD]; GO
ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_DollarsPriorYear] DEFAULT ((0)) FOR [DollarsPriorYear]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactPatientBillingLineItemGroupedCache ------------------
---------------------------------------------
CREATE TABLE [fw].[FactPatientBillingLineItemGroupedCache] (
    [RowID] bigint NOT NULL,
    [DepartmentID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [PatientTypeRollupID] tinyint NOT NULL,
    [ServiceDateID] int NOT NULL,
    [PostDateID] int NOT NULL,
    [UnitsOfService] float NULL,
    [FiscalYearID] smallint NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE NONCLUSTERED INDEX [CORE_PostDateID_DepartmentID_ChargeCodeID_PatientTypeRollupID_inc] ON [fw].[FactPatientBillingLineItemGroupedCache] ([PostDateID], [DepartmentID], [ChargeCodeID], [PatientTypeRollupID]) INCLUDE ([UnitsOfService]);
CREATE NONCLUSTERED INDEX [CORE_ServiceDateID_DepartmentID_ChargeCodeID_PatientTypeRollupID_inc] ON [fw].[FactPatientBillingLineItemGroupedCache] ([ServiceDateID], [DepartmentID], [ChargeCodeID], [PatientTypeRollupID]) INCLUDE ([UnitsOfService]);
GO
ALTER TABLE [fw].[FactPatientBillingLineItemGroupedCache] ADD CONSTRAINT [DF__FactPatie__Fisca__6D4E869C] DEFAULT ((0)) FOR [FiscalYearID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactPayrollSampledDaily ------------------
---------------------------------------------
CREATE TABLE [fw].[FactPayrollSampledDaily] (
    [RowID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayPeriodID] smallint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [DateID] int NOT NULL,
    [Hours] decimal NOT NULL,
    [Dollars] decimal NOT NULL,
    [FTEs] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NULL,
    [IsFlexed] bit NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE NONCLUSTERED INDEX [IDX_FactPayrollSampledDaily] ON [fw].[FactPayrollSampledDaily] ([DepartmentID], [JobCodeID], [PayCodeGroupID], [PayPeriodID], [DateID], [TimeClassID]) INCLUDE ([Dollars], [FTEs], [Hours]);
CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactPayrollSampledDaily] ([IsDeleted]);
GO
ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_PayPeriodID] DEFAULT ((0)) FOR [PayPeriodID]; GO
ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_DateID] DEFAULT ((0)) FOR [DateID]; GO
ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_Hours] DEFAULT ((0)) FOR [Hours]; GO
ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_Dollars] DEFAULT ((0)) FOR [Dollars]; GO
ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_FTEs] DEFAULT ((0)) FOR [FTEs]; GO
ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_TransactionID] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_IsFlexed] DEFAULT ((0)) FOR [IsFlexed]; GO
ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_PayCodeGroupID] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactPayrollSampledDailyDetailed ------------------
---------------------------------------------
CREATE TABLE [fw].[FactPayrollSampledDailyDetailed] (
    [RowID] bigint NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeID] smallint NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [PayPeriodID] smallint NOT NULL,
    [DateID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Dollars] decimal NOT NULL,
    [FTEs] decimal NOT NULL,
    [Hours] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    [EmployeeID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactPayrollSampledDailyDetailed] ([IsDeleted]);
CREATE NONCLUSTERED INDEX [IDX_FactPayrollSampledDailyDetailed] ON [fw].[FactPayrollSampledDailyDetailed] ([DepartmentID], [JobCodeID], [PayCodeID], [PayCodeGroupID], [EmployeeID], [DateID], [TimeClassID]);
GO
ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__Depar__052B3BFA] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__JobCo__061F6033] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__PayCo__0713846C] DEFAULT ((0)) FOR [PayCodeID]; GO
ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__PayCo__0807A8A5] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__PayPe__08FBCCDE] DEFAULT ((0)) FOR [PayPeriodID]; GO
ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__DateI__09EFF117] DEFAULT ((0)) FOR [DateID]; GO
ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__TimeC__0AE41550] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__0BD83989] DEFAULT ((0)) FOR [Dollars]; GO
ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayrol__FTEs__0CCC5DC2] DEFAULT ((0)) FOR [FTEs]; GO
ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__0DC081FB] DEFAULT ((0)) FOR [Hours]; GO
ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__IsDel__0EB4A634] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__Trans__109CEEA6] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__Emplo__119112DF] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__Histo__0FA8CA6D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactPayrollSampledMonthly ------------------
---------------------------------------------
CREATE TABLE [fw].[FactPayrollSampledMonthly] (
    [RowID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeID] smallint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Hours] decimal NOT NULL,
    [HoursYTD] decimal NOT NULL,
    [HoursPriorYear] decimal NOT NULL,
    [HoursPriorYTD] decimal NOT NULL,
    [Dollars] decimal NOT NULL,
    [DollarsYTD] decimal NOT NULL,
    [DollarsPriorYear] decimal NOT NULL,
    [DollarsPriorYTD] decimal NOT NULL,
    [FTEs] decimal NOT NULL,
    [FTEsYTD] decimal NOT NULL,
    [FTEsPriorYear] decimal NOT NULL,
    [FTEsPriorYTD] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NULL,
    [PayCodeGroupID] int NOT NULL,
    [IsSystemGenerated] bit NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_FactPayrollSampledMonthly] ON [fw].[FactPayrollSampledMonthly] ([DepartmentID], [JobCodeID], [PayCodeID], [FiscalYearID], [FiscalMonthID], [TimeClassID]);
CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactPayrollSampledMonthly] ([IsDeleted]);
GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF__FW_FactPayrollSampledMonthly_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_FTEs] DEFAULT ((0)) FOR [FTEs]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_FTEsYTD] DEFAULT ((0)) FOR [FTEsYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_FTEsPriorYear] DEFAULT ((0)) FOR [FTEsPriorYear]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_FTEsPriorYTD] DEFAULT ((0)) FOR [FTEsPriorYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF__FactPayrollSampledMonthly__IsDel__772804EC] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_Hours] DEFAULT ((0)) FOR [Hours]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_HoursYTD] DEFAULT ((0)) FOR [HoursYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_HoursPriorYear] DEFAULT ((0)) FOR [HoursPriorYear]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_HoursPriorYTD] DEFAULT ((0)) FOR [HoursPriorYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_Dollars] DEFAULT ((0)) FOR [Dollars]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_DollarsYTD] DEFAULT ((0)) FOR [DollarsYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_DollarsPriorYear] DEFAULT ((0)) FOR [DollarsPriorYear]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_DollarsPriorYTD] DEFAULT ((0)) FOR [DollarsPriorYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF__FactPayro__PayCo__23AF9150] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF__FactPayrollSampledMonthly__Histo__781C2925] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_PayCodeID] DEFAULT ((0)) FOR [PayCodeID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactPayrollSampledMonthlyDetailed ------------------
---------------------------------------------
CREATE TABLE [fw].[FactPayrollSampledMonthlyDetailed] (
    [RowID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeID] smallint NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [EmployeeID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Dollars] decimal NOT NULL,
    [DollarsYTD] decimal NOT NULL,
    [DollarsPriorYear] decimal NOT NULL,
    [DollarsPriorYTD] decimal NOT NULL,
    [Hours] decimal NOT NULL,
    [HoursYTD] decimal NOT NULL,
    [HoursPriorYear] decimal NOT NULL,
    [HoursPriorYTD] decimal NOT NULL,
    [FTEs] decimal NOT NULL,
    [FTEsYTD] decimal NOT NULL,
    [FTEsPriorYear] decimal NOT NULL,
    [FTEsPriorYTD] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    [IsSystemGenerated] bit NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [fw].[FactPayrollSampledMonthlyDetailed] ([IsDeleted], [DepartmentID], [TimeClassID], [FiscalYearID], [FiscalMonthID], [JobCodeID], [PayCodeGroupID], [PayCodeID], [EmployeeID], [RowID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [fw].[FactPayrollSampledMonthlyDetailed] ([IsDeleted], [DepartmentID], [TimeClassID], [FiscalYearID], [FiscalMonthID], [JobCodeID], [PayCodeGroupID], [PayCodeID], [EmployeeID], [RowID]);
GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__FTEsP__00072DB7] DEFAULT ((0)) FOR [FTEsPriorYear]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__FTEsP__00FB51F0] DEFAULT ((0)) FOR [FTEsPriorYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__IsDel__01EF7629] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Trans__03D7BE9B] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF_FactPayrollSampledMonthlyDetailed_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Histo__02E39A62] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Fisca__74957B0B] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Fisca__75899F44] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__767DC37D] DEFAULT ((0)) FOR [Dollars]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__7771E7B6] DEFAULT ((0)) FOR [DollarsYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__78660BEF] DEFAULT ((0)) FOR [DollarsPriorYear]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__795A3028] DEFAULT ((0)) FOR [DollarsPriorYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF_FactPayrollSampledMonthlyDetailed_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__7A4E5461] DEFAULT ((0)) FOR [Hours]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF_FactPayrollSampledMonthlyDetailed_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__7B42789A] DEFAULT ((0)) FOR [HoursYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF_FactPayrollSampledMonthlyDetailed_PayCodeID] DEFAULT ((0)) FOR [PayCodeID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__7C369CD3] DEFAULT ((0)) FOR [HoursPriorYear]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF_FactPayrollSampledMonthlyDetailed_PayCodeGroupID] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__7D2AC10C] DEFAULT ((0)) FOR [HoursPriorYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF_FactPayrollSampledMonthlyDetailed_EmployeeID] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayrol__FTEs__7E1EE545] DEFAULT ((0)) FOR [FTEs]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF_FactPayrollSampledMonthlyDetailed_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__FTEsY__7F13097E] DEFAULT ((0)) FOR [FTEsYTD]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactPayrollSampledPayPeriod ------------------
---------------------------------------------
CREATE TABLE [fw].[FactPayrollSampledPayPeriod] (
    [RowID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayPeriodID] smallint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Hours] decimal NOT NULL,
    [HoursYTD] decimal NOT NULL,
    [HoursPriorYear] decimal NOT NULL,
    [HoursPriorYTD] decimal NOT NULL,
    [Dollars] decimal NOT NULL,
    [DollarsYTD] decimal NOT NULL,
    [DollarsPriorYear] decimal NOT NULL,
    [DollarsPriorYTD] decimal NOT NULL,
    [FTEs] decimal NOT NULL,
    [FTEsYTD] decimal NOT NULL,
    [FTEsPriorYear] decimal NOT NULL,
    [FTEsPriorYTD] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NULL,
    [IsFlexed] bit NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [IsSystemGenerated] bit NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE NONCLUSTERED INDEX [IDX_FactPayrollSampledPayPeriod] ON [fw].[FactPayrollSampledPayPeriod] ([DepartmentID], [JobCodeID], [PayCodeGroupID], [PayPeriodID], [TimeClassID]) INCLUDE ([Dollars], [DollarsPriorYear], [DollarsPriorYTD], [DollarsYTD], [FTEs], [FTEsPriorYear], [FTEsPriorYTD], [FTEsYTD], [Hours], [HoursPriorYear], [HoursPriorYTD], [HoursYTD]);
CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactPayrollSampledPayPeriod] ([IsDeleted]);
GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF__FW_FactPayrollSampledPayPeriod_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_PayPeriodID] DEFAULT ((0)) FOR [PayPeriodID]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF__FactPayro__IsFle__1508738B] DEFAULT ((0)) FOR [IsFlexed]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_FTEs] DEFAULT ((0)) FOR [FTEs]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_FTEsYTD] DEFAULT ((0)) FOR [FTEsYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_FTEsPriorYear] DEFAULT ((0)) FOR [FTEsPriorYear]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_FTEsPriorYTD] DEFAULT ((0)) FOR [FTEsPriorYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF__FactPayroPP__IsDel__772804EC] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_Dollars] DEFAULT ((0)) FOR [Dollars]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_DollarsYTD] DEFAULT ((0)) FOR [DollarsYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_DollarsPriorYear] DEFAULT ((0)) FOR [DollarsPriorYear]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_DollarsPriorYTD] DEFAULT ((0)) FOR [DollarsPriorYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_Hours] DEFAULT ((0)) FOR [Hours]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_HoursYTD] DEFAULT ((0)) FOR [HoursYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_HoursPriorYear] DEFAULT ((0)) FOR [HoursPriorYear]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_HoursPriorYTD] DEFAULT ((0)) FOR [HoursPriorYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF__FactPayro__PayCo__3875A40C] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF__FactPayroPP__Histo__781C2925] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactPayrollSampledPayPeriodDetailed ------------------
---------------------------------------------
CREATE TABLE [fw].[FactPayrollSampledPayPeriodDetailed] (
    [RowID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeID] smallint NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [PayPeriodID] smallint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Dollars] decimal NOT NULL,
    [DollarsPriorYear] decimal NOT NULL,
    [DollarsPriorYTD] decimal NOT NULL,
    [DollarsYTD] decimal NOT NULL,
    [FTEs] decimal NOT NULL,
    [FTEsPriorYear] decimal NOT NULL,
    [FTEsPriorYTD] decimal NOT NULL,
    [FTEsYTD] decimal NOT NULL,
    [Hours] decimal NOT NULL,
    [HoursPriorYear] decimal NOT NULL,
    [HoursPriorYTD] decimal NOT NULL,
    [HoursYTD] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    [EmployeeID] int NOT NULL,
    [IsSystemGenerated] bit NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [NCNU_BASE] ON [fw].[FactPayrollSampledPayPeriodDetailed] ([PayPeriodID]);
CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactPayrollSampledPayPeriodDetailed] ([IsDeleted]);
CREATE NONCLUSTERED INDEX [IDX_FactPayrollSampledPayPeriodDetailed] ON [fw].[FactPayrollSampledPayPeriodDetailed] ([DepartmentID], [JobCodeID], [PayCodeID], [PayCodeGroupID], [EmployeeID], [PayPeriodID], [TimeClassID]) INCLUDE ([Hours]);
GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__3E2E7D62] DEFAULT ((0)) FOR [DollarsYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayrol__FTEs__3F22A19B] DEFAULT ((0)) FOR [FTEs]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__FTEsP__4016C5D4] DEFAULT ((0)) FOR [FTEsPriorYear]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__FTEsP__410AEA0D] DEFAULT ((0)) FOR [FTEsPriorYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__FTEsY__41FF0E46] DEFAULT ((0)) FOR [FTEsYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__42F3327F] DEFAULT ((0)) FOR [Hours]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__43E756B8] DEFAULT ((0)) FOR [HoursPriorYear]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__44DB7AF1] DEFAULT ((0)) FOR [HoursPriorYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__45CF9F2A] DEFAULT ((0)) FOR [HoursYTD]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__IsDel__46C3C363] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Trans__48AC0BD5] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriodDetailed_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Histo__47B7E79C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Emplo__5ACABC10] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriodDetailed_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriodDetailed_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriodDetailed_PayCodeID] DEFAULT ((0)) FOR [PayCodeID]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriodDetailed_PayCodeGroupID] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriodDetailed_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriodDetailed_PayPeriodID] DEFAULT ((0)) FOR [PayPeriodID]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__3B5210B7] DEFAULT ((0)) FOR [Dollars]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__3C4634F0] DEFAULT ((0)) FOR [DollarsPriorYear]; GO
ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__3D3A5929] DEFAULT ((0)) FOR [DollarsPriorYTD]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactProviderSampledMonthly ------------------
---------------------------------------------
CREATE TABLE [fw].[FactProviderSampledMonthly] (
    [RowID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [OBForecastDetailID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Amount] decimal NOT NULL,
    [AmountYTD] decimal NOT NULL,
    [AmountPriorYear] decimal NOT NULL,
    [AmountPriorYTD] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NULL,
    [IsSystemGenerated] bit NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_FactProviderSampledMonthly] ON [fw].[FactProviderSampledMonthly] ([DepartmentID], [ProviderID], [OBForecastDetailID], [FiscalMonthID], [FiscalYearID], [TimeClassID]);
GO
ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_ProviderID] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_OBForecastDetailID] DEFAULT ((0)) FOR [OBForecastDetailID]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Amount] DEFAULT ((0)) FOR [Amount]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_AmountYTD] DEFAULT ((0)) FOR [AmountYTD]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_AmountPriorYear] DEFAULT ((0)) FOR [AmountPriorYear]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_AmountPriorYTD] DEFAULT ((0)) FOR [AmountPriorYTD]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_TransactionID] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactProviderSampledMonthly_Pivoted ------------------
---------------------------------------------
CREATE TABLE [fw].[FactProviderSampledMonthly_Pivoted] (
    [RowID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [OBForecastDetailID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Volume] decimal NOT NULL,
    [VolumeYTD] decimal NOT NULL,
    [VolumePriorYear] decimal NOT NULL,
    [VolumePriorYTD] decimal NOT NULL,
    [Dollars] decimal NOT NULL,
    [DollarsYTD] decimal NOT NULL,
    [DollarsPriorYear] decimal NOT NULL,
    [DollarsPriorYTD] decimal NOT NULL,
    [Hours] decimal NOT NULL,
    [HoursYTD] decimal NOT NULL,
    [HoursPriorYear] decimal NOT NULL,
    [HoursPriorYTD] decimal NOT NULL,
    [FTEs] decimal NOT NULL,
    [FTEsYTD] decimal NOT NULL,
    [FTEsPriorYear] decimal NOT NULL,
    [FTEsPriorYTD] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NULL,
    [IsSystemGenerated] bit NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_FactProviderSampledMonthly_Pivoted] ON [fw].[FactProviderSampledMonthly_Pivoted] ([DepartmentID], [ProviderID], [OBForecastDetailID], [FiscalMonthID], [FiscalYearID], [TimeClassID]);
GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_TransactionID] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_ProviderID] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_OBForecastDetailID] DEFAULT ((0)) FOR [OBForecastDetailID]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_Volume] DEFAULT ((0)) FOR [Volume]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_VolumeYTD] DEFAULT ((0)) FOR [VolumeYTD]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_VolumePriorYear] DEFAULT ((0)) FOR [VolumePriorYear]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_VolumePriorYTD] DEFAULT ((0)) FOR [VolumePriorYTD]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_Dollars] DEFAULT ((0)) FOR [Dollars]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_DollarsYTD] DEFAULT ((0)) FOR [DollarsYTD]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_DollarsPriorYear] DEFAULT ((0)) FOR [DollarsPriorYear]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_DollarsPriorYTD] DEFAULT ((0)) FOR [DollarsPriorYTD]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_Hours] DEFAULT ((0)) FOR [Hours]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_HoursYTD] DEFAULT ((0)) FOR [HoursYTD]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_HoursPriorYear] DEFAULT ((0)) FOR [HoursPriorYear]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_HoursPriorYTD] DEFAULT ((0)) FOR [HoursPriorYTD]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_FTEs] DEFAULT ((0)) FOR [FTEs]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_FTEsYTD] DEFAULT ((0)) FOR [FTEsYTD]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_FTEsPriorYear] DEFAULT ((0)) FOR [FTEsPriorYear]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_FTEsPriorYTD] DEFAULT ((0)) FOR [FTEsPriorYTD]; GO
ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactReportException ------------------
---------------------------------------------
CREATE TABLE [fw].[FactReportException] (
    [RowID] int NOT NULL,
    [ReportName] nvarchar(100) NOT NULL,
    [ExceptionCount] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fw].[FactReportException] ADD CONSTRAINT [DF_FactReportException_ReportName] DEFAULT ('') FOR [ReportName]; GO
ALTER TABLE [fw].[FactReportException] ADD CONSTRAINT [DF_FactReportException_ExceptionCount] DEFAULT ((0)) FOR [ExceptionCount]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactRoleAssignmentImport ------------------
---------------------------------------------
CREATE TABLE [fw].[FactRoleAssignmentImport] (
    [RowID] int NOT NULL,
    [PlanName] nvarchar(100) NOT NULL,
    [RoleName] nvarchar(100) NOT NULL,
    [UserNameCSV] nvarchar(max) NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fw].[FactRoleAssignmentImport] ADD CONSTRAINT [DF_RoleAssignmentImport_PlanName] DEFAULT ('') FOR [PlanName]; GO
ALTER TABLE [fw].[FactRoleAssignmentImport] ADD CONSTRAINT [DF_RoleAssignmentImport_RoleName] DEFAULT ('') FOR [RoleName]; GO
ALTER TABLE [fw].[FactRoleAssignmentImport] ADD CONSTRAINT [DF_RoleAssignmentImport_UserNameCSV] DEFAULT ('') FOR [UserNameCSV]; GO
ALTER TABLE [fw].[FactRoleAssignmentImport] ADD CONSTRAINT [DF_RoleAssignmentImport_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactRoleAssignmentImport] ADD CONSTRAINT [DF_RoleAssignmentImport_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactStagedDSModelingServiceLineRevenue ------------------
---------------------------------------------
CREATE TABLE [fw].[FactStagedDSModelingServiceLineRevenue] (
    [RowID] int NOT NULL,
    [EntityID] int NOT NULL,
    [FiscalYearID] int NOT NULL,
    [FiscalMonthID] int NOT NULL,
    [TimeClassID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [SPAccountRollupID] int NOT NULL,
    [OBForecastDetailID] int NOT NULL,
    [UnitTypeID] int NOT NULL,
    [Amount] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NULL,
    [ServiceLineID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Servi__0B0ECC0F] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__AgeCo__0C02F048] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Patie__0CF71481] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Medic__0DEB38BA] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Entit__49AB1D06] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Fisca__4B936578] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Fisca__4C8789B1] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__TimeC__4D7BADEA] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Payor__4E6FD223] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Payor__4F63F65C] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__SPAcc__50581A95] DEFAULT ((0)) FOR [SPAccountRollupID]; GO
ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__OBFor__514C3ECE] DEFAULT ((0)) FOR [OBForecastDetailID]; GO
ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__UnitT__52406307] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__IsDel__53348740] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Histo__5428AB79] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Trans__551CCFB2] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactStatisticDriverDepartmentSampledDaily ------------------
---------------------------------------------
CREATE TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] (
    [RowID] bigint NOT NULL,
    [DepartmentID] int NOT NULL,
    [DriverDepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [PayPeriodID] smallint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [DateID] int NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [Units] decimal NOT NULL,
    [TransactionID] int NULL,
    PRIMARY KEY ([RowID])
);

CREATE NONCLUSTERED INDEX [CORE_DepartmentID_AccountID_inc] ON [fw].[FactStatisticDriverDepartmentSampledDaily] ([DepartmentID], [AccountID]) INCLUDE ([IsDeleted]);
CREATE NONCLUSTERED INDEX [CORE_DepartmentID_AccountID_IsDeleted_inc] ON [fw].[FactStatisticDriverDepartmentSampledDaily] ([DepartmentID], [AccountID], [IsDeleted]) INCLUDE ([PayPeriodID], [TimeClassID], [DateID], [Units]);
GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_DateID] DEFAULT ((0)) FOR [DateID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_DriverDepartmentID] DEFAULT ((0)) FOR [DriverDepartmentID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_AccountID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_PayPeriodID] DEFAULT ((0)) FOR [PayPeriodID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_Units] DEFAULT ((0)) FOR [Units]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_TransactionID] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactStatisticDriverDepartmentSampledMonthly ------------------
---------------------------------------------
CREATE TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] (
    [RowID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [DriverDepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Amount] decimal NOT NULL,
    [AmountYTD] decimal NOT NULL,
    [AmountPriorYear] decimal NOT NULL,
    [AmountPriorYTD] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampled_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampled_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampled_DriverDepartmentID] DEFAULT ((0)) FOR [DriverDepartmentID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampled_StatisticID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampled_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampled_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampled_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledMonthly_Amount] DEFAULT ((0)) FOR [Amount]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledMonthly_AmountYTD] DEFAULT ((0)) FOR [AmountYTD]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledMonthly_AmountPriorYear] DEFAULT ((0)) FOR [AmountPriorYear]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledMonthly_AmountPriorYTD] DEFAULT ((0)) FOR [AmountPriorYTD]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampled_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF__FW_FactStatisticDriverDepartmentSampledMonthly_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactStatisticDriverDepartmentSampledPayPeriod ------------------
---------------------------------------------
CREATE TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] (
    [RowID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [DriverDepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [PayPeriodID] smallint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [Units] decimal NOT NULL,
    [UnitsYTD] decimal NOT NULL,
    [UnitsPriorYear] decimal NOT NULL,
    [UnitsPriorYTD] decimal NOT NULL,
    [TransactionID] int NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledPayPeriod_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDeptSampledPP_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDeptSampledPP_DriverDepartmentID] DEFAULT ((0)) FOR [DriverDepartmentID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledPayPeriod_AccountID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDeptSampledPP_PayPeriodID] DEFAULT ((0)) FOR [PayPeriodID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDeptSampledPP_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDeptSampledPP_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledPayPeriod_Units] DEFAULT ((0)) FOR [Units]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledPayPeriod_UnitsYTD] DEFAULT ((0)) FOR [UnitsYTD]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledPayPeriod_UnitsPriorYear] DEFAULT ((0)) FOR [UnitsPriorYear]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledPayPeriod_UnitsPriorYTD] DEFAULT ((0)) FOR [UnitsPriorYTD]; GO
ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF__FW_FactStatisticDriverDepartmentSampledPayPeriod_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactStatisticPrimarySampledMonthly ------------------
---------------------------------------------
CREATE TABLE [fw].[FactStatisticPrimarySampledMonthly] (
    [RowID] int NOT NULL,
    [AccountID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Amount] decimal NOT NULL,
    [AmountPriorYear] decimal NOT NULL,
    [AmountPriorYTD] decimal NOT NULL,
    [AmountYTD] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    [IsSystemGenerated] bit NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [fw].[FactStatisticPrimarySampledMonthly] ([AccountID], [DepartmentID], [FiscalMonthID], [FiscalYearID], [TimeClassID], [IsDeleted]);
CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactStatisticPrimarySampledMonthly] ([IsDeleted]);
GO
ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF_FactStatisticPrimarySampledMonthly_AccountID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF_FactStatisticPrimarySampledMonthly_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF_FactStatisticPrimarySampledMonthly_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO
ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Histo__7B1462B5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Fisca__74676526] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Fisca__755B895F] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Amoun__764FAD98] DEFAULT ((0)) FOR [Amount]; GO
ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Amoun__7743D1D1] DEFAULT ((0)) FOR [AmountPriorYear]; GO
ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Amoun__7837F60A] DEFAULT ((0)) FOR [AmountPriorYTD]; GO
ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Amoun__792C1A43] DEFAULT ((0)) FOR [AmountYTD]; GO
ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__IsDel__7A203E7C] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Trans__7C0886EE] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF_FactStatisticPrimarySampledMonthly_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactStatisticSampledDaily ------------------
---------------------------------------------
CREATE TABLE [fw].[FactStatisticSampledDaily] (
    [RowID] bigint NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [PayPeriodID] smallint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [DateID] int NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [Units] decimal NOT NULL,
    [TransactionID] int NULL,
    [BigRowID] bigint NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_FactStatisticSampledDaily] ON [fw].[FactStatisticSampledDaily] ([AccountID], [DepartmentID], [PayPeriodID], [DateID], [TimeClassID]);
GO
ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [FK_FactStatisticSampledDaily_DimAccount] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [FK_FactStatisticSampledDaily_DimDate] FOREIGN KEY ([DateID]) REFERENCES [fw].[DimDate] ([DateID]); GO
ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [FK_FactStatisticSampledDaily_DimDepartment] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [FK_FactStatisticSampledDaily_DimPayPeriod] FOREIGN KEY ([PayPeriodID]) REFERENCES [fw].[DimPayPeriod] ([PayPeriodID]); GO
ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [FK_FactStatisticSampledDaily_DimTimeClass] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_AccountID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_PayPeriodID] DEFAULT ((0)) FOR [PayPeriodID]; GO
ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_DateID] DEFAULT ((0)) FOR [DateID]; GO
ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_Units] DEFAULT ((0)) FOR [Units]; GO
ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_TransactionID] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactStatisticSampledMonthly ------------------
---------------------------------------------
CREATE TABLE [fw].[FactStatisticSampledMonthly] (
    [RowID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Amount] decimal NOT NULL,
    [AmountYTD] decimal NOT NULL,
    [AmountPriorYear] decimal NOT NULL,
    [AmountPriorYTD] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NULL,
    [IsSystemGenerated] bit NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_FactStatisticSampledMonthly] ON [fw].[FactStatisticSampledMonthly] ([AccountID], [DepartmentID], [FiscalYearID], [FiscalMonthID], [TimeClassID]);
CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactStatisticSampledMonthly] ([IsDeleted]);
GO
ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampled_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF__FW_FactStatisticSampledMonthly_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampledMonthly_Amount] DEFAULT ((0)) FOR [Amount]; GO
ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampledMonthly_AmountYTD] DEFAULT ((0)) FOR [AmountYTD]; GO
ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampledMonthly_AmountPriorYear] DEFAULT ((0)) FOR [AmountPriorYear]; GO
ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampledMonthly_AmountPriorYTD] DEFAULT ((0)) FOR [AmountPriorYTD]; GO
ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampledMonthly_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO
ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampled_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampled_StatisticID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampled_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampled_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampled_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampled_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactStatisticSampledPayPeriod ------------------
---------------------------------------------
CREATE TABLE [fw].[FactStatisticSampledPayPeriod] (
    [RowID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [PayPeriodID] smallint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [Units] decimal NOT NULL,
    [UnitsYTD] decimal NOT NULL,
    [UnitsPriorYear] decimal NOT NULL,
    [UnitsPriorYTD] decimal NOT NULL,
    [TransactionID] int NULL,
    [IsSystemGenerated] bit NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_FactStatisticSampledPayPeriod] ON [fw].[FactStatisticSampledPayPeriod] ([AccountID], [DepartmentID], [PayPeriodID], [TimeClassID]);
CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactStatisticSampledPayPeriod] ([IsDeleted]);
GO
ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [FK_FactStatisticSampledPayPeriod_DimAccount] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [FK_FactStatisticSampledPayPeriod_FactStatisticSampledPayPeriod] FOREIGN KEY ([RowID]) REFERENCES [fw].[FactStatisticSampledPayPeriod] ([RowID]); GO
ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [FK_FactStatisticSampledPP_DimPayPeriod] FOREIGN KEY ([PayPeriodID]) REFERENCES [fw].[DimPayPeriod] ([PayPeriodID]); GO
ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [FK_FactStatisticSampledPP_DimTimeClass] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [FK_FactStatisticSampledPP_FactStatisticSampled] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF__FW_FactStatisticSampledPayPeriod_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPayPeriod_Units] DEFAULT ((0)) FOR [Units]; GO
ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPayPeriod_AccountID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPayPeriod_UnitsYTD] DEFAULT ((0)) FOR [UnitsYTD]; GO
ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPP_PayPeriodID] DEFAULT ((0)) FOR [PayPeriodID]; GO
ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPayPeriod_UnitsPriorYear] DEFAULT ((0)) FOR [UnitsPriorYear]; GO
ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPP_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPayPeriod_UnitsPriorYTD] DEFAULT ((0)) FOR [UnitsPriorYTD]; GO
ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPP_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPayPeriod_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO
ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPP_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPP_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactStatisticSecondarySampledMonthly ------------------
---------------------------------------------
CREATE TABLE [fw].[FactStatisticSecondarySampledMonthly] (
    [RowID] int NOT NULL,
    [AccountID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Amount] decimal NOT NULL,
    [AmountPriorYear] decimal NOT NULL,
    [AmountPriorYTD] decimal NOT NULL,
    [AmountYTD] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    [IsSystemGenerated] bit NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [fw].[FactStatisticSecondarySampledMonthly] ([AccountID], [DepartmentID], [FiscalMonthID], [FiscalYearID], [TimeClassID], [IsDeleted]);
CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactStatisticSecondarySampledMonthly] ([IsDeleted]);
GO
ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Fisca__02B5847D] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF_FactStatisticSecondarySampledMonthly_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Fisca__03A9A8B6] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF_FactStatisticSecondarySampledMonthly_AccountID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Amoun__049DCCEF] DEFAULT ((0)) FOR [Amount]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF_FactStatisticSecondarySampledMonthly_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Amoun__0591F128] DEFAULT ((0)) FOR [AmountPriorYear]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Amoun__06861561] DEFAULT ((0)) FOR [AmountPriorYTD]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Amoun__077A399A] DEFAULT ((0)) FOR [AmountYTD]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__IsDel__086E5DD3] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Trans__0A56A645] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF_FactStatisticSecondarySampledMonthly_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Histo__0962820C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactStatisticSecondarySampledbyPayPeriod ------------------
---------------------------------------------
CREATE TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] (
    [RowID] int NOT NULL,
    [AccountID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [PayPeriodID] smallint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Units] decimal NOT NULL,
    [UnitsPriorYear] decimal NOT NULL,
    [UnitsPriorYTD] decimal NOT NULL,
    [UnitsYTD] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    [IsSystemGenerated] bit NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactStatisticSecondarySampledbyPayPeriod] ([IsDeleted]);
GO
ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF_FactStatisticSecondarySampledbyPayPeriod_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF_FactStatisticSecondarySampledbyPayPeriod_AccountID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF_FactStatisticSecondarySampledbyPayPeriod_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF_FactStatisticSecondarySampledbyPayPeriod_PayPeriodID] DEFAULT ((0)) FOR [PayPeriodID]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF_FactStatisticSecondarySampledbyPayPeriod_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Units__541DBE81] DEFAULT ((0)) FOR [Units]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Units__5511E2BA] DEFAULT ((0)) FOR [UnitsPriorYear]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Units__560606F3] DEFAULT ((0)) FOR [UnitsPriorYTD]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Units__56FA2B2C] DEFAULT ((0)) FOR [UnitsYTD]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Histo__58E2739E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF__FactStati__IsDel__57EE4F65] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Trans__59D697D7] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactSystemGeneratedStatistics ------------------
---------------------------------------------
CREATE TABLE [fw].[FactSystemGeneratedStatistics] (
    [RowID] bigint NOT NULL,
    [DateID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [Value] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fw].[FactSystemGeneratedStatistics] ADD CONSTRAINT [DF_FactSystemGeneratedStatistics_DateID] DEFAULT ((0)) FOR [DateID]; GO
ALTER TABLE [fw].[FactSystemGeneratedStatistics] ADD CONSTRAINT [DF_FactSystemGeneratedStatistics_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactSystemGeneratedStatistics] ADD CONSTRAINT [DF_FactSystemGeneratedStatistics_AccountID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[FactSystemGeneratedStatistics] ADD CONSTRAINT [DF_FactSystemGeneratedStatistics_Value] DEFAULT ((0)) FOR [Value]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactSystemGeneratedStatisticsMonthly ------------------
---------------------------------------------
CREATE TABLE [fw].[FactSystemGeneratedStatisticsMonthly] (
    [RowID] bigint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [Value] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fw].[FactSystemGeneratedStatisticsMonthly] ADD CONSTRAINT [DF_FactSystemGeneratedStatisticsMonthly_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fw].[FactSystemGeneratedStatisticsMonthly] ADD CONSTRAINT [DF_FactSystemGeneratedStatisticsMonthly_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fw].[FactSystemGeneratedStatisticsMonthly] ADD CONSTRAINT [DF_FactSystemGeneratedStatisticsMonthly_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactSystemGeneratedStatisticsMonthly] ADD CONSTRAINT [DF_FactSystemGeneratedStatisticsMonthly_AccountID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[FactSystemGeneratedStatisticsMonthly] ADD CONSTRAINT [DF_FactSystemGeneratedStatisticsMonthly_Value] DEFAULT ((0)) FOR [Value]; GO

---------------------------------------------

---------------------------------------------
-- fw.FactUserDeptXWalk ------------------
---------------------------------------------
CREATE TABLE [fw].[FactUserDeptXWalk] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [Value] int NOT NULL,
    [RowID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [IsDeleted] bit NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fw].[FactUserDeptXWalk] ADD CONSTRAINT [DF__FW_FactUserDeptXWalk_MemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MemberGUID]; GO
ALTER TABLE [fw].[FactUserDeptXWalk] ADD CONSTRAINT [DF__FW_FactUserDeptXWalk_Department] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fw].[FactUserDeptXWalk] ADD CONSTRAINT [DF_FW_FactUserDeptXWalk_Value] DEFAULT ((1)) FOR [Value]; GO
ALTER TABLE [fw].[FactUserDeptXWalk] ADD CONSTRAINT [DF_FW_FactUserDeptXWalk_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fw].[FactUserDeptXWalk] ADD CONSTRAINT [DF_FW_FactUserDeptXWalk_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fw].[FactUserDeptXWalk] ADD CONSTRAINT [DF__FW_FactUserDeptXWalk_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fw].[FactUserDeptXWalk] ADD CONSTRAINT [DF_FW_FactUserDeptXWalk_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO

---------------------------------------------

---------------------------------------------
-- fw.MRPRMetricMapping ------------------
---------------------------------------------
CREATE TABLE [fw].[MRPRMetricMapping] (
    [MappingID] int NOT NULL,
    [PRMetricID] int NOT NULL,
    [MRMetricGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([MappingID])
);

CREATE UNIQUE NONCLUSTERED INDEX [UK_MRPRMetricMapping] ON [fw].[MRPRMetricMapping] ([PRMetricID], [MRMetricGUID]);
GO
ALTER TABLE [fw].[MRPRMetricMapping] ADD CONSTRAINT [FK_MRPRMetricMapping_MetricGUID] FOREIGN KEY ([MRMetricGUID]) REFERENCES [dbo].[CMMetric] ([MetricGUID]); GO
ALTER TABLE [fw].[MRPRMetricMapping] ADD CONSTRAINT [FK_MRPRMetricMapping_PRMetricID] FOREIGN KEY ([PRMetricID]) REFERENCES [pi].[DimMetric] ([MetricID]); GO

---------------------------------------------

---------------------------------------------
-- fw.MrPrFeaturedMetric ------------------
---------------------------------------------
CREATE TABLE [fw].[MrPrFeaturedMetric] (
    [MrPrFeaturedMetricId] int NOT NULL,
    [IsPr] bit NOT NULL,
    [DisplayOrder] int NOT NULL,
    [MetricGUID] uniqueidentifier NOT NULL,
    [RollupLevelID] tinyint NOT NULL,
    PRIMARY KEY ([MrPrFeaturedMetricId])
);
GO
ALTER TABLE [fw].[MrPrFeaturedMetric] ADD CONSTRAINT [DF__MrPrFeatu__Rollu__2001F360] DEFAULT ((1)) FOR [RollupLevelID]; GO

---------------------------------------------

---------------------------------------------
-- fw.PrimaryStatisticsRollupsConfiguration ------------------
---------------------------------------------
CREATE TABLE [fw].[PrimaryStatisticsRollupsConfiguration] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [RollupLevel] varchar(250) NOT NULL,
    [RollupMemberID] int NOT NULL,
    [AccountID] int NOT NULL,
    [Revenue] bit NOT NULL,
    [Staffing] bit NOT NULL,
    [NonStaffing] bit NOT NULL,
    PRIMARY KEY ([MemberGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [AK_PrimaryStatisticsRollupsConfiguration] ON [fw].[PrimaryStatisticsRollupsConfiguration] ([RollupLevel], [RollupMemberID], [AccountID]);
GO
ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [FK_PrimaryStatisticsRollupsConfiguration_Account] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [CK_PrimaryStatisticsRollupsConfiguration_RollupLevel] CHECK ([RollupLevel]='DepartmentRollup6' OR [RollupLevel]='DepartmentRollup5' OR [RollupLevel]='DepartmentRollup4' OR [RollupLevel]='DepartmentRollup3' OR [RollupLevel]='DepartmentRollup2' OR [RollupLevel]='DepartmentRollup1' OR [RollupLevel]='Entity' OR [RollupLevel]='System'); GO
ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [DF__PrimarySt__Membe__3ACCF6A6] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [DF__PrimarySt__Rollu__3BC11ADF] DEFAULT ('') FOR [RollupLevel]; GO
ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [DF__PrimarySt__Rollu__3CB53F18] DEFAULT ((0)) FOR [RollupMemberID]; GO
ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [DF__PrimarySt__Accou__3DA96351] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [DF__PrimarySt__Reven__3E9D878A] DEFAULT ((0)) FOR [Revenue]; GO
ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [DF__PrimarySt__Staff__3F91ABC3] DEFAULT ((0)) FOR [Staffing]; GO
ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [DF__PrimarySt__NonSt__4085CFFC] DEFAULT ((0)) FOR [NonStaffing]; GO

---------------------------------------------

---------------------------------------------
-- fw.SPHACTROLLUP_StandardCodesBackup ------------------
---------------------------------------------
CREATE TABLE [fw].[SPHACTROLLUP_StandardCodesBackup] (
    [Name] nvarchar(max) NOT NULL,
    [SPHAccountRollupCode] nvarchar(max) NOT NULL
);
GO
ALTER TABLE [fw].[SPHACTROLLUP_StandardCodesBackup] ADD CONSTRAINT [DF__SPHACTROLL__Name__2FD86876] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[SPHACTROLLUP_StandardCodesBackup] ADD CONSTRAINT [DF__SPHACTROL__SPHAc__30CC8CAF] DEFAULT ('') FOR [SPHAccountRollupCode]; GO

---------------------------------------------

---------------------------------------------
-- fw.SPHDEPARTMENTROLLUP_StandardCodesBackup ------------------
---------------------------------------------
CREATE TABLE [fw].[SPHDEPARTMENTROLLUP_StandardCodesBackup] (
    [Name] nvarchar(max) NOT NULL,
    [SPHDepartmentRollupCode] nvarchar(max) NOT NULL
);
GO
ALTER TABLE [fw].[SPHDEPARTMENTROLLUP_StandardCodesBackup] ADD CONSTRAINT [DF__SPHDEPARTM__Name__39384F0B] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[SPHDEPARTMENTROLLUP_StandardCodesBackup] ADD CONSTRAINT [DF__SPHDEPART__SPHDe__3A2C7344] DEFAULT ('') FOR [SPHDepartmentRollupCode]; GO

---------------------------------------------

---------------------------------------------
-- fw.SPHDEPARTMENTTYPE_StandardCodesBackup ------------------
---------------------------------------------
CREATE TABLE [fw].[SPHDEPARTMENTTYPE_StandardCodesBackup] (
    [Name] nvarchar(max) NOT NULL,
    [SPHDepartmentTypeCode] nvarchar(max) NOT NULL
);
GO
ALTER TABLE [fw].[SPHDEPARTMENTTYPE_StandardCodesBackup] ADD CONSTRAINT [DF__SPHDEPARTM__Name__4A6CFCAE] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[SPHDEPARTMENTTYPE_StandardCodesBackup] ADD CONSTRAINT [DF__SPHDEPART__SPHDe__4B6120E7] DEFAULT ('') FOR [SPHDepartmentTypeCode]; GO

---------------------------------------------

---------------------------------------------
-- fw.SPHJOBCODEROLLUP_StandardCodesBackup ------------------
---------------------------------------------
CREATE TABLE [fw].[SPHJOBCODEROLLUP_StandardCodesBackup] (
    [Name] nvarchar(max) NOT NULL,
    [SPHJobCodeRollupCode] nvarchar(max) NOT NULL
);
GO
ALTER TABLE [fw].[SPHJOBCODEROLLUP_StandardCodesBackup] ADD CONSTRAINT [DF__SPHJOBCODE__Name__337F75B5] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[SPHJOBCODEROLLUP_StandardCodesBackup] ADD CONSTRAINT [DF__SPHJOBCOD__SPHJo__347399EE] DEFAULT ('') FOR [SPHJobCodeRollupCode]; GO

---------------------------------------------

---------------------------------------------
-- fw.SPHPAYCODEROLLUP_StandardCodesBackup ------------------
---------------------------------------------
CREATE TABLE [fw].[SPHPAYCODEROLLUP_StandardCodesBackup] (
    [Name] nvarchar(max) NOT NULL,
    [SPHPayCodeRollupCode] nvarchar(max) NOT NULL
);
GO
ALTER TABLE [fw].[SPHPAYCODEROLLUP_StandardCodesBackup] ADD CONSTRAINT [DF__SPHPAYCODE__Name__70F363A0] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[SPHPAYCODEROLLUP_StandardCodesBackup] ADD CONSTRAINT [DF__SPHPAYCOD__SPHPa__71E787D9] DEFAULT ('') FOR [SPHPayCodeRollupCode]; GO

---------------------------------------------

---------------------------------------------
-- fw.SectionSecurityImport ------------------
---------------------------------------------
CREATE TABLE [fw].[SectionSecurityImport] (
    [ID] int NOT NULL,
    [GroupName] varchar(255) NULL,
    [BasicGUID] varchar(255) NULL,
    [AdvancedGUID] varchar(255) NULL
);
GO

---------------------------------------------

---------------------------------------------
-- fw.SystemSetting ------------------
---------------------------------------------
CREATE TABLE [fw].[SystemSetting] (
    [SystemSettingID] int NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Description] nvarchar(400) NOT NULL,
    [Value] nvarchar(max) NOT NULL,
    [IsEditable] bit NOT NULL,
    [ColumnType] int NOT NULL,
    [DefaultValue] nvarchar(100) NOT NULL,
    [IsEncrypted] bit NOT NULL,
    [SystemSettingCategoryID] int NOT NULL,
    PRIMARY KEY ([SystemSettingID])
);

CREATE UNIQUE NONCLUSTERED INDEX [AK_Name] ON [fw].[SystemSetting] ([Name]);
GO
ALTER TABLE [fw].[SystemSetting] ADD CONSTRAINT [DF_SYSTEMSETTING_VALUE] DEFAULT ('') FOR [Value]; GO
ALTER TABLE [fw].[SystemSetting] ADD CONSTRAINT [DF__SystemSett__Name__6D80CB2D] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fw].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Descr__6E74EF66] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fw].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__IsEdi__705D37D8] DEFAULT ((0)) FOR [IsEditable]; GO
ALTER TABLE [fw].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Colum__71515C11] DEFAULT ((0)) FOR [ColumnType]; GO
ALTER TABLE [fw].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Defau__7245804A] DEFAULT ('') FOR [DefaultValue]; GO
ALTER TABLE [fw].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__IsEnc__7339A483] DEFAULT ('0') FOR [IsEncrypted]; GO
ALTER TABLE [fw].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Syste__7EAB572F] DEFAULT ((0)) FOR [SystemSettingCategoryID]; GO

---------------------------------------------

---------------------------------------------
-- fw.SystemSettingCategory ------------------
---------------------------------------------
CREATE TABLE [fw].[SystemSettingCategory] (
    [SystemSettingCategoryID] int NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    PRIMARY KEY ([SystemSettingCategoryID])
);
GO
ALTER TABLE [fw].[SystemSettingCategory] ADD CONSTRAINT [DF__SystemSett__Name__7DB732F6] DEFAULT ('') FOR [Name]; GO

---------------------------------------------

---------------------------------------------
-- fw.viewDimAccount_custom ------------------
---------------------------------------------
CREATE TABLE [fw].[viewDimAccount_custom] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([MemberGUID])
);
GO
ALTER TABLE [fw].[viewDimAccount_custom] ADD CONSTRAINT [DF__viewDimAc__Membe__2A065A39] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fw].[viewDimAccount_custom] ADD CONSTRAINT [DF__viewDimAc__Histo__2AFA7E72] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------
---------------------------------------------
--  VIEWS
---------------------------------------------

-- fw.BudgetReallocationWithDefinedType
/************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2018-01-17	IP		B-16703 Omit archived budget adjustments
*************************************************************/
CREATE view [fw].[BudgetReallocationWithDefinedType]
as
SELECT distinct
b.BudgetReallocationGUID,
Date,
SourceDepartmentID,SourceAccountID,TargetDepartmentID,TargetAccountID,UnitTypeID,FiscalMonthID,FiscalYearID,SourceJobCodeID,TargetJobCodeID,DataType,
ShouldUpply = case when Change = 0 then 0 else 1 end,
BudgetReallocationType = case 
	WHEN b.SourceDepartmentID <> 0
		and b.SourceAccountID <> 0
		and b.TargetDepartmentID <> 0
		and b.TargetAccountID <> 0
		and b.GroupGUID = '00000000-0000-0000-0000-000000000000'
	THEN 'ReallocateSingle' 
	WHEN b.SourceDepartmentID <> 0
		and b.SourceAccountID <> 0
		and b.TargetDepartmentID <> 0
		and b.TargetAccountID <> 0
		and b.GroupGUID <> '00000000-0000-0000-0000-000000000000'
	THEN 'ReallocateMulti' 
	WHEN b.SourceDepartmentID <> 0
		and b.SourceAccountID <> 0
		and b.TargetDepartmentID = 0
		and b.TargetAccountID = 0
		and b.GroupGUID  = '00000000-0000-0000-0000-000000000000'
	THEN 'AdjustMontly'
	WHEN b.SourceDepartmentID <> 0
		and b.SourceAccountID <> 0
		and b.TargetDepartmentID = 0
		and b.TargetAccountID = 0
		and b.GroupGUID <> '00000000-0000-0000-0000-000000000000'
	THEN 'ManualFile' 
	END
FROM [mr].[BudgetReallocation] b
INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
WHERE Archived = 0
GO


---------------------------------------------

-- fw.viewABBFlexingReconciliation
CREATE VIEW [fw].[viewABBFlexingReconciliation]
	AS
	
	SELECT
		CostingConfigGUID,
		FiscalYearID,
		FiscalMonthID,
		EntityID,
		DepartmentID,
		ChargeCodeID,
		AccountID,
		JobCodeID,
		PayCodeID,
		CostComponentID,
		ActualChargeUnits,
		ActualChargeUnitsYTD,
		ActualVariableDirectCost,
		ActualVariableDirectCostYTD,
		ActualFixedDirectCost,
		ActualFixedDirectCostYTD,
		BudgetChargeUnits,
		BudgetChargeUnitsYTD,
		BudgetVariableDirectCost,
		BudgetVariableDirectCostYTD,
		BudgetFixedDirectCost,
		BudgetFixedDirectCostYTD,
		FlexedVariableDirectCost,
		FlexedVariableDirectCostYTD
	FROM
		 [fw].[ABBFlexingReconciliation]
GO


---------------------------------------------

-- fw.viewDepartmentChargeCodeStatisticMapping
CREATE VIEW [fw].[viewDepartmentChargeCodeStatisticMapping]
AS
/*
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2018-05-04	IP		B-19364		MRPR - Set Global Weights for Charge Codes - System Center Page
** 2		2018-06-07	IP		TK-58757	Refactored view
************************************************************
*/
SELECT *
FROM (
	SELECT M.RowID, M.FiscalYearID, D.DepartmentID, M.ChargeCodeID, M.PatientTypeRollupID, M.AccountID, M.Weight, M.IsReviewed, ROW_NUMBER() OVER (
			PARTITION BY M.FiscalYearID, D.DepartmentID, M.ChargeCodeID, M.PatientTypeRollupID, M.AccountID ORDER BY L.SortOrder DESC
			) AS PriorityOrder
	FROM (
		SELECT M.RowID, M.FiscalYearID, M.DepartmentRollupLevelMemberID, M.DepartmentRollupLevelMemberColumnName, M.ChargeCodeID, M.PatientTypeRollupID, M.AccountID, M.Weight, M.IsReviewed
		FROM fw.DepartmentChargeCodeStatisticMapping M
		WHERE M.DepartmentRollupLevelMemberID != 0
		) M
	INNER JOIN (
		SELECT L.ColumnName, L.SortOrder
		FROM viewScoreHierarchyAttributeLinkCore30 L
		JOIN ScoreDimension S
			ON S.DefaultHierarchyGUID = L.HierarchyGUID
		WHERE S.GlobalID = 'Department'
		) L
		ON L.ColumnName = M.DepartmentRollupLevelMemberColumnName
	JOIN (
		SELECT DepartmentID, DepartmentID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'DepartmentID'
		FROM fw.ViewDimDepartment_Real
		
		UNION ALL
		
		SELECT DepartmentID, DepartmentRollup1ID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'DepartmentRollup1ID'
		FROM fw.ViewDimDepartment_Real
		
		UNION ALL
		
		SELECT DepartmentID, DepartmentRollup2ID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'DepartmentRollup2ID'
		FROM fw.ViewDimDepartment_Real
		
		UNION ALL
		
		SELECT DepartmentID, DepartmentRollup3ID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'DepartmentRollup3ID'
		FROM fw.ViewDimDepartment_Real
		
		UNION ALL
		
		SELECT DepartmentID, DepartmentRollup4ID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'DepartmentRollup4ID'
		FROM fw.ViewDimDepartment_Real
		
		UNION ALL
		
		SELECT DepartmentID, DepartmentRollup5ID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'DepartmentRollup5ID'
		FROM fw.ViewDimDepartment_Real
		
		UNION ALL
		
		SELECT DepartmentID, DepartmentRollup6ID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'DepartmentRollup6ID'
		FROM fw.ViewDimDepartment_Real
		
		UNION ALL
		
		SELECT DepartmentID, EntityID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'EntityID'
		FROM fw.ViewDimDepartment_Real
		
		UNION ALL
		
		SELECT DepartmentID, SystemID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'SystemID'
		FROM fw.ViewDimDepartment_Real
		) D
		ON D.DepartmentRollupLevelMemberID = M.DepartmentRollupLevelMemberID AND M.DepartmentRollupLevelMemberColumnName = D.DepartmentRollupLevelMemberColumnName
	) SUBSELECT
WHERE PriorityOrder = 1
GO


---------------------------------------------

-- fw.viewDimAccount
CREATE VIEW [fw].[viewDimAccount]
AS
SELECT

[AccountID],
 COALESCE([Name],'') as [Name],
[AccountCode],
[Description],
[GLRollup],
[IsInverted],
[PatientClassID],
[CAPIsDefined],
[DSSIsDefined],
[DSSCostComponent],
[DSSStatisticDriver],
[DSSAccountRollup1ID],
[DSSAccountRollup2ID],
[DSSAccountRollup3ID],
[MRIsDefined],
[FlexStatistic],
[FlexValue],
[FlexBucketGUID],
[OBIsDefined],
[IsStat],
[IsGlobal],
[IsExpense],
[Variability],
[OBDollarsFinancialReportingID],
 COALESCE([OBDollarsFinancialReportingCategory],'') as [OBDollarsFinancialReportingCategory],
[OBUnitsFinancialReportingID],
 COALESCE([OBUnitsFinancialReportingCategory],'') as [OBUnitsFinancialReportingCategory],
[OBAccountPHID],
[OBStatModelSectionID],
[OBStatUnitTypeID],
[OBStaffing],
[OBPayorID],
[OBPayorGroupID],
[SPIsDefined],
[PatientTypeRollupID],
[SPAccountRollupID],
 COALESCE([SPAccountRollupCategory],'') as [SPAccountRollupCategory],
[SPStatAccountRollup],
[SPPayorGroupID],
[SPPhysicianGroupID],
[SPJobCodeGroupID],
[SPCapitalRollupID],
[SPDebtIssuanceID],
[SPIsPhysicianOverride],
[PatientTypeID],
[Inversion],
 COALESCE([PatientClass],'') as [PatientClass],
 COALESCE([DSSAccountRollup1Name],'') as [DSSAccountRollup1Name],
 COALESCE([DSSAccountRollup1Category],'') as [DSSAccountRollup1Category],
 COALESCE([DSSAccountRollup2Name],'') as [DSSAccountRollup2Name],
 COALESCE([DSSAccountRollup3Name],'') as [DSSAccountRollup3Name],
 COALESCE([OBDollarsFinancialReporting],'') as [OBDollarsFinancialReporting],
[OBDollarsFinancialReportingSortOrder],
 COALESCE([OBDollarsFinancialReportingLineName],'') as [OBDollarsFinancialReportingLineName],
 COALESCE([OBUnitsFinancialReporting],'') as [OBUnitsFinancialReporting],
[OBUnitsFinancialReportingSortOrder],
 COALESCE([OBUnitsFinancialReportingLineName],'') as [OBUnitsFinancialReportingLineName],
 COALESCE([OBModelSectionName],'') as [OBModelSectionName],
 COALESCE([OBStatModelSectionName],'') as [OBStatModelSectionName],
 COALESCE([OBUnitType],'') as [OBUnitType],
 COALESCE([OBPayor],'') as [OBPayor],
 COALESCE([OBPayorGroup],'') as [OBPayorGroup],
 COALESCE([PatientTypeRollupName],'') as [PatientTypeRollupName],
 COALESCE([SPAccountRollupName],'') as [SPAccountRollupName],
 COALESCE([SPStatAccountRollupName],'') as [SPStatAccountRollupName],
 COALESCE([SPPayorGroupName],'') as [SPPayorGroupName],
[SPHAccountRollupID],
 COALESCE([SPHAccountRollupName],'') as [SPHAccountRollupName],
[SPHAccountRollupConfidenceScore],
 COALESCE([SPPhysicianGroupName],'') as [SPPhysicianGroupName],
 COALESCE([SPJobCodeGroupName],'') as [SPJobCodeGroupName],
 COALESCE([SPCapitalRollupName],'') as [SPCapitalRollupName],
 COALESCE([SPDebtIssuanceName],'') as [SPDebtIssuanceName],
[MemberGUID],
[HistoryItemGUID],
[DSSAccountRollup4ID],
[DSSAccountRollup5ID],
[DSSAccountRollup6ID],
[DSSAccountRollup7ID],
 COALESCE([DSSAccountRollup4],'') as [DSSAccountRollup4],
 COALESCE([DSSAccountRollup4Name],'') as [DSSAccountRollup4Name],
 COALESCE([DSSAccountRollup2Category],'') as [DSSAccountRollup2Category],
 COALESCE([DSSAccountRollup5Name],'') as [DSSAccountRollup5Name],
 COALESCE([DSSAccountRollup6Name],'') as [DSSAccountRollup6Name],
 COALESCE([DSSAccountRollup7Name],'') as [DSSAccountRollup7Name],
 COALESCE([DSSAccountRollup3Category],'') as [DSSAccountRollup3Category],
 COALESCE([DSSAccountRollup4Category],'') as [DSSAccountRollup4Category],
[FWIsDefined],
[AccountCodeRaw],
[GMAccountRollup1],
[GMAccountRollup2],
[GMAccountRollup3],
[GMAccountRollup4],
[GMAccountRollup5],
[GMAccountRollup6],
[GMAccountRollup7],
[SPHVariability],
 COALESCE([SPHCostComponent],'') as [SPHCostComponent],
 COALESCE([SPHCostComponentRollup],'') as [SPHCostComponentRollup],
[IsSPHCostModel],
 COALESCE([SPHLineItem],'') as [SPHLineItem],
 COALESCE([SPHStatement],'') as [SPHStatement],
 COALESCE([SPHCategory],'') as [SPHCategory],
[SPHAccountRollupIsValidated],
 COALESCE([SPHSection],'') as [SPHSection],
[IsCBP]    ,[Version]

FROM [fw].[DimAccount] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimAccount_source
CREATE VIEW [fw].[viewDimAccount_source]
AS
SELECT
   grp5D92C559C8004C18BF821C58E1977A6C.[AccountID]
   ,grp5D92C559C8004C18BF821C58E1977A6C.[Name]
   ,grp5D92C559C8004C18BF821C58E1977A6C.[PatientTypeID]
   ,grp5D92C559C8004C18BF821C58E1977A6C.[Inversion]
   ,grp5D92C559C8004C18BF821C58E1977A6C.[SPHAccountRollupID]
   ,grp5D92C559C8004C18BF821C58E1977A6C.[MemberGUID]
   ,grp5D92C559C8004C18BF821C58E1977A6C.[HistoryItemGUID]
   ,ISNULL([PATIENTCLASS].[Name], 'Not Specified') as [PatientClass]
   ,ISNULL([DSSACTROL1].[Name], 'Not Specified') as [DSSAccountRollup1Name]
   ,ISNULL([DSSACTROL1].[Category], 'Not Specified') as [DSSAccountRollup1Category]
   ,ISNULL([DSSACTROL2].[Name], 'Not Specified') as [DSSAccountRollup2Name]
   ,ISNULL([DSSACTROL2].[Category], 'Not Specified') as [DSSAccountRollup2Category]
   ,ISNULL([DSSACTROL3].[Name], 'Not Specified') as [DSSAccountRollup3Name]
   ,ISNULL([DSSACTROL3].[Category], 'Not Specified') as [DSSAccountRollup3Category]
   ,ISNULL([OBFINANCIALREP].[IsExpense], 0) as [IsExpense]
   ,ISNULL([OBFINANCIALREP].[Section], 'Not Specified') as [OBDollarsFinancialReportingCategory]
   ,ISNULL([OBFINANCIALREP].[Name], 'Not Specified') as [OBDollarsFinancialReporting]
   ,ISNULL([OBFINANCIALREP].[SortOrder], 0) as [OBDollarsFinancialReportingSortOrder]
   ,ISNULL([OBFINANCIALREP].[LineName], 'Not Specified') as [OBDollarsFinancialReportingLineName]
   ,ISNULL([OBFINANCIALREP_1].[Section], 'Not Specified') as [OBUnitsFinancialReportingCategory]
   ,ISNULL([OBFINANCIALREP_1].[Name], 'Not Specified') as [OBUnitsFinancialReporting]
   ,ISNULL([OBFINANCIALREP_1].[SortOrder], 0) as [OBUnitsFinancialReportingSortOrder]
   ,ISNULL([OBFINANCIALREP_1].[LineName], 'Not Specified') as [OBUnitsFinancialReportingLineName]
   ,ISNULL([ACCOUNTPH].[Name], 'Not Specified') as [OBModelSectionName]
   ,ISNULL([ACCOUNTPH_1].[Name], 'Not Specified') as [OBStatModelSectionName]
   ,ISNULL([UNITTYPE].[Name], 'Not Specified') as [OBUnitType]
   ,ISNULL([PAYOR].[Name], 'Not Specified') as [OBPayor]
   ,ISNULL([PayorGroup].[Name], 'Not Specified') as [OBPayorGroup]
   ,ISNULL([PayorGroup_1].[Name], 'Not Specified') as [SPPayorGroupName]
   ,ISNULL([PatientTyRo].[Name], 'Not Specified') as [PatientTypeRollupName]
   ,ISNULL([SPAccountRollup].[Category], 'Not Specified') as [SPAccountRollupCategory]
   ,ISNULL([SPAccountRollup].[Name], 'Not Specified') as [SPAccountRollupName]
   ,ISNULL([SPAccountRollup_1].[Name], 'Not Specified') as [SPStatAccountRollupName]
   ,ISNULL([PhyGrp].[Name], 'Not Specified') as [SPPhysicianGroupName]
   ,ISNULL([JobCodeGrp].[Name], 'Not Specified') as [SPJobCodeGroupName]
   ,ISNULL([SPCAPITALROLLUP].[Name], 'Not Specified') as [SPCapitalRollupName]
   ,ISNULL([SPDEBTISSUANCE].[Name], 'Not Specified') as [SPDebtIssuanceName]
   ,ISNULL([SPHACTROLLUP].[Name], 'Not Specified') as [SPHAccountRollupName]
   ,ISNULL([SPHACTROLLUP].[SPHCostComponent], 'Not Specified') as [SPHCostComponent]
   ,ISNULL([SPHACTROLLUP].[SPHCostComponentRollup], 'Not Specified') as [SPHCostComponentRollup]
   ,ISNULL([SPHACTROLLUP].[LineItem], 'Not Specified') as [SPHLineItem]
   ,ISNULL([SPHACTROLLUP].[Statement], 'Not Specified') as [SPHStatement]
   ,ISNULL([SPHACTROLLUP].[Category], 'Not Specified') as [SPHCategory]
   ,ISNULL([SPHACTROLLUP].[Section], 'Not Specified') as [SPHSection]
   ,ISNULL([DSSACCTROLL4].[Name], 'Not Specified') as [DSSAccountRollup4]
   ,ISNULL([DSSACCTROLL4].[Name], 'Not Specified') as [DSSAccountRollup4Name]
   ,ISNULL([DSSACCTROLL4].[Category], 'Not Specified') as [DSSAccountRollup4Category]
   ,ISNULL([DSSACCOUNTROLLUP5].[Name], 'Not Specified') as [DSSAccountRollup5Name]
   ,ISNULL([DSSACCOUNTROLLUP6].[Name], 'Not Specified') as [DSSAccountRollup6Name]
   ,ISNULL([DSSACCOUNTROLLUP7].[Name], 'Not Specified') as [DSSAccountRollup7Name]
, [grp5D92C559C8004C18BF821C58E1977A6C].[Version]FROM [fw].[DimAccount] grp5D92C559C8004C18BF821C58E1977A6C (readuncommitted)
   LEFT JOIN [fw].[viewDimPatientClass] [PATIENTCLASS]  on [PATIENTCLASS].[PatientClassID] = [grp5D92C559C8004C18BF821C58E1977A6C].[PatientClassID]
   LEFT JOIN [dss].[viewDimAccountRollup1] [DSSACTROL1]  on [DSSACTROL1].[DSSAccountRollup1ID] = [grp5D92C559C8004C18BF821C58E1977A6C].[DSSAccountRollup1ID]
   LEFT JOIN [dss].[viewDimAccountRollup2] [DSSACTROL2]  on [DSSACTROL2].[DSSAccountRollup2ID] = [grp5D92C559C8004C18BF821C58E1977A6C].[DSSAccountRollup2ID]
   LEFT JOIN [dss].[viewDimAccountRollup3] [DSSACTROL3]  on [DSSACTROL3].[DSSAccountRollup3ID] = [grp5D92C559C8004C18BF821C58E1977A6C].[DSSAccountRollup3ID]
   LEFT JOIN [ob].[viewDimFinancialReporting] [OBFINANCIALREP]  on [OBFINANCIALREP].[FinancialReportingID] = [grp5D92C559C8004C18BF821C58E1977A6C].[OBDollarsFinancialReportingID]
   LEFT JOIN [ob].[viewDimFinancialReporting] [OBFINANCIALREP_1]  on [OBFINANCIALREP_1].[FinancialReportingID] = [grp5D92C559C8004C18BF821C58E1977A6C].[OBUnitsFinancialReportingID]
   LEFT JOIN [ob].[viewDimAccountPH] [ACCOUNTPH]  on [ACCOUNTPH].[AccountPHID] = [grp5D92C559C8004C18BF821C58E1977A6C].[OBAccountPHID]
   INNER JOIN [ob].[viewDimAccountPH] [ACCOUNTPH_1]  on [ACCOUNTPH_1].[AccountPHID] = [grp5D92C559C8004C18BF821C58E1977A6C].[OBStatModelSectionID]
   LEFT JOIN [fw].[viewDimUnitType] [UNITTYPE]  on [UNITTYPE].[UnitTypeID] = [grp5D92C559C8004C18BF821C58E1977A6C].[OBStatUnitTypeID]
   LEFT JOIN [fw].[viewDimPayor] [PAYOR]  on [PAYOR].[PayorID] = [grp5D92C559C8004C18BF821C58E1977A6C].[OBPayorID]
   LEFT JOIN [fw].[viewDimPayorGroup] [PayorGroup]  on [PayorGroup].[PayorGroupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[OBPayorGroupID]
   LEFT JOIN [fw].[viewDimPayorGroup] [PayorGroup_1]  on [PayorGroup_1].[PayorGroupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[SPPayorGroupID]
   LEFT JOIN [fw].[viewDimPatientTypeRollup] [PatientTyRo]  on [PatientTyRo].[PatientTypeRollupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[PatientTypeRollupID]
   LEFT JOIN [sp].[viewDimAccountRollup] [SPAccountRollup]  on [SPAccountRollup].[AccountRollupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[SPAccountRollupID]
   LEFT JOIN [sp].[viewDimAccountRollup] [SPAccountRollup_1]  on [SPAccountRollup_1].[AccountRollupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[SPStatAccountRollup]
   LEFT JOIN [fw].[viewDimPhysicianGroup] [PhyGrp]  on [PhyGrp].[PhysicianGroupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[SPPhysicianGroupID]
   LEFT JOIN [fw].[viewDimJobCodeGroup] [JobCodeGrp]  on [JobCodeGrp].[JobCodeGroupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[SPJobCodeGroupID]
   LEFT JOIN [sp].[viewDimSPCapitalRollup] [SPCAPITALROLLUP]  on [SPCAPITALROLLUP].[SPCapitalRollupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[SPCapitalRollupID]
   LEFT JOIN [sp].[viewDimSPDebtIssuance] [SPDEBTISSUANCE]  on [SPDEBTISSUANCE].[SPDebtIssuanceID] = [grp5D92C559C8004C18BF821C58E1977A6C].[SPDebtIssuanceID]
   LEFT JOIN [fw].[viewDimSPHAccountRollup] [SPHACTROLLUP]  on [SPHACTROLLUP].[SPHAccountRollupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[SPHAccountRollupID]
   LEFT JOIN [dss].[viewDimAccountRollup4] [DSSACCTROLL4]  on [DSSACCTROLL4].[DSSAccountRollup4ID] = [grp5D92C559C8004C18BF821C58E1977A6C].[DSSAccountRollup4ID]
   INNER JOIN [dss].[viewDimAccountRollup5] [DSSACCOUNTROLLUP5]  on [DSSACCOUNTROLLUP5].[DSSAccountRollup5ID] = [grp5D92C559C8004C18BF821C58E1977A6C].[DSSAccountRollup5ID]
   LEFT JOIN [dss].[viewDimAccountRollup6] [DSSACCOUNTROLLUP6]  on [DSSACCOUNTROLLUP6].[DSSAccountRollup6ID] = [grp5D92C559C8004C18BF821C58E1977A6C].[DSSAccountRollup6ID]
   LEFT JOIN [dss].[viewDimAccountRollup7] [DSSACCOUNTROLLUP7]  on [DSSACCOUNTROLLUP7].[DSSAccountRollup7ID] = [grp5D92C559C8004C18BF821C58E1977A6C].[DSSAccountRollup7ID]
GO


---------------------------------------------

-- fw.viewDimAgeCohort
--Last Modified 10/17/2016 11:21 PM
CREATE VIEW [fw].[viewDimAgeCohort]
AS
SELECT
   grpD86C7982BF714099989A70284B99EB36.[AgeCohortID]
   ,grpD86C7982BF714099989A70284B99EB36.[Name]
   ,grpD86C7982BF714099989A70284B99EB36.[Code]
   ,grpD86C7982BF714099989A70284B99EB36.[SortOrder]
   ,grpD86C7982BF714099989A70284B99EB36.[TransactionID]
   ,grpD86C7982BF714099989A70284B99EB36.[MemberGUID]
   ,grpD86C7982BF714099989A70284B99EB36.[HistoryItemGUID]
   ,grpD86C7982BF714099989A70284B99EB36.[TimeMin]
   ,grpD86C7982BF714099989A70284B99EB36.[TimeMax]
   ,grpD86C7982BF714099989A70284B99EB36.[TimeMinUnit]
   ,grpD86C7982BF714099989A70284B99EB36.[TimeMaxUnit]
FROM [fw].[DimAgeCohort] grpD86C7982BF714099989A70284B99EB36 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimAssumption_auto
CREATE VIEW [fw].[viewDimAssumption_auto]
AS
SELECT
   grp2879736FA04A414EA76857E00A234FC5.[AssumptionID]
   ,grp2879736FA04A414EA76857E00A234FC5.[Name]
   ,grp2879736FA04A414EA76857E00A234FC5.[Category]
   ,grp2879736FA04A414EA76857E00A234FC5.[SubCategory]
   ,grp2879736FA04A414EA76857E00A234FC5.[DisplayFormat]
   ,grp2879736FA04A414EA76857E00A234FC5.[SPIsPastingValues]
   ,grp2879736FA04A414EA76857E00A234FC5.[SPIsProtectingRollingValues]
   ,grp2879736FA04A414EA76857E00A234FC5.[MemberGUID]
   ,grp2879736FA04A414EA76857E00A234FC5.[HistoryItemGUID]
, [grp2879736FA04A414EA76857E00A234FC5].[Version]FROM [fw].[DimAssumption] grp2879736FA04A414EA76857E00A234FC5 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimCICostLeader
CREATE VIEW [fw].[viewDimCICostLeader] 
AS
	SELECT 
		MemberGUID
		,UserName
		,NameFirst
		,NameLast
		,EmailAddress
		,PhoneNumber
		,IsSysAdmin
		,NameFull
		,UserGUID AS [CICostLeaderID]
	FROM [fw].[viewDimUsers]
	UNION
	SELECT 
		dbo.ZeroGUID() MemberGUID
		,'' UserName
		,'' NameFirst
		,''  NameLast
		,'' EmailAddress
		,'' PhoneNumber
		,'' IsSysAdmin
		,'Not Specified' NameFull
		,dbo.ZeroGUID() AS [CIOwnerID];
GO


---------------------------------------------

-- fw.viewDimCICostLeader_auto
--Last Modified 11/9/2018 5:03 PM
CREATE VIEW [fw].[viewDimCICostLeader_auto]
AS
SELECT
   grp86039BDA00234558918C494FF9385A1C.[MemberGUID]
  ,coalesce(grp86039BDA00234558918C494FF9385A1C.[UserName],'') as [UserName]
  ,coalesce(grp86039BDA00234558918C494FF9385A1C.[NameFirst],'') as [NameFirst]
  ,coalesce(grp86039BDA00234558918C494FF9385A1C.[NameLast],'') as [NameLast]
  ,coalesce(grp86039BDA00234558918C494FF9385A1C.[EmailAddress],'') as [EmailAddress]
  ,coalesce(grp86039BDA00234558918C494FF9385A1C.[PhoneNumber],'') as [PhoneNumber]
   ,grp86039BDA00234558918C494FF9385A1C.[IsSysAdmin]
  ,coalesce(grp86039BDA00234558918C494FF9385A1C.[NameFull],'') as [NameFull]
   ,grp86039BDA00234558918C494FF9385A1C.[CICostLeaderID]
FROM [fw].[viewDimCICostLeader] grp86039BDA00234558918C494FF9385A1C
GO


---------------------------------------------

-- fw.viewDimCIExecutiveSponsor
CREATE VIEW [fw].[viewDimCIExecutiveSponsor] 
AS
	SELECT 
		MemberGUID
		,UserName
		,NameFirst
		,NameLast
		,EmailAddress
		,PhoneNumber
		,IsSysAdmin
		,NameFull
		,UserGUID AS [CIExecutiveSponsorID]
	FROM [fw].[viewDimUsers]
	UNION
	SELECT 
		dbo.ZeroGUID() MemberGUID
		,'' UserName
		,'' NameFirst
		,''  NameLast
		,'' EmailAddress
		,'' PhoneNumber
		,'' IsSysAdmin
		,'Not Specified' NameFull
		,dbo.ZeroGUID() AS [CIOwnerID];
GO


---------------------------------------------

-- fw.viewDimCIExecutiveSponsor_auto
--Last Modified 11/9/2018 5:03 PM
CREATE VIEW [fw].[viewDimCIExecutiveSponsor_auto]
AS
SELECT
   grpF3B42BDB744145EC920F5404120C877D.[MemberGUID]
  ,coalesce(grpF3B42BDB744145EC920F5404120C877D.[UserName],'') as [UserName]
  ,coalesce(grpF3B42BDB744145EC920F5404120C877D.[NameFirst],'') as [NameFirst]
  ,coalesce(grpF3B42BDB744145EC920F5404120C877D.[NameLast],'') as [NameLast]
  ,coalesce(grpF3B42BDB744145EC920F5404120C877D.[EmailAddress],'') as [EmailAddress]
  ,coalesce(grpF3B42BDB744145EC920F5404120C877D.[PhoneNumber],'') as [PhoneNumber]
   ,grpF3B42BDB744145EC920F5404120C877D.[IsSysAdmin]
  ,coalesce(grpF3B42BDB744145EC920F5404120C877D.[NameFull],'') as [NameFull]
   ,grpF3B42BDB744145EC920F5404120C877D.[CIExecutiveSponsorID]
FROM [fw].[viewDimCIExecutiveSponsor] grpF3B42BDB744145EC920F5404120C877D
GO


---------------------------------------------

-- fw.viewDimCIOwner
CREATE VIEW [fw].[viewDimCIOwner] 
AS
	SELECT 
		MemberGUID
		,UserName
		,NameFirst
		,NameLast
		,EmailAddress
		,PhoneNumber
		,IsSysAdmin
		,NameFull
		,UserGUID AS [CIOwnerID]
	FROM [fw].[viewDimUsers]
	UNION
	SELECT 
		dbo.ZeroGUID() MemberGUID
		,'' UserName
		,'' NameFirst
		,''  NameLast
		,'' EmailAddress
		,'' PhoneNumber
		,'' IsSysAdmin
		,'Not Specified' NameFull
		,dbo.ZeroGUID() AS [CIOwnerID];
GO


---------------------------------------------

-- fw.viewDimCIOwner_auto
--Last Modified 11/9/2018 5:03 PM
CREATE VIEW [fw].[viewDimCIOwner_auto]
AS
SELECT
   grpD4F1A9BB138B4232A3D704B1F74D6CBE.[MemberGUID]
  ,coalesce(grpD4F1A9BB138B4232A3D704B1F74D6CBE.[UserName],'') as [UserName]
  ,coalesce(grpD4F1A9BB138B4232A3D704B1F74D6CBE.[NameFirst],'') as [NameFirst]
  ,coalesce(grpD4F1A9BB138B4232A3D704B1F74D6CBE.[NameLast],'') as [NameLast]
  ,coalesce(grpD4F1A9BB138B4232A3D704B1F74D6CBE.[EmailAddress],'') as [EmailAddress]
  ,coalesce(grpD4F1A9BB138B4232A3D704B1F74D6CBE.[PhoneNumber],'') as [PhoneNumber]
   ,grpD4F1A9BB138B4232A3D704B1F74D6CBE.[IsSysAdmin]
  ,coalesce(grpD4F1A9BB138B4232A3D704B1F74D6CBE.[NameFull],'') as [NameFull]
   ,grpD4F1A9BB138B4232A3D704B1F74D6CBE.[CIOwnerID]
FROM [fw].[viewDimCIOwner] grpD4F1A9BB138B4232A3D704B1F74D6CBE
GO


---------------------------------------------

-- fw.viewDimCMBucket
CREATE VIEW [fw].[viewDimCMBucket]
AS
SELECT
   grp14E4823F9B7A434C9E5390716DA1E83B.[MemberGUID]
   ,grp14E4823F9B7A434C9E5390716DA1E83B.[CategoryGUID]
  ,coalesce(grp14E4823F9B7A434C9E5390716DA1E83B.[Name],'') as [Name]
  ,coalesce(grp14E4823F9B7A434C9E5390716DA1E83B.[Category],'') as [Category]
FROM [dbo].[viewCMBucket] grp14E4823F9B7A434C9E5390716DA1E83B
GO


---------------------------------------------

-- fw.viewDimCareSetting
CREATE VIEW [fw].[viewDimCareSetting]
AS
SELECT
   grpCB4D1E3F1895456A8FAA1F3225FC314E.[CareSettingID]
   ,grpCB4D1E3F1895456A8FAA1F3225FC314E.[Name]
   ,grpCB4D1E3F1895456A8FAA1F3225FC314E.[Code]
   ,grpCB4D1E3F1895456A8FAA1F3225FC314E.[SortOrder]
   ,grpCB4D1E3F1895456A8FAA1F3225FC314E.[IsActive]
   ,grpCB4D1E3F1895456A8FAA1F3225FC314E.[TransactionID]
   ,grpCB4D1E3F1895456A8FAA1F3225FC314E.[MemberGUID]
   ,grpCB4D1E3F1895456A8FAA1F3225FC314E.[HistoryItemGUID]
FROM [fw].[DimCareSetting] grpCB4D1E3F1895456A8FAA1F3225FC314E (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimCareSettingPH
CREATE VIEW [fw].[viewDimCareSettingPH]
AS
SELECT
   grpF1AA6AEECFAB4BC783DD4937D6D780BC.[CareSettingPHID]
   ,grpF1AA6AEECFAB4BC783DD4937D6D780BC.[Name]
   ,grpF1AA6AEECFAB4BC783DD4937D6D780BC.[MemberGUID]
   ,grpF1AA6AEECFAB4BC783DD4937D6D780BC.[HistoryItemGUID]
   ,grpF1AA6AEECFAB4BC783DD4937D6D780BC.[TransactionID]
FROM [fw].[DimCareSettingPH] grpF1AA6AEECFAB4BC783DD4937D6D780BC (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimChargeCode
CREATE VIEW fw.viewDimChargeCode
AS
	SELECT
	 ChargeCodeID,
	 ChargeCode, 
	 MemberGUID, 
	 Name,
	 HistoryItemGUID,
	 IsDefined 
	FROM 
		fw.DimChargeCode
GO


---------------------------------------------

-- fw.viewDimChargeCodePH
CREATE VIEW [fw].[viewDimChargeCodePH]
AS
SELECT
   grp61106722392D44889DEE489AA9F62D29.[ChargeCodePHID]
   ,grp61106722392D44889DEE489AA9F62D29.[Name]
   ,grp61106722392D44889DEE489AA9F62D29.[MemberGUID]
   ,grp61106722392D44889DEE489AA9F62D29.[HistoryItemGUID]
FROM [fw].[DimChargeCodePH] grp61106722392D44889DEE489AA9F62D29 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimChargeCode_auto
--Last Modified 11/16/2020 3:28 PM
CREATE VIEW [fw].[viewDimChargeCode_auto]
AS
SELECT
   grp9F8A3E7BEB06485C914C72C4F66C593E.[ChargeCodeID]
  ,coalesce(grp9F8A3E7BEB06485C914C72C4F66C593E.[Name],'') as [Name]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[ChargeCode]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[Description]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[IsDefined]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[OBIsDefined]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[IsRVU]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[IsStatDriver]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[ChargeIncrease]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[Category]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[RVUWeight]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[StatType]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[PatientTypeID]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[DSSIsDefined]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[DayTypeID]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[DayType2ID]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[DayType3ID]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[UBRevenueCodeID]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[CPTID]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[IsActivityCost]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[MemberGUID]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[HistoryItemGUID]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[CostDriver]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[Rollup]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[IsPatientSpecific]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[FWIsDefined]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[TimeStampWeight]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[IsTimeStamp]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[TimeStampPrecedent]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[TransactionID]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[IsSPHSupplyCosting]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[IsSPHTDCosting]
   ,grp9F8A3E7BEB06485C914C72C4F66C593E.[SPHChargeCodePrefix]
   ,ISNULL([PATIENTTYPE].[Name], 'Not Specified') as [PatientTypeName]
   ,ISNULL([DimDayType].[Name], 'Not Specified') as [DayType]
   ,ISNULL([DAYTYPE2].[Name], 'Not Specified') as [DayType2]
   ,ISNULL([DAYTYPE3].[Name], 'Not Specified') as [DayType3]
   ,ISNULL([DimUBRevenue].[UBRevenueCode], 'Not Specified') as [UBRevenueCode]
   ,ISNULL([DimUBRevenue].[UBRevenueName], 'Not Specified') as [UBRevenueCodeName]
   ,ISNULL([DimCPT].[CPTCode], 'Not Specified') as [CPTCode]
   ,ISNULL([DimCPT].[CPTName], 'Not Specified') as [CPTName]
, [grp9F8A3E7BEB06485C914C72C4F66C593E].[Version]FROM [fw].[DimChargeCode] grp9F8A3E7BEB06485C914C72C4F66C593E (readuncommitted)
   LEFT JOIN [fw].[viewDimPatientType] [PATIENTTYPE]  on [PATIENTTYPE].[PatientTypeID] = [grp9F8A3E7BEB06485C914C72C4F66C593E].[PatientTypeID]
   LEFT JOIN [fw].[viewDimDayType_auto] [DimDayType]  on [DimDayType].[DayTypeID] = [grp9F8A3E7BEB06485C914C72C4F66C593E].[DayTypeID]
   LEFT JOIN [fw].[viewDimDayType2_auto] [DAYTYPE2]  on [DAYTYPE2].[DayType2ID] = [grp9F8A3E7BEB06485C914C72C4F66C593E].[DayType2ID]
   LEFT JOIN [fw].[viewDimDayType3_auto] [DAYTYPE3]  on [DAYTYPE3].[DayType3ID] = [grp9F8A3E7BEB06485C914C72C4F66C593E].[DayType3ID]
   LEFT JOIN [dss].[viewDimUBRevenueCode_auto] [DimUBRevenue]  on [DimUBRevenue].[UBRevenueCodeID] = [grp9F8A3E7BEB06485C914C72C4F66C593E].[UBRevenueCodeID]
   LEFT JOIN [dss].[viewDimCPT_auto] [DimCPT]  on [DimCPT].[CPTID] = [grp9F8A3E7BEB06485C914C72C4F66C593E].[CPTID]
GO


---------------------------------------------

-- fw.viewDimColumnHider_auto
CREATE VIEW [fw].[viewDimColumnHider_auto]
AS
SELECT
   grpDB3AC50ADCA7400E918D0BF9DAA2A474.[Name]
   ,grpDB3AC50ADCA7400E918D0BF9DAA2A474.[ColumnHiderID]
   ,grpDB3AC50ADCA7400E918D0BF9DAA2A474.[MemberGUID]
, [grpDB3AC50ADCA7400E918D0BF9DAA2A474].[Version], [grpDB3AC50ADCA7400E918D0BF9DAA2A474].[HistoryItemGUID]FROM [fw].[DimColumnHider] grpDB3AC50ADCA7400E918D0BF9DAA2A474 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimCompAnDepartment
--Last Modified 11/15/2023 3:55 PM
CREATE VIEW [fw].[viewDimCompAnDepartment]
AS
SELECT
   grp945F64DE366646BD8ACA55CDD45A8F1C.[CompAnDepartmentID]
   ,grp945F64DE366646BD8ACA55CDD45A8F1C.[CompAnDepartmentCode]
   ,grp945F64DE366646BD8ACA55CDD45A8F1C.[Description]
   ,grp945F64DE366646BD8ACA55CDD45A8F1C.[DescriptionLong]
   ,grp945F64DE366646BD8ACA55CDD45A8F1C.[CompAnDepartmentRollup1]
   ,grp945F64DE366646BD8ACA55CDD45A8F1C.[CompAnDepartmentRollup2]
   ,grp945F64DE366646BD8ACA55CDD45A8F1C.[CompAnDepartmentRollup3]
   ,grp945F64DE366646BD8ACA55CDD45A8F1C.[CompAnDepartmentRollup4]
   ,grp945F64DE366646BD8ACA55CDD45A8F1C.[CompAnPrimaryStat]
   ,grp945F64DE366646BD8ACA55CDD45A8F1C.[SPHDepartmentRollupID]
   ,grp945F64DE366646BD8ACA55CDD45A8F1C.[MemberGUID]
   ,grp945F64DE366646BD8ACA55CDD45A8F1C.[TransactionID]
   ,grp945F64DE366646BD8ACA55CDD45A8F1C.[HistoryItemGUID]
   ,ISNULL([SPHDEPARTMENTROLLUP].[Name], 'Not Specified') as [SPHDepartmentRollup]
FROM [fw].[DimCompAnDepartment] grp945F64DE366646BD8ACA55CDD45A8F1C (readuncommitted)
   INNER JOIN [fw].[viewDimSPHDepartmentRollup] [SPHDEPARTMENTROLLUP]  on [SPHDEPARTMENTROLLUP].[SPHDepartmentRollupID] = [grp945F64DE366646BD8ACA55CDD45A8F1C].[SPHDepartmentRollupID]
GO


---------------------------------------------

-- fw.viewDimCompAnPeerGroup_auto
--Last Modified 3/20/2024 5:05 PM
CREATE VIEW [fw].[viewDimCompAnPeerGroup_auto]
AS
SELECT
   grpE48D7237FE824CCE9822B88C3CAC7AB5.[CompAnPeerGroupID]
   ,grpE48D7237FE824CCE9822B88C3CAC7AB5.[Name]
   ,grpE48D7237FE824CCE9822B88C3CAC7AB5.[Description]
   ,grpE48D7237FE824CCE9822B88C3CAC7AB5.[CompAnPeerGroupCode]
   ,grpE48D7237FE824CCE9822B88C3CAC7AB5.[TransactionID]
   ,grpE48D7237FE824CCE9822B88C3CAC7AB5.[MemberGUID]
   ,grpE48D7237FE824CCE9822B88C3CAC7AB5.[HistoryItemGUID]
FROM [fw].[DimCompAnPeerGroup] grpE48D7237FE824CCE9822B88C3CAC7AB5 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimConsolidatedFinancialReporting
CREATE VIEW [fw].[viewDimConsolidatedFinancialReporting]
AS
SELECT

[ConsolidatedFinancialReportingID],
[Statement],
[Section],
[LineName],
 COALESCE([Name],'') as [Name],
[SortOrder],
[MemberGUID],
[HistoryItemGUID]
FROM [fw].[DimConsolidatedFinancialReporting] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimConsolidatedFinancialReporting_source
CREATE VIEW [fw].[viewDimConsolidatedFinancialReporting_source]
AS
SELECT
   grpB839D1E3EA3544B1802E3D15F28F859E.[ConsolidatedFinancialReportingID]
   ,grpB839D1E3EA3544B1802E3D15F28F859E.[MemberGUID]
   ,grpB839D1E3EA3544B1802E3D15F28F859E.[HistoryItemGUID]
   ,[grpB839D1E3EA3544B1802E3D15F28F859E].[Statement] + ' - ' + [grpB839D1E3EA3544B1802E3D15F28F859E].[Section] + ' - ' + [grpB839D1E3EA3544B1802E3D15F28F859E].[LineName] AS [Name]
FROM [fw].[DimConsolidatedFinancialReporting] grpB839D1E3EA3544B1802E3D15F28F859E (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDataType
CREATE VIEW [fw].[viewDimDataType]
AS
SELECT
   grp7931E63E49A84444B96A3473EF2E8342.[DataTypeID]
   ,grp7931E63E49A84444B96A3473EF2E8342.[Name]
   ,grp7931E63E49A84444B96A3473EF2E8342.[GlobalID]
   ,grp7931E63E49A84444B96A3473EF2E8342.[MemberGUID]
   ,grp7931E63E49A84444B96A3473EF2E8342.[HistoryItemGUID]
FROM [fw].[DimDataType] grp7931E63E49A84444B96A3473EF2E8342 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDate_auto
--Last Modified 4/5/2019 11:00 PM
CREATE VIEW [fw].[viewDimDate_auto]
AS
SELECT
   grpFE562A75A28047209619C1D86C699238.[DateID]
   ,grpFE562A75A28047209619C1D86C699238.[TransactionID]
   ,grpFE562A75A28047209619C1D86C699238.[DayNumberOfWeek]
   ,grpFE562A75A28047209619C1D86C699238.[DayNameOfWeek]
   ,grpFE562A75A28047209619C1D86C699238.[DayNumberOfMonth]
   ,grpFE562A75A28047209619C1D86C699238.[DayNumberOfYear]
   ,grpFE562A75A28047209619C1D86C699238.[WeekNumberOfYear]
   ,grpFE562A75A28047209619C1D86C699238.[IsWeekDay]
   ,grpFE562A75A28047209619C1D86C699238.[CalendarQuarter]
   ,grpFE562A75A28047209619C1D86C699238.[CalendarDateTime]
   ,grpFE562A75A28047209619C1D86C699238.[CalendarYear]
   ,grpFE562A75A28047209619C1D86C699238.[CalendarMonth]
   ,grpFE562A75A28047209619C1D86C699238.[CalendarMonthName]
   ,grpFE562A75A28047209619C1D86C699238.[FiscalYear]
  ,coalesce(grpFE562A75A28047209619C1D86C699238.[FiscalYearName],'') as [FiscalYearName]
   ,grpFE562A75A28047209619C1D86C699238.[HistoryItemGUID]
   ,grpFE562A75A28047209619C1D86C699238.[MemberGUID]
   ,grpFE562A75A28047209619C1D86C699238.[FiscalMonth]
   ,grpFE562A75A28047209619C1D86C699238.[FiscalQuarter]
   ,grpFE562A75A28047209619C1D86C699238.[YearMonth]
   ,grpFE562A75A28047209619C1D86C699238.[MonthYear]
   ,grpFE562A75A28047209619C1D86C699238.[DaysInMonth]
  ,coalesce(grpFE562A75A28047209619C1D86C699238.[PremierMapping],'') as [PremierMapping]
, [grpFE562A75A28047209619C1D86C699238].[Version]FROM [fw].[DimDate] grpFE562A75A28047209619C1D86C699238 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDayType2
CREATE VIEW fw.viewDimDayType2

AS

SELECT
	DayTypeID [DayType2ID]
	,DayTypeCode
	,Description
	,Name
	,PrecedentOrder
	,GlobalID
	,Rollup
	,MemberGUID
	,HistoryItemGUID
FROM
	fw.DimDayType
GO


---------------------------------------------

-- fw.viewDimDayType2_auto
CREATE VIEW [fw].[viewDimDayType2_auto]
AS
SELECT
   grp143B285CCD194B4EBEF270972EB02575.[DayType2ID]
   ,grp143B285CCD194B4EBEF270972EB02575.[DayTypeCode]
   ,grp143B285CCD194B4EBEF270972EB02575.[Description]
   ,grp143B285CCD194B4EBEF270972EB02575.[Name]
   ,grp143B285CCD194B4EBEF270972EB02575.[PrecedentOrder]
   ,grp143B285CCD194B4EBEF270972EB02575.[GlobalID]
   ,grp143B285CCD194B4EBEF270972EB02575.[Rollup]
   ,grp143B285CCD194B4EBEF270972EB02575.[MemberGUID]
   ,grp143B285CCD194B4EBEF270972EB02575.[HistoryItemGUID]
FROM [fw].[viewDimDayType2] grp143B285CCD194B4EBEF270972EB02575
GO


---------------------------------------------

-- fw.viewDimDayType3
CREATE VIEW fw.viewDimDayType3

AS

SELECT
	DayTypeID [DayType3ID]
	,DayTypeCode
	,Description
	,Name
	,PrecedentOrder
	,GlobalID
	,Rollup
	,MemberGUID
	,HistoryItemGUID
FROM
	fw.DimDayType
GO


---------------------------------------------

-- fw.viewDimDayType3_auto
CREATE VIEW [fw].[viewDimDayType3_auto]
AS
SELECT
   grp5B075EFFA79145A69E8B48E63306F374.[DayType3ID]
   ,grp5B075EFFA79145A69E8B48E63306F374.[DayTypeCode]
   ,grp5B075EFFA79145A69E8B48E63306F374.[Description]
   ,grp5B075EFFA79145A69E8B48E63306F374.[Name]
   ,grp5B075EFFA79145A69E8B48E63306F374.[PrecedentOrder]
   ,grp5B075EFFA79145A69E8B48E63306F374.[GlobalID]
   ,grp5B075EFFA79145A69E8B48E63306F374.[Rollup]
   ,grp5B075EFFA79145A69E8B48E63306F374.[MemberGUID]
   ,grp5B075EFFA79145A69E8B48E63306F374.[HistoryItemGUID]
FROM [fw].[viewDimDayType3] grp5B075EFFA79145A69E8B48E63306F374
GO


---------------------------------------------

-- fw.viewDimDayType_auto
--Last Modified 3/8/2016 3:28 PM
CREATE VIEW [fw].[viewDimDayType_auto]
AS
SELECT
   grpCCD1FA368B434C7B949582F5A942303E.[DayTypeID]
   ,grpCCD1FA368B434C7B949582F5A942303E.[DayTypeCode]
   ,grpCCD1FA368B434C7B949582F5A942303E.[Description]
  ,coalesce(grpCCD1FA368B434C7B949582F5A942303E.[Name],'') as [Name]
   ,grpCCD1FA368B434C7B949582F5A942303E.[PrecedentOrder]
   ,grpCCD1FA368B434C7B949582F5A942303E.[GlobalID]
   ,grpCCD1FA368B434C7B949582F5A942303E.[MemberGUID]
   ,grpCCD1FA368B434C7B949582F5A942303E.[HistoryItemGUID]
   ,grpCCD1FA368B434C7B949582F5A942303E.[Rollup]
FROM [fw].[DimDayType] grpCCD1FA368B434C7B949582F5A942303E (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDayType_auto_0
CREATE VIEW [fw].[viewDimDayType_auto_0]
AS
SELECT
   grp78A73D3E10C0427BB8F87BD131D0742E.[DayTypeID]
   ,grp78A73D3E10C0427BB8F87BD131D0742E.[DayTypeCode]
   ,grp78A73D3E10C0427BB8F87BD131D0742E.[Description]
  ,coalesce(grp78A73D3E10C0427BB8F87BD131D0742E.[Name],'') as [Name]
   ,grp78A73D3E10C0427BB8F87BD131D0742E.[PrecedentOrder]
   ,grp78A73D3E10C0427BB8F87BD131D0742E.[GlobalID]
   ,grp78A73D3E10C0427BB8F87BD131D0742E.[MemberGUID]
   ,grp78A73D3E10C0427BB8F87BD131D0742E.[HistoryItemGUID]
   ,grp78A73D3E10C0427BB8F87BD131D0742E.[Rollup]
FROM [fw].[DimDayType] grp78A73D3E10C0427BB8F87BD131D0742E
GO


---------------------------------------------

-- fw.viewDimDayofStay
CREATE VIEW [fw].[viewDimDayofStay]
AS
SELECT
   grp13B341BB37FF431BA7F941247BF19B9E.[DayofStayID]
   ,grp13B341BB37FF431BA7F941247BF19B9E.[Name]
   ,grp13B341BB37FF431BA7F941247BF19B9E.[MemberGUID]
   ,grp13B341BB37FF431BA7F941247BF19B9E.[HistoryItemGUID]
FROM [fw].[DimDayofStay] grp13B341BB37FF431BA7F941247BF19B9E (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDepartment
CREATE VIEW [fw].[viewDimDepartment]
AS
SELECT

[DepartmentID],
 COALESCE([Name],'') as [Name],
[DepartmentCode],
[Description],
[SystemID],
[EntityID],
[DepartmentRollup1ID],
[DepartmentRollup2ID],
[DepartmentRollup3ID],
[DepartmentRollup4ID],
[DepartmentRollup5ID],
[DepartmentRollup6ID],
[CareSettingID],
[SortOrder],
[FunctionalAreaID],
[ResearchDepartmentCategoryID],
[AttributionTypeID],
[CAPIsDefined],
[IsCAP],
[DSSIsDefined],
[IsDSS],
[DepartmentTypeOLD],
[DSSDeptGrouping],
[DSSDepartmentRollup1ID],
[DSSDepartmentRollup2ID],
[DSSDepartmentRollup3ID],
[DSSDepartmentRollup4ID],
[DSSDepartmentRollup5ID],
[DSSDepartmentRollup6ID],
[DSSDepartmentRollup7ID],
[IsOverhead],
[OBIsDefined],
[IsOB],
[IsMRPlan],
[IsMRMetricTracking],
[IsPR],
[IsActive],
[IsVariable],
[IsAccountFlexing],
[FlexingBucketGUID],
[OBGlobalStatisticsPlanID],
[OBReimbursementPlanID],
[OBServiceLinePlanID],
[SPIsDefined],
[IsLRFP],
[RollingPlanID],
[OpsPlanID],
[BalPlanID],
[PatientTypeRollup],
[SPJobCodeGroup],
[SPPhysicianGroup],
[SPAccountRollup],
 COALESCE([System],'') as [System],
[SystemSortOrder],
 COALESCE([Entity],'') as [Entity],
[EntitySortOrder],
[EntityTypeOverride],
 COALESCE([EntityCode],'') as [EntityCode],
 COALESCE([CareSetting],'') as [CareSetting],
 COALESCE([DepartmentRollup1],'') as [DepartmentRollup1],
[DepartmentRollup1SortOrder],
 COALESCE([DepartmentRollup2],'') as [DepartmentRollup2],
[DepartmentRollup2SortOrder],
 COALESCE([DepartmentRollup3],'') as [DepartmentRollup3],
[DepartmentRollup3SortOrder],
 COALESCE([DepartmentRollup4],'') as [DepartmentRollup4],
[DepartmentRollup4SortOrder],
[SPHDepartmentRollupID],
 COALESCE([SPHDepartmentRollupName],'') as [SPHDepartmentRollupName],
[SPHDepartmentRollupConfidenceScore],
 COALESCE([DepartmentRollup5],'') as [DepartmentRollup5],
[SPHDepartmentConfidenceScore],
[DepartmentRollup5SortOrder],
 COALESCE([DepartmentRollup6],'') as [DepartmentRollup6],
[DepartmentRollup6SortOrder],
 COALESCE([DSSDepartmentRollup1Name],'') as [DSSDepartmentRollup1Name],
 COALESCE([DSSDepartmentRollup2Name],'') as [DSSDepartmentRollup2Name],
 COALESCE([DSSDepartmentRollup3Name],'') as [DSSDepartmentRollup3Name],
 COALESCE([DSSDepartmentRollup4Name],'') as [DSSDepartmentRollup4Name],
 COALESCE([DSSDepartmentRollup5Name],'') as [DSSDepartmentRollup5Name],
 COALESCE([DSSDepartmentRollup6Name],'') as [DSSDepartmentRollup6Name],
 COALESCE([DSSDepartmentRollup7Name],'') as [DSSDepartmentRollup7Name],
 COALESCE([FunctionalArea],'') as [FunctionalArea],
 COALESCE([ResearchDepartmentCategoryName],'') as [ResearchDepartmentCategoryName],
[ResearchDepartmentCategorySortOrder],
 COALESCE([AttributionType],'') as [AttributionType],
[IsConsolidated],
[ConsolidatedCode],
 COALESCE([OBGlobalStatisticsPlan],'') as [OBGlobalStatisticsPlan],
 COALESCE([OBReimbursementPlan],'') as [OBReimbursementPlan],
 COALESCE([OBServiceLinePlan],'') as [OBServiceLinePlan],
 COALESCE([SPRollingForecastPlanName],'') as [SPRollingForecastPlanName],
 COALESCE([SPOperationsPlanName],'') as [SPOperationsPlanName],
 COALESCE([SPBalanceSheetPlanName],'') as [SPBalanceSheetPlanName],
[IsDepartmentRollup],
[SPServiceLineForecastType],
 COALESCE([PatientTypeRollupName],'') as [PatientTypeRollupName],
[DepartmentTypeID],
 COALESCE([DepartmentType],'') as [DepartmentType],
 COALESCE([SPJobCodeGroupName],'') as [SPJobCodeGroupName],
 COALESCE([SPPhysicianGroupName],'') as [SPPhysicianGroupName],
 COALESCE([SPAccountRollupName],'') as [SPAccountRollupName],
[SecureGroupID],
[MemberGUID],
[HistoryItemGUID],
[WorkWeekID],
[CAPDefaultSalesTax],
[FundID],
 COALESCE([Fund],'') as [Fund],
[FundSortOrder],
[ProjectID],
 COALESCE([Project],'') as [Project],
[ProjectSortOrder],
[HomeDepartmentID],
 COALESCE([HomeDepartment],'') as [HomeDepartment],
[HomeDepartmentSortOrder],
[ProgramID],
 COALESCE([Program],'') as [Program],
[ProgramSortOrder],
[PayCycleID],
[FWIsDefined],
[DepartmentCodeRaw],
[MRVicePresident],
[MRDirector],
[MRManager],
[IsMROrPR],
[IsHealthPlanAdmin],
 COALESCE([DepartmentRollup1Code],'') as [DepartmentRollup1Code],
 COALESCE([DepartmentRollup2Code],'') as [DepartmentRollup2Code],
 COALESCE([DepartmentRollup3Code],'') as [DepartmentRollup3Code],
 COALESCE([DepartmentRollup4Code],'') as [DepartmentRollup4Code],
 COALESCE([DepartmentRollup5Code],'') as [DepartmentRollup5Code],
 COALESCE([DepartmentRollup6Code],'') as [DepartmentRollup6Code],
[TransactionID],
[SPHDepartmentTypeID],
[SPHDepartmentRollupIsValidated],
[SPHDepartmentIsValidated],
[SPHDepartmentID],
 COALESCE([SPHDepartmentName],'') as [SPHDepartmentName],
[SPHDepartmentType],
[IsClaimsCosting],
[ProductivityPercentileID],
 COALESCE([ProductivityPercentile],'') as [ProductivityPercentile],
[CompAnDepartmentID],
 COALESCE([CompAnDepartment],'') as [CompAnDepartment]    ,[Version]

FROM [fw].[DimDepartment] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDepartmentPH_auto
CREATE VIEW [fw].[viewDimDepartmentPH_auto]
AS
SELECT
   grpDC20824AF9C5477F9045CAAEF2A933B7.[Name]
   ,grpDC20824AF9C5477F9045CAAEF2A933B7.[MemberGUID]
   ,grpDC20824AF9C5477F9045CAAEF2A933B7.[DepartmentPHID]
, [grpDC20824AF9C5477F9045CAAEF2A933B7].[Version], [grpDC20824AF9C5477F9045CAAEF2A933B7].[HistoryItemGUID]FROM [fw].[DimDepartmentPH] grpDC20824AF9C5477F9045CAAEF2A933B7 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDepartmentRollup1
CREATE VIEW [fw].[viewDimDepartmentRollup1]
AS
SELECT

[DepartmentRollup1ID],
 COALESCE([Name],'') as [Name],
[Code],
[Description],
[SortOrder],
[SecureGroupID],
[MemberGUID],
[HistoryItemGUID],
[EliminationsDepartmentID]
FROM [fw].[DimDepartmentRollup1] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDepartmentRollup1_source
CREATE VIEW [fw].[viewDimDepartmentRollup1_source]
AS
SELECT
   grpFA10FD701D9D4868B178EDDF1FC3BABD.[DepartmentRollup1ID]
   ,grpFA10FD701D9D4868B178EDDF1FC3BABD.[Name]
   ,grpFA10FD701D9D4868B178EDDF1FC3BABD.[SecureGroupID]
   ,grpFA10FD701D9D4868B178EDDF1FC3BABD.[MemberGUID]
   ,grpFA10FD701D9D4868B178EDDF1FC3BABD.[HistoryItemGUID]
FROM [fw].[DimDepartmentRollup1] grpFA10FD701D9D4868B178EDDF1FC3BABD (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDepartmentRollup2
CREATE VIEW [fw].[viewDimDepartmentRollup2]
AS
SELECT

[DepartmentRollup2ID],
 COALESCE([Name],'') as [Name],
[Code],
[Description],
[SortOrder],
[SecureGroupID],
[MemberGUID],
[HistoryItemGUID],
[EliminationsDepartmentID]
FROM [fw].[DimDepartmentRollup2] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDepartmentRollup2_source
CREATE VIEW [fw].[viewDimDepartmentRollup2_source]
AS
SELECT
   grpB2EDCD6A7E5448C8912DE6279CA5303C.[DepartmentRollup2ID]
   ,grpB2EDCD6A7E5448C8912DE6279CA5303C.[Name]
   ,grpB2EDCD6A7E5448C8912DE6279CA5303C.[SecureGroupID]
   ,grpB2EDCD6A7E5448C8912DE6279CA5303C.[MemberGUID]
   ,grpB2EDCD6A7E5448C8912DE6279CA5303C.[HistoryItemGUID]
FROM [fw].[DimDepartmentRollup2] grpB2EDCD6A7E5448C8912DE6279CA5303C (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDepartmentRollup3
CREATE VIEW [fw].[viewDimDepartmentRollup3]
AS
SELECT

[DepartmentRollup3ID],
 COALESCE([Name],'') as [Name],
[Code],
[Description],
[SortOrder],
[SecureGroupID],
[MemberGUID],
[HistoryItemGUID],
[EliminationsDepartmentID]
FROM [fw].[DimDepartmentRollup3] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDepartmentRollup3_source
CREATE VIEW [fw].[viewDimDepartmentRollup3_source]
AS
SELECT
   grp0D6EBF23F8D6489DA85B11B8FF0DF237.[DepartmentRollup3ID]
   ,grp0D6EBF23F8D6489DA85B11B8FF0DF237.[Name]
   ,grp0D6EBF23F8D6489DA85B11B8FF0DF237.[SecureGroupID]
   ,grp0D6EBF23F8D6489DA85B11B8FF0DF237.[MemberGUID]
   ,grp0D6EBF23F8D6489DA85B11B8FF0DF237.[HistoryItemGUID]
FROM [fw].[DimDepartmentRollup3] grp0D6EBF23F8D6489DA85B11B8FF0DF237 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDepartmentRollup4
CREATE VIEW [fw].[viewDimDepartmentRollup4]
AS
SELECT

[DepartmentRollup4ID],
 COALESCE([Name],'') as [Name],
[Code],
[Description],
[SortOrder],
[SecureGroupID],
[MemberGUID],
[HistoryItemGUID],
[EliminationsDepartmentID]
FROM [fw].[DimDepartmentRollup4] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDepartmentRollup4_source
CREATE VIEW [fw].[viewDimDepartmentRollup4_source]
AS
SELECT
   grp2823DE836C9241B29F219400CAE92824.[SecureGroupID]
   ,grp2823DE836C9241B29F219400CAE92824.[DepartmentRollup4ID]
   ,grp2823DE836C9241B29F219400CAE92824.[Name]
   ,grp2823DE836C9241B29F219400CAE92824.[MemberGUID]
   ,grp2823DE836C9241B29F219400CAE92824.[HistoryItemGUID]
FROM [fw].[DimDepartmentRollup4] grp2823DE836C9241B29F219400CAE92824 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDepartmentRollup5
CREATE VIEW [fw].[viewDimDepartmentRollup5]
AS
SELECT

[DepartmentRollup5ID],
 COALESCE([Name],'') as [Name],
[Code],
[Description],
[SortOrder],
[SecureGroupID],
[MemberGUID],
[HistoryItemGUID],
[EliminationsDepartmentID]
FROM [fw].[DimDepartmentRollup5] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDepartmentRollup5_source
CREATE VIEW [fw].[viewDimDepartmentRollup5_source]
AS
SELECT
   grpFEF2ED58077B4941805CE8B84D4E763A.[SecureGroupID]
   ,grpFEF2ED58077B4941805CE8B84D4E763A.[DepartmentRollup5ID]
   ,grpFEF2ED58077B4941805CE8B84D4E763A.[Name]
   ,grpFEF2ED58077B4941805CE8B84D4E763A.[MemberGUID]
   ,grpFEF2ED58077B4941805CE8B84D4E763A.[HistoryItemGUID]
FROM [fw].[DimDepartmentRollup5] grpFEF2ED58077B4941805CE8B84D4E763A (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDepartmentRollup6
CREATE VIEW [fw].[viewDimDepartmentRollup6]
AS
SELECT

[DepartmentRollup6ID],
 COALESCE([Name],'') as [Name],
[Code],
[Description],
[SortOrder],
[SecureGroupID],
[MemberGUID],
[HistoryItemGUID],
[EliminationsDepartmentID]
FROM [fw].[DimDepartmentRollup6] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDepartmentRollup6_source
CREATE VIEW [fw].[viewDimDepartmentRollup6_source]
AS
SELECT
   grp43C5EF4D49654C9B9526374DD9E2FC93.[DepartmentRollup6ID]
   ,grp43C5EF4D49654C9B9526374DD9E2FC93.[SecureGroupID]
   ,grp43C5EF4D49654C9B9526374DD9E2FC93.[Name]
   ,grp43C5EF4D49654C9B9526374DD9E2FC93.[MemberGUID]
   ,grp43C5EF4D49654C9B9526374DD9E2FC93.[HistoryItemGUID]
FROM [fw].[DimDepartmentRollup6] grp43C5EF4D49654C9B9526374DD9E2FC93 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDepartmentType
--Last Modified 1/20/2016 8:39 AM
CREATE VIEW [fw].[viewDimDepartmentType]
AS
SELECT
   grpFC24FBAFBE8449659F87692015E8BC45.[DepartmentTypeID]
   ,grpFC24FBAFBE8449659F87692015E8BC45.[Name]
   ,grpFC24FBAFBE8449659F87692015E8BC45.[TransactionID]
   ,grpFC24FBAFBE8449659F87692015E8BC45.[MemberGUID]
   ,grpFC24FBAFBE8449659F87692015E8BC45.[HistoryItemGUID]
   ,grpFC24FBAFBE8449659F87692015E8BC45.[Rollup]
FROM [fw].[DimDepartmentType] grpFC24FBAFBE8449659F87692015E8BC45 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimDepartment_Pseudo
CREATE view fw.viewDimDepartment_Pseudo AS
SELECT        DepartmentID, Name, DepartmentCode, Description, SystemID, EntityID, DepartmentRollup1ID, DepartmentRollup2ID, DepartmentRollup3ID, DepartmentRollup4ID, 
                         DepartmentRollup5ID, DepartmentRollup6ID, CareSettingID, SortOrder, FunctionalAreaID, ResearchDepartmentCategoryID, AttributionTypeID, CAPIsDefined, IsCAP, 
                         DSSIsDefined, IsDSS, DepartmentTypeOLD, DSSDeptGrouping, DSSDepartmentRollup1ID, DSSDepartmentRollup2ID, DSSDepartmentRollup3ID, IsOverhead, 
                         OBIsDefined, IsOB, IsMRPlan, IsActive, IsVariable, IsAccountFlexing, FlexingBucketGUID, OBGlobalStatisticsPlanID, OBReimbursementPlanID, 
                         OBServiceLinePlanID, SPIsDefined, IsLRFP, RollingPlanID, OpsPlanID, BalPlanID, PatientTypeRollup, SPJobCodeGroup, SPPhysicianGroup, SPAccountRollup, 
                         System, SystemSortOrder, Entity, EntitySortOrder, EntityTypeOverride, EntityCode, CareSetting, DepartmentRollup1, DepartmentRollup1SortOrder, 
                         DepartmentRollup2, DepartmentRollup2SortOrder, DepartmentRollup3, DepartmentRollup3SortOrder, DepartmentRollup4, DepartmentRollup4SortOrder, 
                         DepartmentRollup5, DepartmentRollup5SortOrder, DepartmentRollup6, DepartmentRollup6SortOrder, DSSDepartmentRollup1Name, DSSDepartmentRollup2Name, 
                         DSSDepartmentRollup3Name, FunctionalArea, ResearchDepartmentCategoryName, ResearchDepartmentCategorySortOrder, AttributionType, IsConsolidated, 
                         ConsolidatedCode, OBGlobalStatisticsPlan, OBReimbursementPlan, OBServiceLinePlan, SPRollingForecastPlanName, SPOperationsPlanName, 
                         SPBalanceSheetPlanName, IsDepartmentRollup, SPServiceLineForecastType, PatientTypeRollupName, DepartmentTypeID, DepartmentType, 
                         SPJobCodeGroupName, SPPhysicianGroupName, SPAccountRollupName, SecureGroupID, MemberGUID, HistoryItemGUID, WorkWeekID, CAPDefaultSalesTax, 
                         FundID, Fund, FundSortOrder, ProjectID, Project, ProjectSortOrder, HomeDepartmentID, HomeDepartment, HomeDepartmentSortOrder, ProgramID, Program, 
                         ProgramSortOrder, PayCycleID, FWIsDefined, DepartmentCodeRaw, IsPR, SPHDepartmentTypeID, SPHDepartmentType, Version
FROM            fw.viewDimDepartment AS d
WHERE        (IsDepartmentRollup = 1) OR
                         (DepartmentID = 0)
GO


---------------------------------------------

-- fw.viewDimDepartment_Real
CREATE view [fw].[viewDimDepartment_Real] 
AS
SELECT        
	DepartmentID, Name, DepartmentCode, Description, SystemID, EntityID, DepartmentRollup1ID, DepartmentRollup2ID, DepartmentRollup3ID, DepartmentRollup4ID, 
    DepartmentRollup5ID, DepartmentRollup6ID, CareSettingID, SortOrder, FunctionalAreaID, ResearchDepartmentCategoryID, AttributionTypeID, CAPIsDefined, IsCAP, 
    DSSIsDefined, IsDSS, DSSDeptGrouping, DSSDepartmentRollup1ID, DSSDepartmentRollup2ID, DSSDepartmentRollup3ID,DSSDepartmentRollup4ID, DSSDepartmentRollup5ID, DSSDepartmentRollup6ID, DSSDepartmentRollup7ID, IsOverhead, 
    OBIsDefined, IsOB, IsMRPlan, IsMRMetricTracking, IsActive, IsVariable, IsAccountFlexing, FlexingBucketGUID, OBGlobalStatisticsPlanID, OBReimbursementPlanID, 
    OBServiceLinePlanID, SPIsDefined, IsLRFP, RollingPlanID, OpsPlanID, BalPlanID, PatientTypeRollup, SPJobCodeGroup, SPPhysicianGroup, SPAccountRollup, 
    System, SystemSortOrder, Entity, EntitySortOrder, EntityTypeOverride, EntityCode, CareSetting, DepartmentRollup1, DepartmentRollup1SortOrder, 
    DepartmentRollup2, DepartmentRollup2SortOrder, DepartmentRollup3, DepartmentRollup3SortOrder, DepartmentRollup4, DepartmentRollup4SortOrder, 
    DepartmentRollup5, DepartmentRollup5SortOrder, DepartmentRollup6, DepartmentRollup6SortOrder, DSSDepartmentRollup1Name, DSSDepartmentRollup2Name, 
    DSSDepartmentRollup3Name,DSSDepartmentRollup4Name,DSSDepartmentRollup5Name,DSSDepartmentRollup6Name,DSSDepartmentRollup7Name, FunctionalArea, ResearchDepartmentCategoryName, ResearchDepartmentCategorySortOrder, AttributionType, IsConsolidated, 
    ConsolidatedCode, OBGlobalStatisticsPlan, OBReimbursementPlan, OBServiceLinePlan, SPRollingForecastPlanName, SPOperationsPlanName, 
    SPBalanceSheetPlanName, IsDepartmentRollup, SPServiceLineForecastType, PatientTypeRollupName, DepartmentTypeID, DepartmentType, 
    SPJobCodeGroupName, SPPhysicianGroupName, SPAccountRollupName, SecureGroupID, MemberGUID, HistoryItemGUID, WorkWeekID, CAPDefaultSalesTax, 
    FundID, Fund, FundSortOrder, ProjectID, Project, ProjectSortOrder, HomeDepartmentID, HomeDepartment, HomeDepartmentSortOrder, ProgramID, Program, 
    ProgramSortOrder, PayCycleID, FWIsDefined, DepartmentCodeRaw, IsPR, SPHDepartmentTypeID, SPHDepartmentType, Version, SPHDepartmentID, SPHDepartmentName, SPHDepartmentConfidenceScore, SPHDepartmentIsValidated, SPHDepartmentRollupID, SPHDepartmentRollupName, SPHDepartmentRollupConfidenceScore
FROM            
	fw.viewDimDepartment d
WHERE        
	(IsDepartmentRollup = 0 OR DepartmentID = 0)
GO


---------------------------------------------

-- fw.viewDimDepartment_source
CREATE VIEW [fw].[viewDimDepartment_source]
AS
SELECT
   grp34146F449F3140ECB03A8BC6153DE46F.[DepartmentID]
   ,grp34146F449F3140ECB03A8BC6153DE46F.[Name]
   ,grp34146F449F3140ECB03A8BC6153DE46F.[EntityTypeOverride]
   ,grp34146F449F3140ECB03A8BC6153DE46F.[SPHDepartmentRollupID]
   ,grp34146F449F3140ECB03A8BC6153DE46F.[SPHDepartmentConfidenceScore]
   ,grp34146F449F3140ECB03A8BC6153DE46F.[SecureGroupID]
   ,grp34146F449F3140ECB03A8BC6153DE46F.[MemberGUID]
   ,grp34146F449F3140ECB03A8BC6153DE46F.[HistoryItemGUID]
   ,grp34146F449F3140ECB03A8BC6153DE46F.[IsMROrPR]
   ,grp34146F449F3140ECB03A8BC6153DE46F.[TransactionID]
   ,ISNULL([SYSTEM].[Name], 'Not Specified') as [System]
   ,ISNULL([SYSTEM].[SortOrder], 0) as [SystemSortOrder]
   ,ISNULL([ENT].[Name], 'Not Specified') as [Entity]
   ,ISNULL([ENT].[SortOrder], 0) as [EntitySortOrder]
   ,ISNULL([ENT].[Code], 'Not Specified') as [EntityCode]
   ,ISNULL([ENT].[SPServiceLineForecastType], 0) as [SPServiceLineForecastType]
   ,ISNULL([ENT].[WorkWeekID], 0) as [WorkWeekID]
   ,ISNULL([ENT].[CAPDefaultSalesTax], 0) as [CAPDefaultSalesTax]
   ,ISNULL([ENT].[PayCycleID], 0) as [PayCycleID]
   ,ISNULL([DeptRollup1].[Name], 'Not Specified') as [DepartmentRollup1]
   ,ISNULL([DeptRollup1].[SortOrder], 0) as [DepartmentRollup1SortOrder]
   ,ISNULL([DeptRollup1].[Code], 'Not Specified') as [DepartmentRollup1Code]
   ,ISNULL([DeptRollup2].[Name], 'Not Specified') as [DepartmentRollup2]
   ,ISNULL([DeptRollup2].[SortOrder], 0) as [DepartmentRollup2SortOrder]
   ,ISNULL([DeptRollup2].[Code], 'Not Specified') as [DepartmentRollup2Code]
   ,ISNULL([DeptRollup3].[Name], 'Not Specified') as [DepartmentRollup3]
   ,ISNULL([DeptRollup3].[SortOrder], 0) as [DepartmentRollup3SortOrder]
   ,ISNULL([DeptRollup3].[Code], 'Not Specified') as [DepartmentRollup3Code]
   ,ISNULL([DeptRollup4].[Name], 'Not Specified') as [DepartmentRollup4]
   ,ISNULL([DeptRollup4].[SortOrder], 0) as [DepartmentRollup4SortOrder]
   ,ISNULL([DeptRollup4].[Code], 'Not Specified') as [DepartmentRollup4Code]
   ,ISNULL([DeptRollup5].[Name], 'Not Specified') as [DepartmentRollup5]
   ,ISNULL([DeptRollup5].[SortOrder], 0) as [DepartmentRollup5SortOrder]
   ,ISNULL([DeptRollup5].[Code], 'Not Specified') as [DepartmentRollup5Code]
   ,ISNULL([DeptRollup6].[Name], 'Not Specified') as [DepartmentRollup6]
   ,ISNULL([DeptRollup6].[SortOrder], 0) as [DepartmentRollup6SortOrder]
   ,ISNULL([DeptRollup6].[Code], 'Not Specified') as [DepartmentRollup6Code]
   ,ISNULL([CARESETTING].[Name], 'Not Specified') as [CareSetting]
   ,ISNULL([FUNCTIONALAREA].[Name], 'Not Specified') as [FunctionalArea]
   ,ISNULL([RESEARCHDEPARTMENTCATEGORY].[Name], 'Not Specified') as [ResearchDepartmentCategoryName]
   ,ISNULL([RESEARCHDEPARTMENTCATEGORY].[SortOrder], 0) as [ResearchDepartmentCategorySortOrder]
   ,ISNULL([ATTRIBUTIONTYPE].[Name], 'Not Specified') as [AttributionType]
   ,ISNULL([DSSDEPTROLLUP1].[Name], 'Not Specified') as [DSSDepartmentRollup1Name]
   ,ISNULL([DSSDEPTROLLUP2].[Name], 'Not Specified') as [DSSDepartmentRollup2Name]
   ,ISNULL([DSSDEPTROLLUP3].[Name], 'Not Specified') as [DSSDepartmentRollup3Name]
   ,ISNULL([DSDEPTR4].[Name], 'Not Specified') as [DSSDepartmentRollup4Name]
   ,ISNULL([DSSDEPT5].[Name], 'Not Specified') as [DSSDepartmentRollup5Name]
   ,ISNULL([DSSDEPTROLL6].[Name], 'Not Specified') as [DSSDepartmentRollup6Name]
   ,ISNULL([DSSDEPARTMENTROLLUP7].[Name], 'Not Specified') as [DSSDepartmentRollup7Name]
   ,ISNULL([OBGLOBALSTATISTICSPLAN].[Name], 'Not Specified') as [OBGlobalStatisticsPlan]
   ,ISNULL([OBREIMBURSEMENTPLAN].[Name], 'Not Specified') as [OBReimbursementPlan]
   ,ISNULL([OBSERVICELINEPLAN].[Name], 'Not Specified') as [OBServiceLinePlan]
   ,ISNULL([SPRFPLAN].[Name], 'Not Specified') as [SPRollingForecastPlanName]
   ,ISNULL([SPLRPLAN].[Name], 'Not Specified') as [SPOperationsPlanName]
   ,ISNULL([SPLRPLAN_1].[Name], 'Not Specified') as [SPBalanceSheetPlanName]
   ,ISNULL([PatientTyRo].[Name], 'Not Specified') as [PatientTypeRollupName]
   ,ISNULL([JobCodeGrp].[Name], 'Not Specified') as [SPJobCodeGroupName]
   ,ISNULL([PhyGrp].[Name], 'Not Specified') as [SPPhysicianGroupName]
   ,ISNULL([SPAccountRollup].[Name], 'Not Specified') as [SPAccountRollupName]
   ,ISNULL([SPHDEPARTMENTROLLUP].[Name], 'Not Specified') as [SPHDepartmentRollupName]
   ,ISNULL([DEPTTYPE].[Name], 'Not Specified') as [DepartmentType]
   ,ISNULL([FUND].[Name], 'Not Specified') as [Fund]
   ,ISNULL([FUND].[SortOrder], 0) as [FundSortOrder]
   ,ISNULL([FWPROJECT].[Name], 'Not Specified') as [Project]
   ,ISNULL([FWPROJECT].[SortOrder], 0) as [ProjectSortOrder]
   ,ISNULL([FWPROJECT].[ProjectID], 0) as [HomeDepartmentID]
   ,ISNULL([HOMEDEPARTMENT].[Name], 'Not Specified') as [HomeDepartment]
   ,ISNULL([HOMEDEPARTMENT].[SortOrder], 0) as [HomeDepartmentSortOrder]
   ,ISNULL([PROGRAM].[Name], 'Not Specified') as [Program]
   ,ISNULL([PROGRAM].[SortOrder], 0) as [ProgramSortOrder]
   ,ISNULL([SPHDEPARTMENT].[Name], 'Not Specified') as [SPHDepartmentName]
   ,ISNULL([PRODUCTIVITYPERCENTILE].[Name], 'Not Specified') as [ProductivityPercentile]
   ,ISNULL([COMPANDEPARTMENT].[Description], 'Not Specified') as [CompAnDepartment]
, [grp34146F449F3140ECB03A8BC6153DE46F].[Version]FROM [fw].[DimDepartment] grp34146F449F3140ECB03A8BC6153DE46F (readuncommitted)
   LEFT JOIN [fw].[viewDimSystem] [SYSTEM]  on [SYSTEM].[SystemID] = [grp34146F449F3140ECB03A8BC6153DE46F].[SystemID]
   LEFT JOIN [fw].[viewDimEntity] [ENT]  on [ENT].[EntityID] = [grp34146F449F3140ECB03A8BC6153DE46F].[EntityID]
   LEFT JOIN [fw].[viewDimDepartmentRollup1] [DeptRollup1]  on [DeptRollup1].[DepartmentRollup1ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DepartmentRollup1ID]
   LEFT JOIN [fw].[viewDimDepartmentRollup2] [DeptRollup2]  on [DeptRollup2].[DepartmentRollup2ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DepartmentRollup2ID]
   LEFT JOIN [fw].[viewDimDepartmentRollup3] [DeptRollup3]  on [DeptRollup3].[DepartmentRollup3ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DepartmentRollup3ID]
   LEFT JOIN [fw].[viewDimDepartmentRollup4] [DeptRollup4]  on [DeptRollup4].[DepartmentRollup4ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DepartmentRollup4ID]
   LEFT JOIN [fw].[viewDimDepartmentRollup5] [DeptRollup5]  on [DeptRollup5].[DepartmentRollup5ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DepartmentRollup5ID]
   LEFT JOIN [fw].[viewDimDepartmentRollup6] [DeptRollup6]  on [DeptRollup6].[DepartmentRollup6ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DepartmentRollup6ID]
   LEFT JOIN [fw].[viewDimCareSetting] [CARESETTING]  on [CARESETTING].[CareSettingID] = [grp34146F449F3140ECB03A8BC6153DE46F].[CareSettingID]
   INNER JOIN [fw].[viewDimFunctionalArea] [FUNCTIONALAREA]  on [FUNCTIONALAREA].[FunctionalAreaID] = [grp34146F449F3140ECB03A8BC6153DE46F].[FunctionalAreaID]
   LEFT JOIN [fw].[viewDimResearchDepartmentCategory] [RESEARCHDEPARTMENTCATEGORY]  on [RESEARCHDEPARTMENTCATEGORY].[ResearchDepartmentCategoryID] = [grp34146F449F3140ECB03A8BC6153DE46F].[ResearchDepartmentCategoryID]
   INNER JOIN [dss].[viewDimAttributionType] [ATTRIBUTIONTYPE]  on [ATTRIBUTIONTYPE].[AttributionTypeID] = [grp34146F449F3140ECB03A8BC6153DE46F].[AttributionTypeID]
   LEFT JOIN [dss].[viewDimDepartmentRollup1] [DSSDEPTROLLUP1]  on [DSSDEPTROLLUP1].[DSSDepartmentRollup1ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DSSDepartmentRollup1ID]
   LEFT JOIN [dss].[viewDimDepartmentRollup2] [DSSDEPTROLLUP2]  on [DSSDEPTROLLUP2].[DSSDepartmentRollup2ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DSSDepartmentRollup2ID]
   LEFT JOIN [dss].[viewDimDepartmentRollup3] [DSSDEPTROLLUP3]  on [DSSDEPTROLLUP3].[DSSDepartmentRollup3ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DSSDepartmentRollup3ID]
   LEFT JOIN [dss].[viewDimDepartmentRollup4] [DSDEPTR4]  on [DSDEPTR4].[DSSDepartmentRollup4ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DSSDepartmentRollup4ID]
   LEFT JOIN [dss].[viewDimDepartmentRollup5] [DSSDEPT5]  on [DSSDEPT5].[DSSDepartmentRollup5ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DSSDepartmentRollup5ID]
   INNER JOIN [dss].[viewDimDepartmentRollup6] [DSSDEPTROLL6]  on [DSSDEPTROLL6].[DSSDepartmentRollup6ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DSSDepartmentRollup6ID]
   LEFT JOIN [dss].[viewDimDepartmentRollup7] [DSSDEPARTMENTROLLUP7]  on [DSSDEPARTMENTROLLUP7].[DSSDepartmentRollup7ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DSSDepartmentRollup7ID]
   LEFT JOIN [ob].[viewDimOBGlobalStatisticsPlan] [OBGLOBALSTATISTICSPLAN]  on [OBGLOBALSTATISTICSPLAN].[OBGlobalStatisticsPlanID] = [grp34146F449F3140ECB03A8BC6153DE46F].[OBGlobalStatisticsPlanID]
   LEFT JOIN [ob].[viewDimOBReimbursementPlan] [OBREIMBURSEMENTPLAN]  on [OBREIMBURSEMENTPLAN].[OBReimbursementPlanID] = [grp34146F449F3140ECB03A8BC6153DE46F].[OBReimbursementPlanID]
   LEFT JOIN [ob].[viewDimOBServiceLinePlan] [OBSERVICELINEPLAN]  on [OBSERVICELINEPLAN].[OBServiceLinePlanID] = [grp34146F449F3140ECB03A8BC6153DE46F].[OBServiceLinePlanID]
   LEFT JOIN [sp].[viewDimSPRollingForecastPlan] [SPRFPLAN]  on [SPRFPLAN].[SPRollingForecastPlanID] = [grp34146F449F3140ECB03A8BC6153DE46F].[RollingPlanID]
   LEFT JOIN [sp].[viewDimSPLongRangePlan] [SPLRPLAN]  on [SPLRPLAN].[SPLongRangePlanID] = [grp34146F449F3140ECB03A8BC6153DE46F].[OpsPlanID]
   LEFT JOIN [sp].[viewDimSPLongRangePlan] [SPLRPLAN_1]  on [SPLRPLAN_1].[SPLongRangePlanID] = [grp34146F449F3140ECB03A8BC6153DE46F].[BalPlanID]
   LEFT JOIN [fw].[viewDimPatientTypeRollup] [PatientTyRo]  on [PatientTyRo].[PatientTypeRollupID] = [grp34146F449F3140ECB03A8BC6153DE46F].[PatientTypeRollup]
   LEFT JOIN [fw].[viewDimJobCodeGroup] [JobCodeGrp]  on [JobCodeGrp].[JobCodeGroupID] = [grp34146F449F3140ECB03A8BC6153DE46F].[SPJobCodeGroup]
   LEFT JOIN [fw].[viewDimPhysicianGroup] [PhyGrp]  on [PhyGrp].[PhysicianGroupID] = [grp34146F449F3140ECB03A8BC6153DE46F].[SPPhysicianGroup]
   LEFT JOIN [sp].[viewDimAccountRollup] [SPAccountRollup]  on [SPAccountRollup].[AccountRollupID] = [grp34146F449F3140ECB03A8BC6153DE46F].[SPAccountRollup]
   LEFT JOIN [fw].[viewDimSPHDepartmentRollup] [SPHDEPARTMENTROLLUP]  on [SPHDEPARTMENTROLLUP].[SPHDepartmentRollupID] = [grp34146F449F3140ECB03A8BC6153DE46F].[SPHDepartmentRollupID]
   INNER JOIN [fw].[viewDimDepartmentType] [DEPTTYPE]  on [DEPTTYPE].[DepartmentTypeID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DepartmentTypeID]
   LEFT JOIN [fw].[viewDimFund] [FUND]  on [FUND].[FundID] = [grp34146F449F3140ECB03A8BC6153DE46F].[FundID]
   LEFT JOIN [fw].[viewDimProject] [FWPROJECT]  on [FWPROJECT].[ProjectID] = [grp34146F449F3140ECB03A8BC6153DE46F].[ProjectID]
   LEFT JOIN [fw].[viewDimHomeDepartment] [HOMEDEPARTMENT]  on [HOMEDEPARTMENT].[HomeDepartmentID] = [grp34146F449F3140ECB03A8BC6153DE46F].[HomeDepartmentID]
   LEFT JOIN [fw].[viewDimProgram] [PROGRAM]  on [PROGRAM].[ProgramID] = [grp34146F449F3140ECB03A8BC6153DE46F].[ProgramID]
   INNER JOIN [fw].[viewDimSPHDepartment_auto] [SPHDEPARTMENT]  on [SPHDEPARTMENT].[SPHDepartmentID] = [grp34146F449F3140ECB03A8BC6153DE46F].[SPHDepartmentID]
   INNER JOIN [pi].[viewDimProductivityPercentile] [PRODUCTIVITYPERCENTILE]  on [PRODUCTIVITYPERCENTILE].[ProductivityPercentileID] = [grp34146F449F3140ECB03A8BC6153DE46F].[ProductivityPercentileID]
   INNER JOIN [fw].[viewDimCompAnDepartment] [COMPANDEPARTMENT]  on [COMPANDEPARTMENT].[CompAnDepartmentID] = [grp34146F449F3140ECB03A8BC6153DE46F].[CompAnDepartmentID]
GO


---------------------------------------------

-- fw.viewDimDepartment_triggers
CREATE view fw.viewDimDepartment_triggers
as
select 
	d.FriendlyName as RefreshDimension, 
	'exec procScoreSetDimensionSecurity30 ''' + cast(d.DimensionGUID as nvarchar(36)) + ''',0,0' as RefreshSQL,
	'drop trigger fw.' + tg.Name as DropSQL 
from 
	sys.triggers tg 
	inner join [dbo].[ScoreDimension] d on tg.name like '%' + replace(cast(d.DimensionGUID as nvarchar(36)),'-', '') + '%' where tg.parent_id in(select t.object_id from sys.tables t inner join sys.schemas s on s.schema_id = t.schema_id where t.name = 'DimDepartment' and s.name = 'fw') 
	and name like '%ScoreDimension%'
GO


---------------------------------------------

-- fw.viewDimEmployee
CREATE VIEW [fw].[viewDimEmployee]
AS
SELECT

[EmployeeID],
 COALESCE([Name],'') as [Name],
[NameLast],
[NameFirst],
[Number],
[JobCodeID],
[Code],
[OBIsDefined],
[WageRate],
[IsProvider],
[ProviderID],
 COALESCE([JobCode],'') as [JobCode],
 COALESCE([JobCodeCode],'') as [JobCodeCode],
[IsVariable],
[HireDate],
[IsActive],
[Status],
[NextReview],
[MemberGUID],
[HistoryItemGUID],
[WorkWeekOverrideID],
[HomeDepartmentID],
 COALESCE([HomeDepartment],'') as [HomeDepartment],
 COALESCE([HomeDepartmentCode],'') as [HomeDepartmentCode],
 COALESCE([NameFull],'') as [NameFull],
[EmployeeCohortID],
 COALESCE([EmployeeCohortName],'') as [EmployeeCohortName],
[EmployeeCohortContractDate],
 COALESCE([EmployeeCohortMeritType],'') as [EmployeeCohortMeritType],
[StandardHours],
[FWIsDefined],
[TerminationDate],
[AdjustedHireDate],
[FTETotal],
[HomeAccountID],
 COALESCE([HomeAccount],'') as [HomeAccount],
 COALESCE([HomeAccountCode],'') as [HomeAccountCode],
[EmployeeClass],
[NPI],
[TransactionID],
[PositionControlNumber]    ,[Version]

FROM [fw].[DimEmployee] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimEmployeeCohort
--Last Modified 4/13/2015 3:16 PM
CREATE VIEW [fw].[viewDimEmployeeCohort]
AS
SELECT
   grp62E0F8DE46CB42D18A44A996145E4741.[EmployeeCohortID]
   ,grp62E0F8DE46CB42D18A44A996145E4741.[Name]
   ,grp62E0F8DE46CB42D18A44A996145E4741.[Code]
   ,grp62E0F8DE46CB42D18A44A996145E4741.[Description]
   ,grp62E0F8DE46CB42D18A44A996145E4741.[MeritType]
   ,grp62E0F8DE46CB42D18A44A996145E4741.[ContractDate]
   ,grp62E0F8DE46CB42D18A44A996145E4741.[SortOrder]
   ,grp62E0F8DE46CB42D18A44A996145E4741.[TransactionID]
   ,grp62E0F8DE46CB42D18A44A996145E4741.[MemberGUID]
   ,grp62E0F8DE46CB42D18A44A996145E4741.[HistoryItemGUID]
FROM [fw].[DimEmployeeCohort] grp62E0F8DE46CB42D18A44A996145E4741 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimEmployeePH
CREATE VIEW [fw].[viewDimEmployeePH]
AS
SELECT
   grpAE7FA4E45FE14270A057580F39CDA6F1.[EmployeePHID]
   ,grpAE7FA4E45FE14270A057580F39CDA6F1.[Name]
   ,grpAE7FA4E45FE14270A057580F39CDA6F1.[MemberGUID]
FROM [fw].[DimEmployeePH] grpAE7FA4E45FE14270A057580F39CDA6F1 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimEmployee_source
CREATE VIEW [fw].[viewDimEmployee_source]
AS
SELECT
   grp304BAC4BC73943CCBFF4E85B307B146A.[EmployeeID]
   ,grp304BAC4BC73943CCBFF4E85B307B146A.[Name]
   ,grp304BAC4BC73943CCBFF4E85B307B146A.[MemberGUID]
   ,grp304BAC4BC73943CCBFF4E85B307B146A.[HistoryItemGUID]
   ,grp304BAC4BC73943CCBFF4E85B307B146A.[NameFull]
   ,grp304BAC4BC73943CCBFF4E85B307B146A.[TransactionID]
   ,ISNULL([JOBCODE].[Name], 'Not Specified') as [JobCode]
   ,ISNULL([JOBCODE].[JobCode], 'Not Specified') as [JobCodeCode]
   ,ISNULL([JOBCODE].[IsVariable], 0) as [IsVariable]
   ,ISNULL([JOBCODE].[WorkWeekOverrideID], 0) as [WorkWeekOverrideID]
   ,ISNULL([DEPT].[Name], 'Not Specified') as [HomeDepartment]
   ,ISNULL([DEPT].[DepartmentCode], 'Not Specified') as [HomeDepartmentCode]
   ,ISNULL([EMPLOYEECOHORT].[Name], 'Not Specified') as [EmployeeCohortName]
   ,ISNULL([EMPLOYEECOHORT].[ContractDate], getdate()) as [EmployeeCohortContractDate]
   ,ISNULL([EMPLOYEECOHORT].[MeritType], 'Not Specified') as [EmployeeCohortMeritType]
   ,ISNULL([ACCT].[Name], 'Not Specified') as [HomeAccount]
   ,ISNULL([ACCT].[AccountCode], 'Not Specified') as [HomeAccountCode]
, [grp304BAC4BC73943CCBFF4E85B307B146A].[Version]FROM [fw].[DimEmployee] grp304BAC4BC73943CCBFF4E85B307B146A (readuncommitted)
   LEFT JOIN [fw].[viewDimJobCode] [JOBCODE]  on [JOBCODE].[JobCodeID] = [grp304BAC4BC73943CCBFF4E85B307B146A].[JobCodeID]
   LEFT JOIN [fw].[viewDimDepartment] [DEPT]  on [DEPT].[DepartmentID] = [grp304BAC4BC73943CCBFF4E85B307B146A].[HomeDepartmentID]
   INNER JOIN [fw].[viewDimEmployeeCohort] [EMPLOYEECOHORT]  on [EMPLOYEECOHORT].[EmployeeCohortID] = [grp304BAC4BC73943CCBFF4E85B307B146A].[EmployeeCohortID]
   INNER JOIN [fw].[viewDimAccount] [ACCT]  on [ACCT].[AccountID] = [grp304BAC4BC73943CCBFF4E85B307B146A].[HomeAccountID]
GO


---------------------------------------------

-- fw.viewDimEntity
CREATE VIEW [fw].[viewDimEntity]
AS
SELECT

[EntityID],
 COALESCE([Name],'') as [Name],
[Code],
[Description],
[SortOrder],
[EntityType],
[IsActive],
[CAPIsDefined],
[DSSIsDefined],
[OBIsDefined],
[OBBenefitsDepartmentID],
 COALESCE([OBBenefitsDepartment],'') as [OBBenefitsDepartment],
[OBHasGlobalStatisticsPlan],
[OBHasReimbursementPlan],
[OBHasServiceLinePlan],
[OBIsUsingProviderComp],
[SPIsDefined],
[SPGrossChargesPatientTypeRollup],
[SPGrossChargesPayorGroup],
[SPContractualsPatientTypeRollup],
[SPContractualsPayorGroup],
[SPIPVolumesPatientTypeRollup],
[SPIPVolumesPayorGroup],
[SPIPDaysPatientTypeRollup],
[SPIPDaysPayorGroup],
[SPOPVolumesPatientTypeRollup],
[SPOPVolumesPayorGroup],
[SPFTEsJobCodeGroup],
[SPSalariesJobCodeGroup],
[SPClinicGrossChargesPayorGroup],
[SPClinicContractualsPayorGroup],
[SPClinicPrimaryVolumePhysicianGroup],
[SPClinicSecondaryVolumePhysicianGroup],
[SPClinicFTEsPhysicianGroup],
[SPClinicSalariesPhysicianGroup],
[SPOperationsSLDrivenModelID],
[SPRollingForecastSLDrivenModelID],
[SPServiceLineForecastType],
[SecureGroupID],
[WorkWeekID],
[TransactionID],
[PayCycleID],
[HistoryItemGUID],
[MemberGUID],
[CAPDefaultSalesTax],
[FWIsDefined],
[EliminationsDepartmentID],
[CompAnPeerGroupID]
FROM [fw].[DimEntity] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimEntityPH
Create VIEW [fw].[viewDimEntityPH]
AS
SELECT
   [EntityPHID],
   [Name],
   [MemberGUID],
   [HistoryItemGUID],
   [TransactionID]
FROM [fw].[DimEntityPH] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimEntity_source
CREATE VIEW [fw].[viewDimEntity_source]
AS
SELECT
   grpDE819FBD8CE84979B478F0E94260A8F7.[EntityID]
   ,grpDE819FBD8CE84979B478F0E94260A8F7.[Name]
   ,grpDE819FBD8CE84979B478F0E94260A8F7.[SecureGroupID]
   ,grpDE819FBD8CE84979B478F0E94260A8F7.[TransactionID]
   ,grpDE819FBD8CE84979B478F0E94260A8F7.[HistoryItemGUID]
   ,grpDE819FBD8CE84979B478F0E94260A8F7.[MemberGUID]
   ,ISNULL([DEPT].[Name], 'Not Specified') as [OBBenefitsDepartment]
FROM [fw].[DimEntity] grpDE819FBD8CE84979B478F0E94260A8F7 (readuncommitted)
   INNER JOIN [fw].[viewDimDepartment] [DEPT]  on [DEPT].[DepartmentID] = [grpDE819FBD8CE84979B478F0E94260A8F7].[OBBenefitsDepartmentID]
GO


---------------------------------------------

-- fw.viewDimFiscalMonth
--Last Modified 5/8/2015 5:50 PM
CREATE VIEW [fw].[viewDimFiscalMonth]
AS
SELECT
   grpC5A4CCC2DC85403F8A1BD9849CF14E18.[FiscalMonthID]
  ,coalesce(grpC5A4CCC2DC85403F8A1BD9849CF14E18.[Name],'') as [Name]
   ,grpC5A4CCC2DC85403F8A1BD9849CF14E18.[FiscalMonthCode]
  ,coalesce(grpC5A4CCC2DC85403F8A1BD9849CF14E18.[Abbreviation],'') as [Abbreviation]
   ,grpC5A4CCC2DC85403F8A1BD9849CF14E18.[QuarterID]
   ,grpC5A4CCC2DC85403F8A1BD9849CF14E18.[SortOrder]
   ,grpC5A4CCC2DC85403F8A1BD9849CF14E18.[DaysInMonth]
   ,grpC5A4CCC2DC85403F8A1BD9849CF14E18.[YTDDaysInMonth]
   ,grpC5A4CCC2DC85403F8A1BD9849CF14E18.[MemberGUID]
  ,coalesce(grpC5A4CCC2DC85403F8A1BD9849CF14E18.[MonthColumnName],'') as [MonthColumnName]
   ,grpC5A4CCC2DC85403F8A1BD9849CF14E18.[HistoryItemGUID]
   ,grpC5A4CCC2DC85403F8A1BD9849CF14E18.[IsReal]
, [grpC5A4CCC2DC85403F8A1BD9849CF14E18].[Version]FROM [fw].[DimFiscalMonth] grpC5A4CCC2DC85403F8A1BD9849CF14E18 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimFiscalTime
--Last Modified 3/15/2022 10:09 PM
CREATE VIEW [fw].[viewDimFiscalTime]
AS
SELECT
   grp32094482DE9943D5832B9F8295DACBDF.[FiscalTimeID]
   ,grp32094482DE9943D5832B9F8295DACBDF.[FiscalTime]
   ,grp32094482DE9943D5832B9F8295DACBDF.[TransactionID]
   ,grp32094482DE9943D5832B9F8295DACBDF.[MemberGUID]
   ,grp32094482DE9943D5832B9F8295DACBDF.[HistoryItemGUID]
   ,grp32094482DE9943D5832B9F8295DACBDF.[FiscalYearID]
   ,grp32094482DE9943D5832B9F8295DACBDF.[FiscalMonthID]
   ,grp32094482DE9943D5832B9F8295DACBDF.[YearMonth]
   ,grp32094482DE9943D5832B9F8295DACBDF.[CountFromCurrentMonth]
   ,grp32094482DE9943D5832B9F8295DACBDF.[StartDate]
   ,grp32094482DE9943D5832B9F8295DACBDF.[EndDate]
FROM [fw].[DimFiscalTime] grp32094482DE9943D5832B9F8295DACBDF (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimFiscalYear
--Last Modified 5/8/2015 5:50 PM
CREATE VIEW [fw].[viewDimFiscalYear]
AS
SELECT
   grp07DC08C1A3354C289D66B7FAF5CEC935.[FiscalYearID]
   ,grp07DC08C1A3354C289D66B7FAF5CEC935.[MemberGUID]
   ,grp07DC08C1A3354C289D66B7FAF5CEC935.[Name]
   ,grp07DC08C1A3354C289D66B7FAF5CEC935.[SortOrder]
   ,grp07DC08C1A3354C289D66B7FAF5CEC935.[IsSP]
   ,grp07DC08C1A3354C289D66B7FAF5CEC935.[HistoryItemGUID]
   ,grp07DC08C1A3354C289D66B7FAF5CEC935.[IsCAP]
, [grp07DC08C1A3354C289D66B7FAF5CEC935].[Version]FROM [fw].[DimFiscalYear] grp07DC08C1A3354C289D66B7FAF5CEC935 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimFiscalYearPH_auto
CREATE VIEW [fw].[viewDimFiscalYearPH_auto]
AS
SELECT
   grp74AEECE5F9BE4AAFA6BADD6EF917266F.[Name]
   ,grp74AEECE5F9BE4AAFA6BADD6EF917266F.[MemberGUID]
   ,grp74AEECE5F9BE4AAFA6BADD6EF917266F.[FiscalYearPHID]
   ,grp74AEECE5F9BE4AAFA6BADD6EF917266F.[HistoryItemGUID]
, [grp74AEECE5F9BE4AAFA6BADD6EF917266F].[Version]FROM [fw].[DimFiscalYearPH] grp74AEECE5F9BE4AAFA6BADD6EF917266F (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimFlag
--Last Modified 4/12/2019 11:35 AM
CREATE VIEW [fw].[viewDimFlag]
AS
SELECT
   grp7ECC55FC3D4F41479EA1C29BC253029B.[FlagID]
   ,grp7ECC55FC3D4F41479EA1C29BC253029B.[Code]
   ,grp7ECC55FC3D4F41479EA1C29BC253029B.[Description]
  ,coalesce(grp7ECC55FC3D4F41479EA1C29BC253029B.[Name],'') as [Name]
   ,grp7ECC55FC3D4F41479EA1C29BC253029B.[TransactionID]
   ,grp7ECC55FC3D4F41479EA1C29BC253029B.[MemberGUID]
   ,grp7ECC55FC3D4F41479EA1C29BC253029B.[HistoryItemGUID]
FROM [fw].[DimFlag] grp7ECC55FC3D4F41479EA1C29BC253029B (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimFlexJobCodeGroup
--Last Modified 2/25/2015 11:46 AM
CREATE VIEW [fw].[viewDimFlexJobCodeGroup]
AS
SELECT
   grp37D108FB34FF431799A3DD4B6EDB7CDC.[FlexJobCodeGroupID]
   ,grp37D108FB34FF431799A3DD4B6EDB7CDC.[Name]
   ,grp37D108FB34FF431799A3DD4B6EDB7CDC.[Code]
   ,grp37D108FB34FF431799A3DD4B6EDB7CDC.[SortOrder]
   ,grp37D108FB34FF431799A3DD4B6EDB7CDC.[TransactionID]
   ,grp37D108FB34FF431799A3DD4B6EDB7CDC.[MemberGUID]
   ,grp37D108FB34FF431799A3DD4B6EDB7CDC.[HistoryItemGUID]
FROM [fw].[DimFlexJobCodeGroup] grp37D108FB34FF431799A3DD4B6EDB7CDC (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimForecastDetail
CREATE VIEW [fw].[viewDimForecastDetail]
AS
SELECT

[ForecastDetailID],
 COALESCE([Name],'') as [Name],
[ForecastDetailCode],
[Description],
[CAPForecastDetailID],
[CPIsDefined],
[OBForecastDetailID],
[OBIsDefined],
[SPAccountRollupID],
[SPIsDefined],
[TransactionID],
[SPCostComponentID],
[MemberGUID],
[HistoryItemGUID]
FROM [fw].[DimForecastDetail] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimForecastDetail_source
CREATE VIEW [fw].[viewDimForecastDetail_source]
AS
SELECT
   grp19542254A1554DCB89A76BAACAB6E162.[ForecastDetailID]
   ,grp19542254A1554DCB89A76BAACAB6E162.[Name]
   ,grp19542254A1554DCB89A76BAACAB6E162.[TransactionID]
   ,grp19542254A1554DCB89A76BAACAB6E162.[MemberGUID]
   ,grp19542254A1554DCB89A76BAACAB6E162.[HistoryItemGUID]
FROM [fw].[DimForecastDetail] grp19542254A1554DCB89A76BAACAB6E162 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimFramework
CREATE view [fw].[viewDimFramework]
as
	select
		fwk.FrameworkID,
		fwk.Name,
		fwk.Abbreviation,
		fwk.FrameworkSchemaName,
		fwk.ClientSchemaName,
		fwk.IsLatestDataModel,
		case when fwk.Name = 'General' then cast(1 as bit) else cast(max(cast(isnull(m.IsLicensed, 0) as int)) as bit) end as IsLicensed,
		cast(max(cast(isnull(m.IsSetupComplete, 0) as int)) as bit) as IsSetupComplete
	from
		[fw].[DimFramework] fwk
		left join [dbo].[SystemCenterSolution] s on s.Name = fwk.Name
		left join [dbo].[SystemCenterModule] m on m.SolutionGUID = s.SolutionGUID or m.Name = fwk.Name
	group by
		fwk.FrameworkID,
		fwk.Name,
		fwk.Abbreviation,
		fwk.FrameworkSchemaName,
		fwk.ClientSchemaName,
		fwk.IsLatestDataModel
GO


---------------------------------------------

-- fw.viewDimFramework_auto
CREATE VIEW [fw].[viewDimFramework_auto]
AS
SELECT
  coalesce(grp67F5902643D4451785A9B828FC66FFFD.[Name],'') as [Name]
   ,grp67F5902643D4451785A9B828FC66FFFD.[MemberGUID]
   ,grp67F5902643D4451785A9B828FC66FFFD.[FrameworkID]
, [grp67F5902643D4451785A9B828FC66FFFD].[Version], [grp67F5902643D4451785A9B828FC66FFFD].[HistoryItemGUID]FROM [fw].[DimFramework] grp67F5902643D4451785A9B828FC66FFFD (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimFunctionalArea
CREATE VIEW [fw].[viewDimFunctionalArea]
AS
SELECT
   grp6CD1220F54B84B4F9BA381B12A98DDB4.[FunctionalAreaID]
   ,grp6CD1220F54B84B4F9BA381B12A98DDB4.[Name]
   ,grp6CD1220F54B84B4F9BA381B12A98DDB4.[TransactionID]
   ,grp6CD1220F54B84B4F9BA381B12A98DDB4.[MemberGUID]
   ,grp6CD1220F54B84B4F9BA381B12A98DDB4.[HistoryItemGUID]
FROM [fw].[DimFunctionalArea] grp6CD1220F54B84B4F9BA381B12A98DDB4 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimFund
--Last Modified 5/27/2015 1:34 PM
CREATE VIEW [fw].[viewDimFund]
AS
SELECT
   grp15688121574D4B38A25965FF7CA63FCE.[FundID]
  ,coalesce(grp15688121574D4B38A25965FF7CA63FCE.[Name],'') as [Name]
   ,grp15688121574D4B38A25965FF7CA63FCE.[Code]
   ,grp15688121574D4B38A25965FF7CA63FCE.[Description]
   ,grp15688121574D4B38A25965FF7CA63FCE.[SortOrder]
   ,grp15688121574D4B38A25965FF7CA63FCE.[TransactionID]
   ,grp15688121574D4B38A25965FF7CA63FCE.[MemberGUID]
   ,grp15688121574D4B38A25965FF7CA63FCE.[HistoryItemGUID]
FROM [fw].[DimFund] grp15688121574D4B38A25965FF7CA63FCE (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimGLAndPayrollInitiative
--Last Modified 9/12/2022 9:10 PM
CREATE VIEW [fw].[viewDimGLAndPayrollInitiative]
AS
SELECT
   grpBE8428F4CC9543D192CBE7EBD767DB6C.[GLAndPayrollInitiativeGUID]
   ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[Name]
   ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[Owner]
   ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[Author]
   ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[CostLeader]
   ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[ExecutiveSponsor]
   ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[EffectiveDate]
   ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[AnnualGoal]
   ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[DateCreated]
   ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[GoalStartDate]
   ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[GoalEndDate]
   ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[SavingsEstimate]
   ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[SourceOfSavings]
   ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[Description]
   ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[Workstream]
   ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[InitiativeStatus]
FROM [cci].[viewDimGLAndPayrollInitiative] grpBE8428F4CC9543D192CBE7EBD767DB6C
GO


---------------------------------------------

-- fw.viewDimGLAndPayrollOpportunity
--Last Modified 9/12/2022 9:10 PM
CREATE VIEW [fw].[viewDimGLAndPayrollOpportunity]
AS
SELECT
   grp45B56B6F4F434F229DB3FA943E5107AE.[GLAndPayrollOpportunityGUID]
   ,grp45B56B6F4F434F229DB3FA943E5107AE.[Name]
   ,grp45B56B6F4F434F229DB3FA943E5107AE.[Owner]
   ,grp45B56B6F4F434F229DB3FA943E5107AE.[AnnualGoal]
   ,grp45B56B6F4F434F229DB3FA943E5107AE.[SavingsEstimate]
   ,grp45B56B6F4F434F229DB3FA943E5107AE.[OpportunityKey]
   ,grp45B56B6F4F434F229DB3FA943E5107AE.[DateCreated]
   ,grp45B56B6F4F434F229DB3FA943E5107AE.[BaselineStartDate]
   ,grp45B56B6F4F434F229DB3FA943E5107AE.[BaselineEndDate]
   ,grp45B56B6F4F434F229DB3FA943E5107AE.[SavingsIdentified]
   ,grp45B56B6F4F434F229DB3FA943E5107AE.[SavingsGoal]
   ,grp45B56B6F4F434F229DB3FA943E5107AE.[HasInitiative]
   ,grp45B56B6F4F434F229DB3FA943E5107AE.[SourceOfSavings]
   ,grp45B56B6F4F434F229DB3FA943E5107AE.[IsHidden]
FROM [cci].[viewDimGLAndPayrollOpportunity] grp45B56B6F4F434F229DB3FA943E5107AE
GO


---------------------------------------------

-- fw.viewDimGLPostDate
CREATE VIEW [fw].[viewDimGLPostDate] 
AS
	SELECT 
		DateID AS [GLPostDateID]
		,TransactionID
		,DayNumberOfWeek
		,DayNameOfWeek
		,DayNumberOfMonth
		,DayNumberOfYear
		,WeekNumberOfYear
		,IsWeekDay
		,CalendarQuarter
		,CalendarDateTime
		,CalendarYear
		,CalendarMonth
		,CalendarMonthName
		,FiscalYear
		,FiscalYearName
		,HistoryItemGUID
		,MemberGUID
		,FiscalMonth
		,FiscalQuarter
		,YearMonth
		,MonthYear
		,DaysInMonth
		,PremierMapping
	FROM [fw].[DimDate];
GO


---------------------------------------------

-- fw.viewDimGLPostDate_auto
--Last Modified 6/8/2020 3:11 PM
CREATE VIEW [fw].[viewDimGLPostDate_auto]
AS
SELECT
   grp5D0EB954A8774F2B9816D9D0814D3F9F.[GLPostDateID]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[TransactionID]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[DayNumberOfWeek]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[DayNameOfWeek]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[DayNumberOfMonth]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[DayNumberOfYear]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[WeekNumberOfYear]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[IsWeekDay]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[CalendarQuarter]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[CalendarDateTime]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[CalendarYear]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[CalendarMonth]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[CalendarMonthName]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[FiscalYear]
  ,coalesce(grp5D0EB954A8774F2B9816D9D0814D3F9F.[FiscalYearName],'') as [FiscalYearName]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[HistoryItemGUID]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[MemberGUID]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[FiscalMonth]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[FiscalQuarter]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[YearMonth]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[MonthYear]
   ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[DaysInMonth]
  ,coalesce(grp5D0EB954A8774F2B9816D9D0814D3F9F.[PremierMapping],'') as [PremierMapping]
FROM [fw].[viewDimGLPostDate] grp5D0EB954A8774F2B9816D9D0814D3F9F
GO


---------------------------------------------

-- fw.viewDimGMTestFWProj
CREATE VIEW [fw].[viewDimGMTestFWProj]
AS
SELECT
   grpDB12BF7D35E34296A3CBFCDACB880F51.[GMTestFWDateCreated]
   ,grpDB12BF7D35E34296A3CBFCDACB880F51.[GMTestFWName]
   ,grpDB12BF7D35E34296A3CBFCDACB880F51.[MemberGUID]
   ,grpDB12BF7D35E34296A3CBFCDACB880F51.[GMTestFWProjID]
   ,ISNULL([DimXP].[PlanID], 0) as [PlanID]
   ,ISNULL([DimXP].[Name], 'Not Specified') as [Name]
FROM [cap].[DimGMTestFWProj] grpDB12BF7D35E34296A3CBFCDACB880F51 (readuncommitted)
   INNER JOIN [fw].[viewDimXPlan_auto] [DimXP]  on [DimXP].[MemberGUID] = [grpDB12BF7D35E34296A3CBFCDACB880F51].[MemberGUID]
GO


---------------------------------------------

-- fw.viewDimHealthPlanRegion
CREATE VIEW [fw].[viewDimHealthPlanRegion] 
AS
	SELECT 
		DepartmentRollup1ID AS [HealthPlanRegionID]
		,Name
		,Code AS [Code]
		,Description
		,SortOrder
		,SecureGroupID
		,MemberGUID
		,HistoryItemGUID
		,EliminationsDepartmentID
	FROM [fw].[DimDepartmentRollup1];
GO


---------------------------------------------

-- fw.viewDimHealthPlanRegion_auto
--Last Modified 10/30/2018 9:41 AM
CREATE VIEW [fw].[viewDimHealthPlanRegion_auto]
AS
SELECT
   grp59F984CE07874F708A1B24F9C8376E7D.[HealthPlanRegionID]
  ,coalesce(grp59F984CE07874F708A1B24F9C8376E7D.[Name],'') as [Name]
   ,grp59F984CE07874F708A1B24F9C8376E7D.[Code]
   ,grp59F984CE07874F708A1B24F9C8376E7D.[Description]
   ,grp59F984CE07874F708A1B24F9C8376E7D.[SortOrder]
   ,grp59F984CE07874F708A1B24F9C8376E7D.[SecureGroupID]
   ,grp59F984CE07874F708A1B24F9C8376E7D.[MemberGUID]
   ,grp59F984CE07874F708A1B24F9C8376E7D.[HistoryItemGUID]
   ,grp59F984CE07874F708A1B24F9C8376E7D.[EliminationsDepartmentID]
FROM [fw].[viewDimHealthPlanRegion] grp59F984CE07874F708A1B24F9C8376E7D
GO


---------------------------------------------

-- fw.viewDimHomeDepartment
--Last Modified 5/26/2015 10:11 AM
CREATE VIEW [fw].[viewDimHomeDepartment]
AS
SELECT
   grp4A1ECAA1FE314B2F8C73E9A238625529.[HomeDepartmentID]
  ,coalesce(grp4A1ECAA1FE314B2F8C73E9A238625529.[Name],'') as [Name]
   ,grp4A1ECAA1FE314B2F8C73E9A238625529.[Code]
   ,grp4A1ECAA1FE314B2F8C73E9A238625529.[Description]
   ,grp4A1ECAA1FE314B2F8C73E9A238625529.[SortOrder]
   ,grp4A1ECAA1FE314B2F8C73E9A238625529.[TransactionID]
   ,grp4A1ECAA1FE314B2F8C73E9A238625529.[MemberGUID]
   ,grp4A1ECAA1FE314B2F8C73E9A238625529.[HistoryItemGUID]
FROM [fw].[DimHomeDepartment] grp4A1ECAA1FE314B2F8C73E9A238625529 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimInitiative
CREATE   VIEW [fw].[viewDimInitiative]
AS
SELECT
   grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Name]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Description]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[MemberGUID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[MemberGUID] AS [InitiativeGUID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[HistoryItemGUID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[TransactionID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeStatusID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeStatus]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[AuthorGUID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Author]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[CostLeaderGUID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[CostLeader]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[OwnerGUID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Owner]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[ExecutiveSponsorGUID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[ExecutiveSponsor]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[SourceOfSavingsID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[SourceOfSavings]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Workstream]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[DateCreated]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[EffectiveDate]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[GoalStartDate]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[GoalEndDate]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[AnnualGoal]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[SavingsEstimate]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeRollup1ID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeRollup1]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeRollup2ID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeRollup2]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeRollup3ID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeRollup3]
FROM [fw].[DimInitiative] grp63E2E9DC1F4747C7A31CA6E43ECE1FF4
GO


---------------------------------------------

-- fw.viewDimInitiativeStatus
--Last Modified 10/31/2018 10:40 AM
CREATE VIEW [fw].[viewDimInitiativeStatus]
AS
SELECT
   grpC9DC306912F4434CA7D806FB28CC0AF9.[InitiativeStatusID]
   ,grpC9DC306912F4434CA7D806FB28CC0AF9.[Name]
   ,grpC9DC306912F4434CA7D806FB28CC0AF9.[MemberGUID]
   ,grpC9DC306912F4434CA7D806FB28CC0AF9.[HistoryItemGUID]
   ,grpC9DC306912F4434CA7D806FB28CC0AF9.[TransactionID]
FROM [fw].[DimInitiativeStatus] grpC9DC306912F4434CA7D806FB28CC0AF9 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimInitiative_auto
--Last Modified 7/10/2024 5:05 PM
CREATE VIEW [fw].[viewDimInitiative_auto]
AS
SELECT
   grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Name]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[TransactionID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[MemberGUID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[HistoryItemGUID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeGUID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Description]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Workstream]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[DateCreated]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Author]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[EffectiveDate]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[SourceOfSavingsId]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[SourceOfSavings]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeStatusID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[GoalStartDate]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[GoalEndDate]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[CostLeaderGUID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[AnnualGoal]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[SavingsEstimate]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[OwnerGUID]
   ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[ExecutiveSponsorGUID]
   ,ISNULL([INITIATIVESTATUS].[Name], 'Not Specified') as [InitiativeStatus]
   ,ISNULL([CICOSTLEADER].[NameFull], 'Not Specified') as [CostLeader]
   ,ISNULL([CIOWNER].[NameFull], 'Not Specified') as [Owner]
   ,ISNULL([CIEXECUTIVESPONSOR].[NameFull], 'Not Specified') as [ExecutiveSponsor]
FROM [fw].[viewDimInitiative] grp63E2E9DC1F4747C7A31CA6E43ECE1FF4 
   INNER JOIN [fw].[viewDimInitiativeStatus] [INITIATIVESTATUS]  on [INITIATIVESTATUS].[InitiativeStatusID] = [grp63E2E9DC1F4747C7A31CA6E43ECE1FF4].[InitiativeStatusID]
   INNER JOIN [fw].[viewDimCICostLeader_auto] [CICOSTLEADER]  on [CICOSTLEADER].[CICostLeaderID] = [grp63E2E9DC1F4747C7A31CA6E43ECE1FF4].[CostLeaderGUID]
   INNER JOIN [fw].[viewDimCIOwner_auto] [CIOWNER]  on [CIOWNER].[CIOwnerID] = [grp63E2E9DC1F4747C7A31CA6E43ECE1FF4].[OwnerGUID]
   INNER JOIN [fw].[viewDimCIExecutiveSponsor_auto] [CIEXECUTIVESPONSOR]  on [CIEXECUTIVESPONSOR].[CIExecutiveSponsorID] = [grp63E2E9DC1F4747C7A31CA6E43ECE1FF4].[ExecutiveSponsorGUID]
GO


---------------------------------------------

-- fw.viewDimJobCode
--Last Modified 8/21/2024 10:16 AM
CREATE VIEW [fw].[viewDimJobCode]
AS
SELECT
   grpAAD69FC0ED76427EA52ED356470BFE0A.[JobCodeID]
  ,coalesce(grpAAD69FC0ED76427EA52ED356470BFE0A.[Name],'') as [Name]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[JobCode]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[Description]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[JobCodeGroupID]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsVariable]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsPR]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsDaily]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsActive]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsProvider]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsAgency]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSIsDefined]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSCostingRollup]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSRate]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[OBIsDefined]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[FlexBucketGUID]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[SPIsDefined]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[Rollup]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[Variability]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[MemberGUID]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[FlexJobCodeGroupID]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[HistoryItemGUID]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[WorkWeekOverrideID]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSCostingRollup2]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSCostingRollup3]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[FWIsDefined]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[PRIsDefined]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[CIIsDefined]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsPatientCare]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsBedside]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsLicensed]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[ManagementLevel]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSCostComponentID]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[SkillMix]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSJobCodeRollup1ID]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSJobCodeRollup2ID]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSJobCodeRollup3ID]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[SPHJobCodeRollupID]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[SPHJobCodeRollupIsValidated]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[TransactionID]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[SPHVariability]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[StaffingCategoryID]
   ,grpAAD69FC0ED76427EA52ED356470BFE0A.[SPHJobCodeRollupConfidenceScore]
   ,ISNULL([JobCodeGrp].[Name], 'Not Specified') as [JobCodeGroup]
   ,ISNULL([FLEXJOBCODEGROUP].[Name], 'Not Specified') as [FlexJobCodeGroup]
   ,ISNULL([DSJCROL].[Name], 'Not Specified') as [DSSCostComponent]
   ,ISNULL([DSJCROL_1].[Name], 'Not Specified') as [DSSJobCodeRollup1]
   ,ISNULL([DSSJOBCODEROLLUP2].[Name], 'Not Specified') as [DSSJobCodeRollup2]
   ,ISNULL([DSSJOBCODEROLLUP3].[Name], 'Not Specified') as [DSSJobCodeRollup3]
   ,ISNULL([SPHJOBCODEROLLUP].[Name], 'Not Specified') as [SPHJobCodeRollupName]
   ,ISNULL([SPHJOBCODEROLLUP].[SPHCostComponent], 'Not Specified') as [SPHCostComponent]
   ,ISNULL([STAFFINGCATEGORY].[Name], 'Not Specified') as [StaffingCategory]
, [grpAAD69FC0ED76427EA52ED356470BFE0A].[Version]FROM [fw].[DimJobCode] grpAAD69FC0ED76427EA52ED356470BFE0A (readuncommitted)
   LEFT JOIN [fw].[viewDimJobCodeGroup] [JobCodeGrp]  on [JobCodeGrp].[JobCodeGroupID] = [grpAAD69FC0ED76427EA52ED356470BFE0A].[JobCodeGroupID]
   LEFT JOIN [fw].[viewDimFlexJobCodeGroup] [FLEXJOBCODEGROUP]  on [FLEXJOBCODEGROUP].[FlexJobCodeGroupID] = [grpAAD69FC0ED76427EA52ED356470BFE0A].[FlexJobCodeGroupID]
   INNER JOIN [dss].[viewDimDSSJobCodeRollup1] [DSJCROL]  on [DSJCROL].[DSSJobCodeRollup1ID] = [grpAAD69FC0ED76427EA52ED356470BFE0A].[DSSCostComponentID]
   INNER JOIN [dss].[viewDimDSSJobCodeRollup1] [DSJCROL_1]  on [DSJCROL_1].[DSSJobCodeRollup1ID] = [grpAAD69FC0ED76427EA52ED356470BFE0A].[DSSJobCodeRollup1ID]
   LEFT JOIN [dss].[viewDimJobCodeRollup2] [DSSJOBCODEROLLUP2]  on [DSSJOBCODEROLLUP2].[DSSJobCodeRollup2ID] = [grpAAD69FC0ED76427EA52ED356470BFE0A].[DSSJobCodeRollup2ID]
   INNER JOIN [dss].[viewDimJobCodeRollup3] [DSSJOBCODEROLLUP3]  on [DSSJOBCODEROLLUP3].[DSSJobCodeRollup3ID] = [grpAAD69FC0ED76427EA52ED356470BFE0A].[DSSJobCodeRollup3ID]
   INNER JOIN [fw].[viewDimSPHJobCodeRollup] [SPHJOBCODEROLLUP]  on [SPHJOBCODEROLLUP].[SPHJobCodeRollupID] = [grpAAD69FC0ED76427EA52ED356470BFE0A].[SPHJobCodeRollupID]
   INNER JOIN [fw].[viewDimStaffingCategory_auto] [STAFFINGCATEGORY]  on [STAFFINGCATEGORY].[StaffingCategoryID] = [grpAAD69FC0ED76427EA52ED356470BFE0A].[StaffingCategoryID]
GO


---------------------------------------------

-- fw.viewDimJobCodeGroup
CREATE VIEW [fw].[viewDimJobCodeGroup]
AS
SELECT

[JobCodeGroupID],
[Category],
[Name],
[SPStaffType],
[SPSalariesFinancialReportingID],
[SPFTEsFinancialReportingID],
[SPDefaultVolumeDriver],
[CAPFinancialReportingID],
[IsSP],
[IsCapital],
[IsOB],
[IsMR],
[IsDSS],
[SortOrder],
 COALESCE([SPSalariesFinancialReporting],'') as [SPSalariesFinancialReporting],
 COALESCE([SPFTEsFinancialReporting],'') as [SPFTEsFinancialReporting],
 COALESCE([CAPFinancialReporting],'') as [CAPFinancialReporting],
[MemberGUID],
[WorkWeekOverrideID]    ,[HistoryItemGUID]

FROM [fw].[DimJobCodeGroup] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimJobCodeGroupPH
CREATE VIEW [fw].[viewDimJobCodeGroupPH]
AS
SELECT

[JobCodeGroupPHID],
[MemberGUID],
[Name]    ,[HistoryItemGUID]

FROM [fw].[DimJobCodeGroupPH] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimJobCodeGroupPH_source
CREATE VIEW [fw].[viewDimJobCodeGroupPH_source]
AS
SELECT
   grpDC670445EFFE4323B34B44C1C17F8B0C.[JobCodeGroupPHID]
   ,grpDC670445EFFE4323B34B44C1C17F8B0C.[MemberGUID]
, [grpDC670445EFFE4323B34B44C1C17F8B0C].[HistoryItemGUID]FROM [fw].[DimJobCodeGroupPH] grpDC670445EFFE4323B34B44C1C17F8B0C (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimJobCodeGroup_source
CREATE VIEW [fw].[viewDimJobCodeGroup_source]
AS
SELECT
   grpCC17B05111184E228AA364D935410A33.[JobCodeGroupID]
   ,grpCC17B05111184E228AA364D935410A33.[MemberGUID]
   ,ISNULL([SPFINANCIALREP].[Name], 'Not Specified') as [SPSalariesFinancialReporting]
   ,ISNULL([SPFINANCIALREP_1].[Name], 'Not Specified') as [SPFTEsFinancialReporting]
   ,ISNULL([CAPFINANCIALREP].[Name], 'Not Specified') as [CAPFinancialReporting]
, [grpCC17B05111184E228AA364D935410A33].[HistoryItemGUID]FROM [fw].[DimJobCodeGroup] grpCC17B05111184E228AA364D935410A33 (readuncommitted)
   LEFT JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP]  on [SPFINANCIALREP].[FinancialReportingID] = [grpCC17B05111184E228AA364D935410A33].[SPSalariesFinancialReportingID]
   INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP_1]  on [SPFINANCIALREP_1].[FinancialReportingID] = [grpCC17B05111184E228AA364D935410A33].[SPFTEsFinancialReportingID]
   INNER JOIN [cap].[viewDimFinancialReporting] [CAPFINANCIALREP]  on [CAPFINANCIALREP].[FinancialReportingID] = [grpCC17B05111184E228AA364D935410A33].[CAPFinancialReportingID]
GO


---------------------------------------------

-- fw.viewDimJobCodePH
CREATE VIEW [fw].[viewDimJobCodePH]
AS
SELECT
   grpB5738AC6D8C2411DAAA2747D17D10AC1.[JobCodePHID]
   ,grpB5738AC6D8C2411DAAA2747D17D10AC1.[Name]
   ,grpB5738AC6D8C2411DAAA2747D17D10AC1.[MemberGUID]
FROM [fw].[DimJobCodePH] grpB5738AC6D8C2411DAAA2747D17D10AC1 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimLineNumber
CREATE VIEW [fw].[viewDimLineNumber]
AS
SELECT
   grpFF26C92DA42548758DE9652EF433A8D7.[LineNumberID]
   ,grpFF26C92DA42548758DE9652EF433A8D7.[MemberGUID]
   ,grpFF26C92DA42548758DE9652EF433A8D7.[HistoryItemGUID]
FROM [fw].[DimLineNumber] grpFF26C92DA42548758DE9652EF433A8D7 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimManufacturer
--Last Modified 8/11/2015 12:21 PM
CREATE VIEW [fw].[viewDimManufacturer]
AS
SELECT
   grp4B506B64C5C141E3A75D30F00344E01C.[ManufacturerID]
  ,coalesce(grp4B506B64C5C141E3A75D30F00344E01C.[Name],'') as [Name]
   ,grp4B506B64C5C141E3A75D30F00344E01C.[Code]
   ,grp4B506B64C5C141E3A75D30F00344E01C.[Description]
   ,grp4B506B64C5C141E3A75D30F00344E01C.[MemberGUID]
   ,grp4B506B64C5C141E3A75D30F00344E01C.[TransactionID]
   ,grp4B506B64C5C141E3A75D30F00344E01C.[HistoryItemGUID]
FROM [fw].[DimManufacturer] grp4B506B64C5C141E3A75D30F00344E01C (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimMedicalSurgical
CREATE VIEW [fw].[viewDimMedicalSurgical]
AS
SELECT
   grp78A79D4B760C4847814C610A03087D52.[MedicalSurgicalID]
   ,grp78A79D4B760C4847814C610A03087D52.[Name]
   ,grp78A79D4B760C4847814C610A03087D52.[MemberGUID]
   ,grp78A79D4B760C4847814C610A03087D52.[HistoryItemGUID]
   ,grp78A79D4B760C4847814C610A03087D52.[TransactionID]
   ,grp78A79D4B760C4847814C610A03087D52.[Code]
   ,grp78A79D4B760C4847814C610A03087D52.[SortOrder]
FROM [fw].[DimMedicalSurgical] grp78A79D4B760C4847814C610A03087D52 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimModelingServiceLine
CREATE VIEW [fw].[viewDimModelingServiceLine]
AS
SELECT

[ModelingServiceLineID],
 COALESCE([Name],'') as [Name],
[PatientClassID],
[ServiceLineID],
[MedicalSurgicalID],
[AgeCohortID],
 COALESCE([SortOrder],'') as [SortOrder],
 COALESCE([PatientClass],'') as [PatientClass],
 COALESCE([PatientClassCode],'') as [PatientClassCode],
[PatientClassSortOrder],
 COALESCE([ServiceLine],'') as [ServiceLine],
 COALESCE([ServiceLineCode],'') as [ServiceLineCode],
[ServiceLineSortOrder],
 COALESCE([ServiceLineRollup],'') as [ServiceLineRollup],
[ServiceLineRollupSortOrder],
 COALESCE([MedicalSurgical],'') as [MedicalSurgical],
 COALESCE([MedicalSurgicalCode],'') as [MedicalSurgicalCode],
[MedicalSurgicalSortOrder],
 COALESCE([AgeCohort],'') as [AgeCohort],
 COALESCE([AgeCohortCode],'') as [AgeCohortCode],
[AgeCohortSortOrder],
[TransactionID],
[MemberGUID],
[HistoryItemGUID]
FROM [fw].[DimModelingServiceLine] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimModelingServiceLinePH
CREATE VIEW [fw].[viewDimModelingServiceLinePH]
AS
SELECT
   grp0760A281D6F040D39AF8F219869FCF1B.[ModelingServiceLinePHID]
   ,grp0760A281D6F040D39AF8F219869FCF1B.[Name]
   ,grp0760A281D6F040D39AF8F219869FCF1B.[MemberGUID]
   ,grp0760A281D6F040D39AF8F219869FCF1B.[HistoryItemGUID]
   ,grp0760A281D6F040D39AF8F219869FCF1B.[TransactionID]
FROM [fw].[DimModelingServiceLinePH] grp0760A281D6F040D39AF8F219869FCF1B (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimModelingServiceLine_source
CREATE VIEW [fw].[viewDimModelingServiceLine_source]
AS
SELECT
   grpB6F9DA58A60D41B485FFBF15F95D40EF.[ModelingServiceLineID]
   ,grpB6F9DA58A60D41B485FFBF15F95D40EF.[Name]
   ,grpB6F9DA58A60D41B485FFBF15F95D40EF.[SortOrder]
   ,grpB6F9DA58A60D41B485FFBF15F95D40EF.[TransactionID]
   ,grpB6F9DA58A60D41B485FFBF15F95D40EF.[MemberGUID]
   ,grpB6F9DA58A60D41B485FFBF15F95D40EF.[HistoryItemGUID]
   ,ISNULL([PATIENTCLASS].[Name], 'Not Specified') as [PatientClass]
   ,ISNULL([PATIENTCLASS].[Code], 'Not Specified') as [PatientClassCode]
   ,ISNULL([PATIENTCLASS].[SortOrder], 0) as [PatientClassSortOrder]
   ,ISNULL([SL].[Name], 'Not Specified') as [ServiceLine]
   ,ISNULL([SL].[Code], 'Not Specified') as [ServiceLineCode]
   ,ISNULL([SL].[SortOrder], 0) as [ServiceLineSortOrder]
   ,ISNULL([SL].[Rollup], 'Not Specified') as [ServiceLineRollup]
   ,ISNULL([SL].[RollupSortOrder], 0) as [ServiceLineRollupSortOrder]
   ,ISNULL([MEDICALSURGICAL].[Name], 'Not Specified') as [MedicalSurgical]
   ,ISNULL([MEDICALSURGICAL].[Code], 'Not Specified') as [MedicalSurgicalCode]
   ,ISNULL([MEDICALSURGICAL].[SortOrder], 0) as [MedicalSurgicalSortOrder]
   ,ISNULL([AGECOHORT].[Name], 'Not Specified') as [AgeCohort]
   ,ISNULL([AGECOHORT].[Code], 'Not Specified') as [AgeCohortCode]
   ,ISNULL([AGECOHORT].[SortOrder], 0) as [AgeCohortSortOrder]
FROM [fw].[DimModelingServiceLine] grpB6F9DA58A60D41B485FFBF15F95D40EF (readuncommitted)
   INNER JOIN [fw].[viewDimPatientClass] [PATIENTCLASS]  on [PATIENTCLASS].[PatientClassID] = [grpB6F9DA58A60D41B485FFBF15F95D40EF].[PatientClassID]
   INNER JOIN [fw].[viewDimServiceLine] [SL]  on [SL].[ServiceLineID] = [grpB6F9DA58A60D41B485FFBF15F95D40EF].[ServiceLineID]
   INNER JOIN [fw].[viewDimMedicalSurgical] [MEDICALSURGICAL]  on [MEDICALSURGICAL].[MedicalSurgicalID] = [grpB6F9DA58A60D41B485FFBF15F95D40EF].[MedicalSurgicalID]
   INNER JOIN [fw].[viewDimAgeCohort] [AGECOHORT]  on [AGECOHORT].[AgeCohortID] = [grpB6F9DA58A60D41B485FFBF15F95D40EF].[AgeCohortID]
GO


---------------------------------------------

-- fw.viewDimOpportunity
CREATE     VIEW [fw].[viewDimOpportunity]
AS
SELECT
   grpB205B5DB5DD943E7B55EB4AC84FCFF14.[OpportunityKey]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Name]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[MemberGUID]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[MemberGUID] [OpportunityGUID]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[HistoryItemGUID]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[TransactionID]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[EntityID]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[SourceOfSavingsID]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[IsHidden]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[HasInitiative]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeGUID]
   ,ISNULL([ENT].[Name], 'Not Specified') AS [Entity]
   ,ISNULL([ENT].[Code], 'Not Specified') AS [Code]
   ,ISNULL([ENT].[Description], 'Not Specified') AS [Description]
   ,ISNULL([ENT].[SortOrder], 0) AS [SortOrder]
   ,ISNULL([ENT].[EntityType], 0) AS [EntityType]
   ,ISNULL([ENT].[IsActive], 0) AS [IsActive]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[SourceOfSavings]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Initiative]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeStatus]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.Owner
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.CostLeader
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.ExecutiveSponsor
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.Workstream
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.DateCreated
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.BaselineStartDate
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.BaselineEndDate
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.SavingsIdentified
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.SavingsGoal
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.AnnualGoal
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.SavingsEstimate
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.InitiativeStatusID
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.InitiativeRollup1Id
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.InitiativeRollup1
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.InitiativeRollup2Id
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.InitiativeRollup2
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.InitiativeRollup3Id
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.InitiativeRollup3
FROM [fw].[DimOpportunity] grpB205B5DB5DD943E7B55EB4AC84FCFF14
LEFT OUTER JOIN [fw].[viewDimEntity] [ENT]  ON [ENT].[EntityID] = [grpB205B5DB5DD943E7B55EB4AC84FCFF14].[EntityID]
GO


---------------------------------------------

-- fw.viewDimOpportunity_auto
--Last Modified 6/12/2024 5:33 PM
CREATE VIEW [fw].[viewDimOpportunity_auto]
AS
SELECT
   grpB205B5DB5DD943E7B55EB4AC84FCFF14.[OpportunityKey]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Name]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[TransactionID]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[MemberGUID]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[HistoryItemGUID]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[DateCreated]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[BaselineStartDate]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[OpportunityGUID]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[AnnualGoal]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[SavingsEstimate]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeRollup1]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeRollup2]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[BaselineEndDate]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[EntityID]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[SavingsIdentified]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeRollup3]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeRollup1Id]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[SavingsGoal]
  ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Entity],'') as [Entity]
  ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Code],'') as [Code]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeRollup2Id]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeRollup3Id]
  ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Description],'') as [Description]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[SortOrder]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeStatusID]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[EntityType]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[IsActive]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[SourceOfSavingsID]
  ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[SourceOfSavings],'') as [SourceOfSavings]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[IsHidden]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[HasInitiative]
   ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeGUID]
  ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Initiative],'') as [Initiative]
  ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeStatus],'') as [InitiativeStatus]
  ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[CostLeader],'') as [CostLeader]
  ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Owner],'') as [Owner]
  ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[ExecutiveSponsor],'') as [ExecutiveSponsor]
  ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Workstream],'') as [Workstream]
FROM [fw].[viewDimOpportunity] grpB205B5DB5DD943E7B55EB4AC84FCFF14
GO


---------------------------------------------

-- fw.viewDimPatientClass
CREATE VIEW [fw].[viewDimPatientClass]
AS
SELECT
   grp30F99B15877C4FA6B62ED8D6E563E438.[PatientClassID]
   ,grp30F99B15877C4FA6B62ED8D6E563E438.[Name]
   ,grp30F99B15877C4FA6B62ED8D6E563E438.[Code]
   ,grp30F99B15877C4FA6B62ED8D6E563E438.[SortOrder]
   ,grp30F99B15877C4FA6B62ED8D6E563E438.[IsActive]
   ,grp30F99B15877C4FA6B62ED8D6E563E438.[IncludeInAdjustedCalculations]
   ,grp30F99B15877C4FA6B62ED8D6E563E438.[TransactionID]
   ,grp30F99B15877C4FA6B62ED8D6E563E438.[MemberGUID]
   ,grp30F99B15877C4FA6B62ED8D6E563E438.[OBServiceLinePrimaryVolumeAccountID]
   ,grp30F99B15877C4FA6B62ED8D6E563E438.[HistoryItemGUID]
FROM [fw].[DimPatientClass] grp30F99B15877C4FA6B62ED8D6E563E438 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPatientReimbursementGroup
CREATE VIEW [fw].[viewDimPatientReimbursementGroup]
AS
SELECT

[PatientReimbursementGroupID],
 COALESCE([Name],'') as [Name],
[PatientClassID],
[CareSettingID],
 COALESCE([Code],'') as [Code],
 COALESCE([SortOrder],'') as [SortOrder],
 COALESCE([PatientClass],'') as [PatientClass],
 COALESCE([PatientClassCode],'') as [PatientClassCode],
[PatientClassSortOrder],
 COALESCE([CareSetting],'') as [CareSetting],
 COALESCE([CareSettingCode],'') as [CareSettingCode],
[CareSettingSortOrder],
[TransactionID],
[MemberGUID],
[HistoryItemGUID]
FROM [fw].[DimPatientReimbursementGroup] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPatientReimbursementGroupPH
CREATE VIEW [fw].[viewDimPatientReimbursementGroupPH]
AS
SELECT
   grp7A426BF8FC8F4EBF8A76AA76229A06F2.[PatientReimbursementGroupPHID]
   ,grp7A426BF8FC8F4EBF8A76AA76229A06F2.[Name]
   ,grp7A426BF8FC8F4EBF8A76AA76229A06F2.[MemberGUID]
   ,grp7A426BF8FC8F4EBF8A76AA76229A06F2.[HistoryItemGUID]
   ,grp7A426BF8FC8F4EBF8A76AA76229A06F2.[TransactionID]
FROM [fw].[DimPatientReimbursementGroupPH] grp7A426BF8FC8F4EBF8A76AA76229A06F2 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPatientReimbursementGroup_source
CREATE VIEW [fw].[viewDimPatientReimbursementGroup_source]
AS
SELECT
   grp795F9572D0D04ED390051C3D7CD34946.[PatientReimbursementGroupID]
   ,grp795F9572D0D04ED390051C3D7CD34946.[Name]
   ,grp795F9572D0D04ED390051C3D7CD34946.[Code]
   ,grp795F9572D0D04ED390051C3D7CD34946.[SortOrder]
   ,grp795F9572D0D04ED390051C3D7CD34946.[TransactionID]
   ,grp795F9572D0D04ED390051C3D7CD34946.[MemberGUID]
   ,grp795F9572D0D04ED390051C3D7CD34946.[HistoryItemGUID]
   ,ISNULL([PATIENTCLASS].[Name], 'Not Specified') as [PatientClass]
   ,ISNULL([PATIENTCLASS].[Code], 'Not Specified') as [PatientClassCode]
   ,ISNULL([PATIENTCLASS].[SortOrder], 0) as [PatientClassSortOrder]
   ,ISNULL([CARESETTING].[Name], 'Not Specified') as [CareSetting]
   ,ISNULL([CARESETTING].[Code], 'Not Specified') as [CareSettingCode]
   ,ISNULL([CARESETTING].[SortOrder], 0) as [CareSettingSortOrder]
FROM [fw].[DimPatientReimbursementGroup] grp795F9572D0D04ED390051C3D7CD34946 (readuncommitted)
   LEFT JOIN [fw].[viewDimPatientClass] [PATIENTCLASS]  on [PATIENTCLASS].[PatientClassID] = [grp795F9572D0D04ED390051C3D7CD34946].[PatientClassID]
   LEFT JOIN [fw].[viewDimCareSetting] [CARESETTING]  on [CARESETTING].[CareSettingID] = [grp795F9572D0D04ED390051C3D7CD34946].[CareSettingID]
GO


---------------------------------------------

-- fw.viewDimPatientType
--Last Modified 11/16/2020 3:28 PM
CREATE VIEW [fw].[viewDimPatientType]
AS
SELECT
   grpF76658C4B97240B881CAF29A84373B98.[PatientTypeID]
  ,coalesce(grpF76658C4B97240B881CAF29A84373B98.[Name],'') as [Name]
   ,grpF76658C4B97240B881CAF29A84373B98.[Code]
   ,grpF76658C4B97240B881CAF29A84373B98.[Description]
   ,grpF76658C4B97240B881CAF29A84373B98.[PatientTypeRollupID]
   ,grpF76658C4B97240B881CAF29A84373B98.[MemberGUID]
   ,grpF76658C4B97240B881CAF29A84373B98.[HistoryItemGUID]
   ,grpF76658C4B97240B881CAF29A84373B98.[DSSRollup]
   ,grpF76658C4B97240B881CAF29A84373B98.[TransactionID]
   ,ISNULL([PatientTyRo].[Name], 'Not Specified') as [PatientTypeRollupName]
   ,ISNULL([PatientTyRo].[Sg2PatientTypeRollup], 'Not Specified') as [Sg2PatientTypeRollup]
FROM [fw].[DimPatientType] grpF76658C4B97240B881CAF29A84373B98 (readuncommitted)
   LEFT JOIN [fw].[viewDimPatientTypeRollup] [PatientTyRo]  on [PatientTyRo].[PatientTypeRollupID] = [grpF76658C4B97240B881CAF29A84373B98].[PatientTypeRollupID]
GO


---------------------------------------------

-- fw.viewDimPatientTypeRollup
CREATE VIEW [fw].[viewDimPatientTypeRollup]
AS
SELECT

[PatientTypeRollupID],
[Type],
[Name],
[PatientClassID],
[SortOrder],
[IsSP],
[CareSettingID],
[IsCapital],
[IsOB],
[IsMR],
[IsDSS],
[SPChargesFinancialReportingID],
[SPContractualsFinancialReportingID],
[SPPrimaryStatisticFinancialReportingID],
[SPSecondaryStatisticFinancialReportingID],
[SPTertiaryStatisticFinancialReportingID],
[CAPChargesFinancialReportingID],
[CAPContractualsFinancialReportingID],
[CAPPrimaryStatisticFinancialReportingID],
[CAPSecondaryStatisticFinancialReportingID],
 COALESCE([SPChargesFinancialReporting],'') as [SPChargesFinancialReporting],
 COALESCE([SPContractualsFinancialReporting],'') as [SPContractualsFinancialReporting],
 COALESCE([SPPrimaryStatisticFinancialReporting],'') as [SPPrimaryStatisticFinancialReporting],
 COALESCE([PatientClassName],'') as [PatientClassName],
 COALESCE([CareSettingName],'') as [CareSettingName],
 COALESCE([SPSecondaryStatisticFinancialReporting],'') as [SPSecondaryStatisticFinancialReporting],
 COALESCE([SPTertiaryStatisticFinancialReporting],'') as [SPTertiaryStatisticFinancialReporting],
 COALESCE([SPPrimaryStatisticFinancialReportingLineName],'') as [SPPrimaryStatisticFinancialReportingLineName],
 COALESCE([SPSecondaryStatisticFinancialReportingLineName],'') as [SPSecondaryStatisticFinancialReportingLineName],
 COALESCE([SPTertiaryStatisticFinancialReportingLineName],'') as [SPTertiaryStatisticFinancialReportingLineName],
 COALESCE([CAPChargesFinancialReporting],'') as [CAPChargesFinancialReporting],
 COALESCE([CAPContractualsFinancialReporting],'') as [CAPContractualsFinancialReporting],
 COALESCE([CAPPrimaryStatisticFinancialReporting],'') as [CAPPrimaryStatisticFinancialReporting],
 COALESCE([CAPSecondaryStatisticFinancialReporting],'') as [CAPSecondaryStatisticFinancialReporting],
[MemberGUID],
[HistoryItemGUID],
 COALESCE([CAPPrimaryStatisticFinancialReportingLineName],'') as [CAPPrimaryStatisticFinancialReportingLineName],
 COALESCE([CAPSecondaryStatisticFinancialReportingLineName],'') as [CAPSecondaryStatisticFinancialReportingLineName],
[Sg2PatientTypeRollup]    ,[Version]

FROM [fw].[DimPatientTypeRollup] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPatientTypeRollupPH
CREATE VIEW [fw].[viewDimPatientTypeRollupPH]
AS
SELECT
   grpB3573F00604F4FA28AF6435494C52F6C.[PatientTypeRollupPHID]
   ,grpB3573F00604F4FA28AF6435494C52F6C.[Name]
   ,grpB3573F00604F4FA28AF6435494C52F6C.[MemberGUID]
   ,grpB3573F00604F4FA28AF6435494C52F6C.[HistoryItemGUID]
FROM [fw].[DimPatientTypeRollupPH] grpB3573F00604F4FA28AF6435494C52F6C (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPatientTypeRollup_source
CREATE VIEW [fw].[viewDimPatientTypeRollup_source]
AS
SELECT
   grpFE81F461D5C6457B8209E3E5F86A30DB.[PatientTypeRollupID]
   ,grpFE81F461D5C6457B8209E3E5F86A30DB.[MemberGUID]
   ,grpFE81F461D5C6457B8209E3E5F86A30DB.[HistoryItemGUID]
   ,ISNULL([PATIENTCLASS].[Name], 'Not Specified') as [PatientClassName]
   ,ISNULL([CARESETTING].[Name], 'Not Specified') as [CareSettingName]
   ,ISNULL([SPFINANCIALREP].[Name], 'Not Specified') as [SPChargesFinancialReporting]
   ,ISNULL([SPFINANCIALREP_1].[Name], 'Not Specified') as [SPContractualsFinancialReporting]
   ,ISNULL([SPFINANCIALREP_2].[Name], 'Not Specified') as [SPPrimaryStatisticFinancialReporting]
   ,ISNULL([SPFINANCIALREP_2].[LineName], 'Not Specified') as [SPPrimaryStatisticFinancialReportingLineName]
   ,ISNULL([SPFINANCIALREP_3].[Name], 'Not Specified') as [SPSecondaryStatisticFinancialReporting]
   ,ISNULL([SPFINANCIALREP_3].[LineName], 'Not Specified') as [SPSecondaryStatisticFinancialReportingLineName]
   ,ISNULL([SPFINANCIALREP_4].[Name], 'Not Specified') as [SPTertiaryStatisticFinancialReporting]
   ,ISNULL([SPFINANCIALREP_4].[LineName], 'Not Specified') as [SPTertiaryStatisticFinancialReportingLineName]
   ,ISNULL([CAPFINANCIALREP].[Name], 'Not Specified') as [CAPChargesFinancialReporting]
   ,ISNULL([CAPFINANCIALREP_1].[Name], 'Not Specified') as [CAPContractualsFinancialReporting]
   ,ISNULL([CAPFINANCIALREP_2].[Name], 'Not Specified') as [CAPPrimaryStatisticFinancialReporting]
   ,ISNULL([CAPFINANCIALREP_2].[LineName], 'Not Specified') as [CAPPrimaryStatisticFinancialReportingLineName]
   ,ISNULL([CAPFINANCIALREP_3].[Name], 'Not Specified') as [CAPSecondaryStatisticFinancialReporting]
   ,ISNULL([CAPFINANCIALREP_3].[LineName], 'Not Specified') as [CAPSecondaryStatisticFinancialReportingLineName]
, [grpFE81F461D5C6457B8209E3E5F86A30DB].[Version]FROM [fw].[DimPatientTypeRollup] grpFE81F461D5C6457B8209E3E5F86A30DB (readuncommitted)
   INNER JOIN [fw].[viewDimPatientClass] [PATIENTCLASS]  on [PATIENTCLASS].[PatientClassID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[PatientClassID]
   INNER JOIN [fw].[viewDimCareSetting] [CARESETTING]  on [CARESETTING].[CareSettingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[CareSettingID]
   INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP]  on [SPFINANCIALREP].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[SPChargesFinancialReportingID]
   INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP_1]  on [SPFINANCIALREP_1].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[SPContractualsFinancialReportingID]
   INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP_2]  on [SPFINANCIALREP_2].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[SPPrimaryStatisticFinancialReportingID]
   INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP_3]  on [SPFINANCIALREP_3].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[SPSecondaryStatisticFinancialReportingID]
   INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP_4]  on [SPFINANCIALREP_4].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[SPTertiaryStatisticFinancialReportingID]
   INNER JOIN [cap].[viewDimFinancialReporting] [CAPFINANCIALREP]  on [CAPFINANCIALREP].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[CAPChargesFinancialReportingID]
   INNER JOIN [cap].[viewDimFinancialReporting] [CAPFINANCIALREP_1]  on [CAPFINANCIALREP_1].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[CAPContractualsFinancialReportingID]
   INNER JOIN [cap].[viewDimFinancialReporting] [CAPFINANCIALREP_2]  on [CAPFINANCIALREP_2].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[CAPPrimaryStatisticFinancialReportingID]
   INNER JOIN [cap].[viewDimFinancialReporting] [CAPFINANCIALREP_3]  on [CAPFINANCIALREP_3].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[CAPSecondaryStatisticFinancialReportingID]
GO


---------------------------------------------

-- fw.viewDimPayCode
CREATE VIEW [fw].[viewDimPayCode]
AS
SELECT

[PayCodeID],
 COALESCE([Name],'') as [Name],
[Description],
[PayCode],
[PayCodeGroupID],
[IsAccrued],
[IsHoursIgnored],
[IsDollarsIgnored],
[DSSIsDefined],
[DSSPayCodeRollup1ID],
[DSSCostingRollup],
 COALESCE([DSSPayCodeRollup1],'') as [DSSPayCodeRollup1],
[OBIsDefined],
[OBForecastDetailID],
[SPIsDefined],
[ImportIDAlt],
[IsPayCodeGroup],
[Rollup],
[SubRollup],
 COALESCE([PayCodeGroup],'') as [PayCodeGroup],
[PayCodeGroupSortOrder],
 COALESCE([PayClass],'') as [PayClass],
 COALESCE([ProductiveClass],'') as [ProductiveClass],
[Variability],
 COALESCE([ReportingCategory],'') as [ReportingCategory],
[MemberGUID],
[HistoryItemGUID],
[DSSCostingRollup2],
[FWIsDefined],
[DSSPayCodeRollup2ID],
 COALESCE([DSSPayCodeRollup2],'') as [DSSPayCodeRollup2],
[TransactionID],
[SPHPayCodeRollupIsValidated],
[ProviderLineItemID],
 COALESCE([ProviderLineItem],'') as [ProviderLineItem],
 COALESCE([SPHProductiveClass],'') as [SPHProductiveClass],
[SPHPayCodeRollupID],
 COALESCE([SPHPayCodeRollupName],'') as [SPHPayCodeRollupName],
[SPHPayCodeRollupConfidenceScore]    ,[Version]

FROM [fw].[DimPayCode] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPayCodeGroup
--Last Modified 3/20/2024 5:05 PM
CREATE VIEW [fw].[viewDimPayCodeGroup]
AS
SELECT
   grpB9F3A1C540C14A449028ADA57350A79D.[PayCodeGroupID]
   ,grpB9F3A1C540C14A449028ADA57350A79D.[Name]
   ,grpB9F3A1C540C14A449028ADA57350A79D.[SortOrder]
   ,grpB9F3A1C540C14A449028ADA57350A79D.[PayCodeGroupCode]
   ,grpB9F3A1C540C14A449028ADA57350A79D.[PayClass]
   ,grpB9F3A1C540C14A449028ADA57350A79D.[ProductiveClassID]
   ,grpB9F3A1C540C14A449028ADA57350A79D.[IsVariable]
   ,grpB9F3A1C540C14A449028ADA57350A79D.[IsOvertime]
   ,grpB9F3A1C540C14A449028ADA57350A79D.[IsAgency]
   ,grpB9F3A1C540C14A449028ADA57350A79D.[IsExcludedFromBenefits]
   ,grpB9F3A1C540C14A449028ADA57350A79D.[IsDirect]
   ,grpB9F3A1C540C14A449028ADA57350A79D.[IsPremium]
   ,grpB9F3A1C540C14A449028ADA57350A79D.[WageRateMultiplier]
   ,grpB9F3A1C540C14A449028ADA57350A79D.[DefaultPayCodeID]
   ,grpB9F3A1C540C14A449028ADA57350A79D.[ReportingCategory]
   ,grpB9F3A1C540C14A449028ADA57350A79D.[MemberGUID]
   ,grpB9F3A1C540C14A449028ADA57350A79D.[TransactionID]
   ,grpB9F3A1C540C14A449028ADA57350A79D.[HistoryItemGUID]
   ,ISNULL([PRODUCTIVECL].[Name], 'Not Specified') as [ProductiveClass]
   ,ISNULL([PAYCODE].[Name], 'Not Specified') as [DefaultPayCode]
, [grpB9F3A1C540C14A449028ADA57350A79D].[Version]FROM [fw].[DimPayCodeGroup] grpB9F3A1C540C14A449028ADA57350A79D (readuncommitted)
   LEFT JOIN [fw].[viewDimProductiveClass] [PRODUCTIVECL]  on [PRODUCTIVECL].[ProductiveClassID] = [grpB9F3A1C540C14A449028ADA57350A79D].[ProductiveClassID]
   LEFT JOIN [fw].[viewDimPayCode] [PAYCODE]  on [PAYCODE].[PayCodeID] = [grpB9F3A1C540C14A449028ADA57350A79D].[DefaultPayCodeID]
GO


---------------------------------------------

-- fw.viewDimPayCodeGroupPH
CREATE VIEW [fw].[viewDimPayCodeGroupPH]
AS
SELECT
   grpCAA5DF4BE5434757B51AD811109F16DB.[PayCodeGroupPHID]
   ,grpCAA5DF4BE5434757B51AD811109F16DB.[Name]
   ,grpCAA5DF4BE5434757B51AD811109F16DB.[TransactionID]
   ,grpCAA5DF4BE5434757B51AD811109F16DB.[MemberGUID]
   ,grpCAA5DF4BE5434757B51AD811109F16DB.[HistoryItemGUID]
FROM [fw].[DimPayCodeGroupPH] grpCAA5DF4BE5434757B51AD811109F16DB (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPayCode_source
CREATE VIEW [fw].[viewDimPayCode_source]
AS
SELECT
   grpB323F295F71F4248991D24C571ED8831.[PayCodeID]
   ,grpB323F295F71F4248991D24C571ED8831.[Name]
   ,grpB323F295F71F4248991D24C571ED8831.[MemberGUID]
   ,grpB323F295F71F4248991D24C571ED8831.[HistoryItemGUID]
   ,grpB323F295F71F4248991D24C571ED8831.[TransactionID]
   ,ISNULL([PCG].[Name], 'Not Specified') as [PayCodeGroup]
   ,ISNULL([PCG].[SortOrder], 0) as [PayCodeGroupSortOrder]
   ,ISNULL([PCG].[PayClass], 'Not Specified') as [PayClass]
   ,ISNULL([PCG].[ProductiveClass], 'Not Specified') as [ProductiveClass]
   ,ISNULL([PCG].[ReportingCategory], 'Not Specified') as [ReportingCategory]
   ,ISNULL([DSSPAYCODEROLLUP1].[Name], 'Not Specified') as [DSSPayCodeRollup1]
   ,ISNULL([DSSPAYCODEROLLUP2].[Name], 'Not Specified') as [DSSPayCodeRollup2]
   ,ISNULL([PROVIDERLI].[Description], 'Not Specified') as [ProviderLineItem]
   ,ISNULL([SPHPAYCODEROLLUP].[SPHProductiveClass], 'Not Specified') as [SPHProductiveClass]
   ,ISNULL([SPHPAYCODEROLLUP].[Name], 'Not Specified') as [SPHPayCodeRollupName]
, [grpB323F295F71F4248991D24C571ED8831].[Version]FROM [fw].[DimPayCode] grpB323F295F71F4248991D24C571ED8831 (readuncommitted)
   LEFT JOIN [fw].[viewDimPayCodeGroup] [PCG]  on [PCG].[PayCodeGroupID] = [grpB323F295F71F4248991D24C571ED8831].[PayCodeGroupID]
   INNER JOIN [dss].[viewDimPayCodeRollup1] [DSSPAYCODEROLLUP1]  on [DSSPAYCODEROLLUP1].[DSSPayCodeRollup1ID] = [grpB323F295F71F4248991D24C571ED8831].[DSSPayCodeRollup1ID]
   INNER JOIN [dss].[viewDimPayCodeRollup2] [DSSPAYCODEROLLUP2]  on [DSSPAYCODEROLLUP2].[DSSPayCodeRollup2ID] = [grpB323F295F71F4248991D24C571ED8831].[DSSPayCodeRollup2ID]
   LEFT JOIN [fp].[viewProviderLineItem_auto] [PROVIDERLI]  on [PROVIDERLI].[ProviderLineItemID] = [grpB323F295F71F4248991D24C571ED8831].[ProviderLineItemID]
   INNER JOIN [fw].[viewDimSPHPayCodeRollup] [SPHPAYCODEROLLUP]  on [SPHPAYCODEROLLUP].[SPHPayCodeRollupID] = [grpB323F295F71F4248991D24C571ED8831].[SPHPayCodeRollupID]
GO


---------------------------------------------

-- fw.viewDimPayCycle
--Last Modified 11/30/2015 12:22 PM
CREATE VIEW [fw].[viewDimPayCycle]
AS
SELECT
   grp97FA080700B74428A51EDA0423536FBB.[PayCycleID]
   ,grp97FA080700B74428A51EDA0423536FBB.[Name]
   ,grp97FA080700B74428A51EDA0423536FBB.[Code]
   ,grp97FA080700B74428A51EDA0423536FBB.[SortOrder]
   ,grp97FA080700B74428A51EDA0423536FBB.[PeriodDays]
   ,grp97FA080700B74428A51EDA0423536FBB.[FirstPayPeriodStartDate]
   ,grp97FA080700B74428A51EDA0423536FBB.[AccrualMethod]
   ,grp97FA080700B74428A51EDA0423536FBB.[TransactionID]
   ,grp97FA080700B74428A51EDA0423536FBB.[MemberGUID]
   ,grp97FA080700B74428A51EDA0423536FBB.[HistoryItemGUID]
   ,grp97FA080700B74428A51EDA0423536FBB.[CurrentPayPeriodID]
FROM [fw].[DimPayCycle] grp97FA080700B74428A51EDA0423536FBB (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPayPeriod
CREATE VIEW [fw].[viewDimPayPeriod]
AS
SELECT

[PayPeriodID],
[Name],
[PeriodNumber],
[Code],
[PayPeriodCode],
[FiscalYearIDStart],
[FiscalYearIDSecond],
[PeriodStartCalendarDate],
[PeriodEndCalendarDate],
[PeriodDays],
[WorkingDays],
[FiscalMonthIDStart],
[FiscalMonthIDSecond],
[CalendarDaysStart],
[CalendarDaysSecond],
[PeriodDaysStart],
[PeriodDaysSecond],
[PeriodWeightStart],
[PeriodWeightSecond],
[DaysInPeriodWeightStart],
[DaysInPeriodWeightSecond],
[HistoryItemGUID],
[PayCycleID],
 COALESCE([PayCycleName],'') as [PayCycleName],
[MemberGUID],
[TransactionID],
 COALESCE([PayCycleCode],'') as [PayCycleCode],
[PayCycleSortOrder],
 COALESCE([AccrualMethod],'') as [AccrualMethod],
[IsCurrentPayPeriod],
[CountFromCurrentPayPeriod]    ,[Version]

FROM [fw].[DimPayPeriod] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPayPeriod_source
CREATE VIEW [fw].[viewDimPayPeriod_source]
AS
SELECT
   grp90F54C2D43B54BE39642E686F8DE7839.[PayPeriodID]
   ,grp90F54C2D43B54BE39642E686F8DE7839.[PeriodStartCalendarDate]
   ,grp90F54C2D43B54BE39642E686F8DE7839.[FiscalMonthIDStart]
   ,grp90F54C2D43B54BE39642E686F8DE7839.[FiscalMonthIDSecond]
   ,grp90F54C2D43B54BE39642E686F8DE7839.[CalendarDaysStart]
   ,grp90F54C2D43B54BE39642E686F8DE7839.[CalendarDaysSecond]
   ,grp90F54C2D43B54BE39642E686F8DE7839.[PeriodDaysStart]
   ,grp90F54C2D43B54BE39642E686F8DE7839.[PeriodDaysSecond]
   ,grp90F54C2D43B54BE39642E686F8DE7839.[PeriodWeightStart]
   ,grp90F54C2D43B54BE39642E686F8DE7839.[PeriodWeightSecond]
   ,grp90F54C2D43B54BE39642E686F8DE7839.[DaysInPeriodWeightStart]
   ,grp90F54C2D43B54BE39642E686F8DE7839.[DaysInPeriodWeightSecond]
   ,grp90F54C2D43B54BE39642E686F8DE7839.[HistoryItemGUID]
   ,grp90F54C2D43B54BE39642E686F8DE7839.[MemberGUID]
   ,grp90F54C2D43B54BE39642E686F8DE7839.[TransactionID]
   ,ISNULL([PAYCYCLE].[Name], 'Not Specified') as [PayCycleName]
   ,ISNULL([PAYCYCLE].[Code], 'Not Specified') as [PayCycleCode]
   ,ISNULL([PAYCYCLE].[SortOrder], 0) as [PayCycleSortOrder]
   ,ISNULL([PAYCYCLE].[AccrualMethod], 'Not Specified') as [AccrualMethod]
, [grp90F54C2D43B54BE39642E686F8DE7839].[Version]FROM [fw].[DimPayPeriod] grp90F54C2D43B54BE39642E686F8DE7839 (readuncommitted)
   INNER JOIN [fw].[viewDimPayCycle] [PAYCYCLE]  on [PAYCYCLE].[PayCycleID] = [grp90F54C2D43B54BE39642E686F8DE7839].[PayCycleID]
GO


---------------------------------------------

-- fw.viewDimPayor
--Last Modified 6/8/2020 3:13 PM
CREATE VIEW [fw].[viewDimPayor]
AS
SELECT
   grp0887B09C7E9342638431A42A05EA03B5.[PayorID]
  ,coalesce(grp0887B09C7E9342638431A42A05EA03B5.[Name],'') as [Name]
   ,grp0887B09C7E9342638431A42A05EA03B5.[Description]
   ,grp0887B09C7E9342638431A42A05EA03B5.[DescriptionLong]
   ,grp0887B09C7E9342638431A42A05EA03B5.[PayorCode]
   ,grp0887B09C7E9342638431A42A05EA03B5.[PayorGroupID]
   ,grp0887B09C7E9342638431A42A05EA03B5.[IsOB]
   ,grp0887B09C7E9342638431A42A05EA03B5.[IsDSS]
   ,grp0887B09C7E9342638431A42A05EA03B5.[FinancialClassID]
   ,grp0887B09C7E9342638431A42A05EA03B5.[OBDefaultInpatientReimbursementMethod]
   ,grp0887B09C7E9342638431A42A05EA03B5.[OBDefaultOutpatientReimbursementMethod]
   ,grp0887B09C7E9342638431A42A05EA03B5.[MemberGUID]
   ,grp0887B09C7E9342638431A42A05EA03B5.[HistoryItemGUID]
   ,grp0887B09C7E9342638431A42A05EA03B5.[TransactionID]
   ,ISNULL([PayorGroup].[Name], 'Not Specified') as [PayorGroup]
   ,ISNULL([FINANCIALCLASS].[Name], 'Not Specified') as [FinancialClass]
FROM [fw].[DimPayor] grp0887B09C7E9342638431A42A05EA03B5 (readuncommitted)
   LEFT JOIN [fw].[viewDimPayorGroup] [PayorGroup]  on [PayorGroup].[PayorGroupID] = [grp0887B09C7E9342638431A42A05EA03B5].[PayorGroupID]
   LEFT JOIN [clientdss].[viewDimFinancialClass] [FINANCIALCLASS]  on [FINANCIALCLASS].[FinancialClassID] = [grp0887B09C7E9342638431A42A05EA03B5].[FinancialClassID]
GO


---------------------------------------------

-- fw.viewDimPayorGroup
CREATE VIEW [fw].[viewDimPayorGroup]
AS
SELECT

[PayorGroupID],
[Name],
[Category],
[ReimbursementType],
[PayorGroupCode],
[SortOrder],
[IsCapital],
[CAPChargesFinancialReportingID],
[CAPContractualsFinancialReportingID],
[IsDSS],
[IsOB],
[IsMR],
[IsSP],
[SPHCRPayorID],
[SPChargesFinancialReportingID],
[SPContractualsFinancialReportingID],
[SPDefaultInpatientReimbursementMethod],
[SPDefaultOutpatientReimbursementMethod],
[SPDefaultClinicReimbursementMethod],
[OBDefaultInpatientReimbursementMethod],
 COALESCE([CAPChargesFinancialReporting],'') as [CAPChargesFinancialReporting],
 COALESCE([CAPContractualsFinancialReporting],'') as [CAPContractualsFinancialReporting],
[OBDefaultOutpatientReimbursementMethod],
 COALESCE([SPHCRPayor],'') as [SPHCRPayor],
 COALESCE([SPChargesFinancialReporting],'') as [SPChargesFinancialReporting],
 COALESCE([SPContractualsFinancialReporting],'') as [SPContractualsFinancialReporting],
[SPCMISamplingSourceType],
[SPCMISamplingAccountID],
[MemberGUID]    ,[HistoryItemGUID]

FROM [fw].[DimPayorGroup] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPayorGroupPH
CREATE VIEW [fw].[viewDimPayorGroupPH]
AS
SELECT

[PayorGroupPHID],
[MemberGUID],
[Name]    ,[HistoryItemGUID]

FROM [fw].[DimPayorGroupPH] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPayorGroupPH_source
CREATE VIEW [fw].[viewDimPayorGroupPH_source]
AS
SELECT
   grp4D76CDC6FB8D4D8FB7B95C7CD71A1E5A.[PayorGroupPHID]
   ,grp4D76CDC6FB8D4D8FB7B95C7CD71A1E5A.[MemberGUID]
, [grp4D76CDC6FB8D4D8FB7B95C7CD71A1E5A].[HistoryItemGUID]FROM [fw].[DimPayorGroupPH] grp4D76CDC6FB8D4D8FB7B95C7CD71A1E5A (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPayorGroup_source
CREATE VIEW [fw].[viewDimPayorGroup_source]
AS
SELECT
   grpEF15CAACBD154F79B68A2D4655C8489C.[PayorGroupID]
   ,grpEF15CAACBD154F79B68A2D4655C8489C.[SPCMISamplingSourceType]
   ,grpEF15CAACBD154F79B68A2D4655C8489C.[SPCMISamplingAccountID]
   ,grpEF15CAACBD154F79B68A2D4655C8489C.[MemberGUID]
   ,ISNULL([CAPFINANCIALREP].[Name], 'Not Specified') as [CAPChargesFinancialReporting]
   ,ISNULL([CAPFINANCIALREP_1].[Name], 'Not Specified') as [CAPContractualsFinancialReporting]
   ,ISNULL([SPHCRPAYOR].[Name], 'Not Specified') as [SPHCRPayor]
   ,ISNULL([SPFINANCIALREP].[Name], 'Not Specified') as [SPChargesFinancialReporting]
   ,ISNULL([SPFINANCIALREP_1].[Name], 'Not Specified') as [SPContractualsFinancialReporting]
, [grpEF15CAACBD154F79B68A2D4655C8489C].[HistoryItemGUID]FROM [fw].[DimPayorGroup] grpEF15CAACBD154F79B68A2D4655C8489C (readuncommitted)
   INNER JOIN [cap].[viewDimFinancialReporting] [CAPFINANCIALREP]  on [CAPFINANCIALREP].[FinancialReportingID] = [grpEF15CAACBD154F79B68A2D4655C8489C].[CAPChargesFinancialReportingID]
   INNER JOIN [cap].[viewDimFinancialReporting] [CAPFINANCIALREP_1]  on [CAPFINANCIALREP_1].[FinancialReportingID] = [grpEF15CAACBD154F79B68A2D4655C8489C].[CAPContractualsFinancialReportingID]
   INNER JOIN [sp].[viewDimHCRPayor] [SPHCRPAYOR]  on [SPHCRPAYOR].[SPHCRPayorID] = [grpEF15CAACBD154F79B68A2D4655C8489C].[SPHCRPayorID]
   INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP]  on [SPFINANCIALREP].[FinancialReportingID] = [grpEF15CAACBD154F79B68A2D4655C8489C].[SPChargesFinancialReportingID]
   INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP_1]  on [SPFINANCIALREP_1].[FinancialReportingID] = [grpEF15CAACBD154F79B68A2D4655C8489C].[SPContractualsFinancialReportingID]
GO


---------------------------------------------

-- fw.viewDimPayorPH
CREATE VIEW [fw].[viewDimPayorPH]
AS
SELECT
   grpF3B83E94F08649FDBDD59852FB8C7C47.[PayorPHID]
   ,grpF3B83E94F08649FDBDD59852FB8C7C47.[Name]
   ,grpF3B83E94F08649FDBDD59852FB8C7C47.[MemberGUID]
FROM [fw].[DimPayorPH] grpF3B83E94F08649FDBDD59852FB8C7C47 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPhysicianGroup
CREATE VIEW [fw].[viewDimPhysicianGroup]
AS
SELECT

[PhysicianGroupID],
[Category],
[Subcategory],
[Name],
[PhysicianType],
[IsSP],
[IsCapital],
[IsOB],
[IsMR],
[IsDSS],
[SortOrder],
[SPSalariesFinancialReportingID],
[SPFTEsFinancialReportingID],
 COALESCE([SPSalariesFinancialReporting],'') as [SPSalariesFinancialReporting],
[SPSalariesVolumeDriverID],
[SPPhysicianBenefitsTypeID],
 COALESCE([SPFTEsFinancialReporting],'') as [SPFTEsFinancialReporting],
 COALESCE([SPSalariesVolumeDriver],'') as [SPSalariesVolumeDriver],
 COALESCE([SPPhysicianBenefitsType],'') as [SPPhysicianBenefitsType],
[MemberGUID],
[HistoryItemGUID],
[WorkWeekOverrideID]    ,[Version]

FROM [fw].[DimPhysicianGroup] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPhysicianGroupPH
CREATE VIEW [fw].[viewDimPhysicianGroupPH]
AS
SELECT

[PhysicianGroupPHID],
[Name],
[MemberGUID],
[HistoryItemGUID]    ,[Version]

FROM [fw].[DimPhysicianGroupPH] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPhysicianGroupPH_source
CREATE VIEW [fw].[viewDimPhysicianGroupPH_source]
AS
SELECT
   grpFA7033208877495E84B853F8157A91A4.[PhysicianGroupPHID]
   ,grpFA7033208877495E84B853F8157A91A4.[MemberGUID]
   ,grpFA7033208877495E84B853F8157A91A4.[HistoryItemGUID]
, [grpFA7033208877495E84B853F8157A91A4].[Version]FROM [fw].[DimPhysicianGroupPH] grpFA7033208877495E84B853F8157A91A4 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPhysicianGroup_source
CREATE VIEW [fw].[viewDimPhysicianGroup_source]
AS
SELECT
   grpF4583D1A174C47B999BA61480A7A4378.[PhysicianGroupID]
   ,grpF4583D1A174C47B999BA61480A7A4378.[MemberGUID]
   ,grpF4583D1A174C47B999BA61480A7A4378.[HistoryItemGUID]
   ,ISNULL([SPFINANCIALREP].[Name], 'Not Specified') as [SPSalariesFinancialReporting]
   ,ISNULL([SPFINANCIALREP_1].[Name], 'Not Specified') as [SPFTEsFinancialReporting]
   ,ISNULL([SPAccountRollup].[Name], 'Not Specified') as [SPSalariesVolumeDriver]
   ,ISNULL([SPAccountRollup_1].[Name], 'Not Specified') as [SPPhysicianBenefitsType]
, [grpF4583D1A174C47B999BA61480A7A4378].[Version]FROM [fw].[DimPhysicianGroup] grpF4583D1A174C47B999BA61480A7A4378 (readuncommitted)
   INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP]  on [SPFINANCIALREP].[FinancialReportingID] = [grpF4583D1A174C47B999BA61480A7A4378].[SPSalariesFinancialReportingID]
   INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP_1]  on [SPFINANCIALREP_1].[FinancialReportingID] = [grpF4583D1A174C47B999BA61480A7A4378].[SPFTEsFinancialReportingID]
   INNER JOIN [sp].[viewDimAccountRollup] [SPAccountRollup]  on [SPAccountRollup].[AccountRollupID] = [grpF4583D1A174C47B999BA61480A7A4378].[SPSalariesVolumeDriverID]
   INNER JOIN [sp].[viewDimAccountRollup] [SPAccountRollup_1]  on [SPAccountRollup_1].[AccountRollupID] = [grpF4583D1A174C47B999BA61480A7A4378].[SPPhysicianBenefitsTypeID]
GO


---------------------------------------------

-- fw.viewDimPhysicianPH
CREATE VIEW [fw].[viewDimPhysicianPH]
AS
SELECT
   grp085BA6AC2CB14AD4A83D611E7B1646B1.[PhysicianPHID]
   ,grp085BA6AC2CB14AD4A83D611E7B1646B1.[Name]
   ,grp085BA6AC2CB14AD4A83D611E7B1646B1.[MemberGUID]
   ,grp085BA6AC2CB14AD4A83D611E7B1646B1.[HistoryItemGUID]
   ,grp085BA6AC2CB14AD4A83D611E7B1646B1.[TransactionID]
FROM [fw].[DimPhysicianPH] grp085BA6AC2CB14AD4A83D611E7B1646B1 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPhysicianSpecialty
CREATE VIEW [fw].[viewDimPhysicianSpecialty]
AS
SELECT
   grp3091D7E63A5F4E09B9439680761F9990.[PhysicianSpecialtyID]
  ,coalesce(grp3091D7E63A5F4E09B9439680761F9990.[Name],'') as [Name]
   ,grp3091D7E63A5F4E09B9439680761F9990.[TransactionID]
   ,grp3091D7E63A5F4E09B9439680761F9990.[MemberGUID]
   ,grp3091D7E63A5F4E09B9439680761F9990.[HistoryItemGUID]
   ,grp3091D7E63A5F4E09B9439680761F9990.[PhysicianSpecialtyCode]
   ,grp3091D7E63A5F4E09B9439680761F9990.[SpecialtyGroup]
   ,grp3091D7E63A5F4E09B9439680761F9990.[Description]
   ,grp3091D7E63A5F4E09B9439680761F9990.[RVUTarget]
FROM [fw].[DimPhysicianSpecialty] grp3091D7E63A5F4E09B9439680761F9990 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimPositionType
--Last Modified 11/8/2024 12:46 AM
CREATE VIEW [fw].[viewDimPositionType]
AS
SELECT
   grp69B5488AB512468F8B9002077835B307.[PositionTypeID]
   ,grp69B5488AB512468F8B9002077835B307.[Name]
   ,grp69B5488AB512468F8B9002077835B307.[TransactionID]
   ,grp69B5488AB512468F8B9002077835B307.[MemberGUID]
   ,grp69B5488AB512468F8B9002077835B307.[HistoryItemGUID]
   ,grp69B5488AB512468F8B9002077835B307.[PositionTypeAssignmentTypeID]
   ,ISNULL([POSITIONTYPEASSIGNMENTTYPE].[Name], 'Not Specified') as [PositionTypeAssignmentType]
FROM [fw].[DimPositionType] grp69B5488AB512468F8B9002077835B307 (readuncommitted)
   INNER JOIN [fw].[viewDimPositionTypeAssignmentType] [POSITIONTYPEASSIGNMENTTYPE]  on [POSITIONTYPEASSIGNMENTTYPE].[PositionTypeAssignmentTypeID] = [grp69B5488AB512468F8B9002077835B307].[PositionTypeAssignmentTypeID]
GO


---------------------------------------------

-- fw.viewDimPositionTypeAssignmentType
--Last Modified 11/8/2024 12:46 AM
CREATE VIEW [fw].[viewDimPositionTypeAssignmentType]
AS
SELECT
   grp34DC76DCBD1B4EB7BB814C769354A3F5.[PositionTypeAssignmentTypeID]
   ,grp34DC76DCBD1B4EB7BB814C769354A3F5.[Name]
   ,grp34DC76DCBD1B4EB7BB814C769354A3F5.[TransactionID]
   ,grp34DC76DCBD1B4EB7BB814C769354A3F5.[MemberGUID]
   ,grp34DC76DCBD1B4EB7BB814C769354A3F5.[HistoryItemGUID]
FROM [fw].[DimPositionTypeAssignmentType] grp34DC76DCBD1B4EB7BB814C769354A3F5 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimProductiveClass
CREATE VIEW [fw].[viewDimProductiveClass]
AS
SELECT
   grp6EF32EA816124EEF8860ED7A89141304.[ProductiveClassID]
   ,grp6EF32EA816124EEF8860ED7A89141304.[Name]
   ,grp6EF32EA816124EEF8860ED7A89141304.[MemberGUID]
   ,grp6EF32EA816124EEF8860ED7A89141304.[HistoryItemGUID]
FROM [fw].[DimProductiveClass] grp6EF32EA816124EEF8860ED7A89141304 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimProgram
--Last Modified 5/26/2015 10:11 AM
CREATE VIEW [fw].[viewDimProgram]
AS
SELECT
   grp7D067B54714C46E1927FF61AE552BEA9.[ProgramID]
  ,coalesce(grp7D067B54714C46E1927FF61AE552BEA9.[Name],'') as [Name]
   ,grp7D067B54714C46E1927FF61AE552BEA9.[Code]
   ,grp7D067B54714C46E1927FF61AE552BEA9.[Description]
   ,grp7D067B54714C46E1927FF61AE552BEA9.[SortOrder]
   ,grp7D067B54714C46E1927FF61AE552BEA9.[TransactionID]
   ,grp7D067B54714C46E1927FF61AE552BEA9.[MemberGUID]
   ,grp7D067B54714C46E1927FF61AE552BEA9.[HistoryItemGUID]
FROM [fw].[DimProgram] grp7D067B54714C46E1927FF61AE552BEA9 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimProject
--Last Modified 5/26/2015 10:11 AM
CREATE VIEW [fw].[viewDimProject]
AS
SELECT
   grp2CF09BEF8FF548EB995FA62246911542.[ProjectID]
  ,coalesce(grp2CF09BEF8FF548EB995FA62246911542.[Name],'') as [Name]
   ,grp2CF09BEF8FF548EB995FA62246911542.[Code]
   ,grp2CF09BEF8FF548EB995FA62246911542.[Description]
   ,grp2CF09BEF8FF548EB995FA62246911542.[SortOrder]
   ,grp2CF09BEF8FF548EB995FA62246911542.[TransactionID]
   ,grp2CF09BEF8FF548EB995FA62246911542.[MemberGUID]
   ,grp2CF09BEF8FF548EB995FA62246911542.[HistoryItemGUID]
FROM [fw].[DimProject] grp2CF09BEF8FF548EB995FA62246911542 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimProvider
--Last Modified 9/4/2018 7:30 PM
CREATE VIEW [fw].[viewDimProvider]
AS
SELECT
   grp1D2F3A2E50034A10A3B63D4C0CC69235.[ProviderID]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[Type]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[NameFirst]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[IsPhysician]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[NameLast]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[ProviderCode]
  ,coalesce(grp1D2F3A2E50034A10A3B63D4C0CC69235.[Name],'') as [Name]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[PhysicianSpecialtyID]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[StateLicenseNumber]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[NPI]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[GroupAffiliaition]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[DSSIsDefined]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBIsDefined]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[IsEmployee]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBIsActive]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier1Rate]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier2Rate]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier3Rate]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier4Rate]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier5Rate]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier6Rate]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier1Threshold]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier2Threshold]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier3Threshold]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier4Threshold]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier5Threshold]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier6Threshold]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBVolumeTarget1]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBVolumeTarget2]
  ,coalesce(grp1D2F3A2E50034A10A3B63D4C0CC69235.[ProviderName],'') as [ProviderName]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[PayRate]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBVolumeTarget3]
  ,coalesce(grp1D2F3A2E50034A10A3B63D4C0CC69235.[CompensationMethod],'') as [CompensationMethod]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[BasePay]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[TransactionID]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[MemberGUID]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[HistoryItemGUID]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[WorkWeekOverrideID]
   ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[IsVariable]
   ,ISNULL([PHYSICIANSPECIALTY].[Name], 'Not Specified') as [Specialty]
FROM [fw].[DimProvider] grp1D2F3A2E50034A10A3B63D4C0CC69235 (readuncommitted)
   LEFT JOIN [fw].[viewDimPhysicianSpecialty] [PHYSICIANSPECIALTY]  on [PHYSICIANSPECIALTY].[PhysicianSpecialtyID] = [grp1D2F3A2E50034A10A3B63D4C0CC69235].[PhysicianSpecialtyID]
GO


---------------------------------------------

-- fw.viewDimProviderPH
CREATE VIEW [fw].[viewDimProviderPH]
AS
SELECT
   grp085BA6AC2CB14AD4A83D611E7B1646B1.[ProviderPHID]
   ,grp085BA6AC2CB14AD4A83D611E7B1646B1.[Name]
   ,grp085BA6AC2CB14AD4A83D611E7B1646B1.[TransactionID]
   ,grp085BA6AC2CB14AD4A83D611E7B1646B1.[MemberGUID]
   ,grp085BA6AC2CB14AD4A83D611E7B1646B1.[HistoryItemGUID]
FROM [fw].[DimProviderPH] grp085BA6AC2CB14AD4A83D611E7B1646B1 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimQuarter_auto
CREATE VIEW [fw].[viewDimQuarter_auto]
AS
SELECT
   grp3CBAB808CE024FFBB6B5C2F2E6B7EC5E.[Name]
   ,grp3CBAB808CE024FFBB6B5C2F2E6B7EC5E.[MemberGUID]
   ,grp3CBAB808CE024FFBB6B5C2F2E6B7EC5E.[QuarterID]
, [grp3CBAB808CE024FFBB6B5C2F2E6B7EC5E].[Version], [grp3CBAB808CE024FFBB6B5C2F2E6B7EC5E].[HistoryItemGUID]FROM [fw].[DimQuarter] grp3CBAB808CE024FFBB6B5C2F2E6B7EC5E (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimReportDetailType
CREATE VIEW [fw].[viewDimReportDetailType]
AS
SELECT
   grp280082C30690409ABF34E0DC53FEDC09.[ReportDetailTypeID]
   ,grp280082C30690409ABF34E0DC53FEDC09.[Name]
   ,grp280082C30690409ABF34E0DC53FEDC09.[TransactionID]
   ,grp280082C30690409ABF34E0DC53FEDC09.[MemberGUID]
   ,grp280082C30690409ABF34E0DC53FEDC09.[HistoryItemGUID]
   ,grp280082C30690409ABF34E0DC53FEDC09.[TableName]
FROM [fw].[DimReportDetailType] grp280082C30690409ABF34E0DC53FEDC09 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimResearchDepartmentCategory
CREATE VIEW [fw].[viewDimResearchDepartmentCategory]
AS
SELECT
   grpE9D662D6B156456CBA91AE99CF2DF414.[ResearchDepartmentCategoryID]
   ,grpE9D662D6B156456CBA91AE99CF2DF414.[Name]
   ,grpE9D662D6B156456CBA91AE99CF2DF414.[SortOrder]
   ,grpE9D662D6B156456CBA91AE99CF2DF414.[TransactionID]
   ,grpE9D662D6B156456CBA91AE99CF2DF414.[MemberGUID]
   ,grpE9D662D6B156456CBA91AE99CF2DF414.[HistoryItemGUID]
FROM [fw].[DimResearchDepartmentCategory] grpE9D662D6B156456CBA91AE99CF2DF414 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimRowNumber
CREATE VIEW [fw].[viewDimRowNumber]
AS
SELECT
   grpCEA161A7FFE24D2B90F4491D4C324B8D.[RowNumberID]
   ,grpCEA161A7FFE24D2B90F4491D4C324B8D.[Name]
   ,grpCEA161A7FFE24D2B90F4491D4C324B8D.[MemberGUID]
   ,grpCEA161A7FFE24D2B90F4491D4C324B8D.[HistoryItemGUID]
FROM [fw].[DimRowNumber] grpCEA161A7FFE24D2B90F4491D4C324B8D (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimSPHAccountRollup
--Last Modified 3/15/2022 10:09 PM
CREATE VIEW [fw].[viewDimSPHAccountRollup]
AS
SELECT
   grp0FB965B53015438FA55B5196CD9FEEC1.[SPHAccountRollupID]
  ,coalesce(grp0FB965B53015438FA55B5196CD9FEEC1.[Name],'') as [Name]
   ,grp0FB965B53015438FA55B5196CD9FEEC1.[TransactionID]
   ,grp0FB965B53015438FA55B5196CD9FEEC1.[MemberGUID]
   ,grp0FB965B53015438FA55B5196CD9FEEC1.[HistoryItemGUID]
   ,grp0FB965B53015438FA55B5196CD9FEEC1.[Statement]
   ,grp0FB965B53015438FA55B5196CD9FEEC1.[Category]
   ,grp0FB965B53015438FA55B5196CD9FEEC1.[LineItem]
   ,grp0FB965B53015438FA55B5196CD9FEEC1.[Section]
   ,grp0FB965B53015438FA55B5196CD9FEEC1.[SortOrder]
   ,grp0FB965B53015438FA55B5196CD9FEEC1.[IsStandard]
   ,grp0FB965B53015438FA55B5196CD9FEEC1.[SPHCostComponent]
   ,grp0FB965B53015438FA55B5196CD9FEEC1.[SPHCostComponentRollup]
   ,grp0FB965B53015438FA55B5196CD9FEEC1.[SPHAccountRollupCode]
FROM [fw].[DimSPHAccountRollup] grp0FB965B53015438FA55B5196CD9FEEC1 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimSPHDepartmentRollup
--Last Modified 11/16/2020 3:28 PM
CREATE VIEW [fw].[viewDimSPHDepartmentRollup]
AS
SELECT
   grp5181C574309B42B29625F6AA66F56763.[SPHDepartmentRollupID]
   ,grp5181C574309B42B29625F6AA66F56763.[TransactionID]
  ,coalesce(grp5181C574309B42B29625F6AA66F56763.[Name],'') as [Name]
   ,grp5181C574309B42B29625F6AA66F56763.[MemberGUID]
   ,grp5181C574309B42B29625F6AA66F56763.[HistoryItemGUID]
   ,grp5181C574309B42B29625F6AA66F56763.[SPHDepartmentRollupCode]
   ,grp5181C574309B42B29625F6AA66F56763.[SortOrder]
   ,grp5181C574309B42B29625F6AA66F56763.[IsStandard]
FROM [fw].[DimSPHDepartmentRollup] grp5181C574309B42B29625F6AA66F56763 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimSPHDepartmentType_auto
--Last Modified 11/16/2020 3:28 PM
CREATE VIEW [fw].[viewDimSPHDepartmentType_auto]
AS
SELECT
   grp0A011FEFFE0943ACA25C28B87AF8BB5E.[SPHDepartmentTypeID]
   ,grp0A011FEFFE0943ACA25C28B87AF8BB5E.[Name]
   ,grp0A011FEFFE0943ACA25C28B87AF8BB5E.[TransactionID]
   ,grp0A011FEFFE0943ACA25C28B87AF8BB5E.[MemberGUID]
   ,grp0A011FEFFE0943ACA25C28B87AF8BB5E.[HistoryItemGUID]
   ,grp0A011FEFFE0943ACA25C28B87AF8BB5E.[SPHDepartmentTypeCode]
   ,grp0A011FEFFE0943ACA25C28B87AF8BB5E.[IsStandard]
FROM [fw].[DimSPHDepartmentType] grp0A011FEFFE0943ACA25C28B87AF8BB5E (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimSPHDepartment_auto
--Last Modified 4/5/2024 9:49 AM
CREATE VIEW [fw].[viewDimSPHDepartment_auto]
AS
SELECT
   grpBA529E3553234961A9B03E2BB2DE62D6.[SPHDepartmentID]
   ,grpBA529E3553234961A9B03E2BB2DE62D6.[Name]
   ,grpBA529E3553234961A9B03E2BB2DE62D6.[SPHDepartmentRollup]
   ,grpBA529E3553234961A9B03E2BB2DE62D6.[TransactionID]
   ,grpBA529E3553234961A9B03E2BB2DE62D6.[MemberGUID]
   ,grpBA529E3553234961A9B03E2BB2DE62D6.[HistoryItemGUID]
   ,grpBA529E3553234961A9B03E2BB2DE62D6.[SPHDepartmentCode]
FROM [fw].[DimSPHDepartment] grpBA529E3553234961A9B03E2BB2DE62D6 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimSPHJobCodeRollup
--Last Modified 12/15/2020 2:06 PM
CREATE VIEW [fw].[viewDimSPHJobCodeRollup]
AS
SELECT
   grpCC5829E5D6334D34958CCF8057B6E850.[SPHJobCodeRollupID]
   ,grpCC5829E5D6334D34958CCF8057B6E850.[Name]
   ,grpCC5829E5D6334D34958CCF8057B6E850.[TransactionID]
   ,grpCC5829E5D6334D34958CCF8057B6E850.[MemberGUID]
   ,grpCC5829E5D6334D34958CCF8057B6E850.[HistoryItemGUID]
   ,grpCC5829E5D6334D34958CCF8057B6E850.[SPHJobCodeRollupCode]
   ,grpCC5829E5D6334D34958CCF8057B6E850.[SPHCostComponent]
   ,grpCC5829E5D6334D34958CCF8057B6E850.[SortOrder]
   ,grpCC5829E5D6334D34958CCF8057B6E850.[IsStandard]
FROM [fw].[DimSPHJobCodeRollup] grpCC5829E5D6334D34958CCF8057B6E850 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimSPHPayCodeRollup
--Last Modified 02/17/2022 3:49 PM
CREATE VIEW [fw].[viewDimSPHPayCodeRollup]
AS
SELECT
   grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[SPHPayCodeRollupID]
   ,grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[Name]
   ,grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[TransactionID]
   ,grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[MemberGUID]
   ,grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[HistoryItemGUID]
  ,coalesce(grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[SPHProductiveClass],'') as [SPHProductiveClass]
   ,grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[SortOrder]
   ,grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[IsStandard]
   ,grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[SPHPayCodeRollupCode]
FROM [fw].[DimSPHPayCodeRollup] grpCD15C19FF64B4AE6B4AEF15FE3E938C8 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimSecureGroup
CREATE VIEW [fw].[viewDimSecureGroup]
AS
SELECT
   grpCD7483929A80421EB8FCB5F08DA13707.[SecureGroupID]
   ,grpCD7483929A80421EB8FCB5F08DA13707.[Name]
   ,grpCD7483929A80421EB8FCB5F08DA13707.[MemberGUID]
   ,grpCD7483929A80421EB8FCB5F08DA13707.[HistoryItemGUID]
FROM [fw].[DimSecureGroup] grpCD7483929A80421EB8FCB5F08DA13707 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimServiceLine
CREATE VIEW [fw].[viewDimServiceLine]
AS
SELECT

[ServiceLineID],
 COALESCE([Name],'') as [Name],
[RollupID],
[ProductLine],
[Code],
[SortOrder],
 COALESCE([Rollup],'') as [Rollup],
[RollupSortOrder],
[MemberGUID],
[HistoryItemGUID]
FROM [fw].[DimServiceLine] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimServiceLine2_auto
--Last Modified 8/1/2016 9:45 AM
CREATE VIEW [fw].[viewDimServiceLine2_auto]
AS
SELECT
   grp49B904B3B0B047D8BE592BFC9B8A8AB5.[ServiceLine2ID]
   ,grp49B904B3B0B047D8BE592BFC9B8A8AB5.[Name]
   ,grp49B904B3B0B047D8BE592BFC9B8A8AB5.[MemberGUID]
   ,grp49B904B3B0B047D8BE592BFC9B8A8AB5.[HistoryItemGUID]
   ,grp49B904B3B0B047D8BE592BFC9B8A8AB5.[PatientTypeID]
   ,grp49B904B3B0B047D8BE592BFC9B8A8AB5.[Rollup]
   ,grp49B904B3B0B047D8BE592BFC9B8A8AB5.[Rollup2]
   ,grp49B904B3B0B047D8BE592BFC9B8A8AB5.[SortOrder]
FROM [fw].[DimServiceLine2] grp49B904B3B0B047D8BE592BFC9B8A8AB5 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimServiceLine3_auto
--Last Modified 8/1/2016 9:45 AM
CREATE VIEW [fw].[viewDimServiceLine3_auto]
AS
SELECT
   grp5974196196F64FC9A4F8AA9FACBDCD45.[ServiceLine3ID]
   ,grp5974196196F64FC9A4F8AA9FACBDCD45.[Name]
   ,grp5974196196F64FC9A4F8AA9FACBDCD45.[MemberGUID]
   ,grp5974196196F64FC9A4F8AA9FACBDCD45.[HistoryItemGUID]
   ,grp5974196196F64FC9A4F8AA9FACBDCD45.[PatientTypeID]
   ,grp5974196196F64FC9A4F8AA9FACBDCD45.[Rollup]
   ,grp5974196196F64FC9A4F8AA9FACBDCD45.[SortOrder]
FROM [fw].[DimServiceLine3] grp5974196196F64FC9A4F8AA9FACBDCD45 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimServiceLine4_auto
--Last Modified 8/1/2016 9:45 AM
CREATE VIEW [fw].[viewDimServiceLine4_auto]
AS
SELECT
   grp569AFAF6B05343CD97F0CAAF28DC8F00.[ServiceLine4ID]
   ,grp569AFAF6B05343CD97F0CAAF28DC8F00.[Name]
   ,grp569AFAF6B05343CD97F0CAAF28DC8F00.[MemberGUID]
   ,grp569AFAF6B05343CD97F0CAAF28DC8F00.[HistoryItemGUID]
   ,grp569AFAF6B05343CD97F0CAAF28DC8F00.[PatientTypeID]
   ,grp569AFAF6B05343CD97F0CAAF28DC8F00.[Rollup]
   ,grp569AFAF6B05343CD97F0CAAF28DC8F00.[SortOrder]
   ,grp569AFAF6B05343CD97F0CAAF28DC8F00.[Rollup2]
FROM [fw].[DimServiceLine4] grp569AFAF6B05343CD97F0CAAF28DC8F00 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimServiceLine5_auto
--Last Modified 8/1/2016 9:45 AM
CREATE VIEW [fw].[viewDimServiceLine5_auto]
AS
SELECT
   grpC0586B9CF59342389C2043964523F713.[ServiceLine5ID]
   ,grpC0586B9CF59342389C2043964523F713.[Name]
   ,grpC0586B9CF59342389C2043964523F713.[MemberGUID]
   ,grpC0586B9CF59342389C2043964523F713.[HistoryItemGUID]
   ,grpC0586B9CF59342389C2043964523F713.[PatientTypeID]
   ,grpC0586B9CF59342389C2043964523F713.[Rollup]
   ,grpC0586B9CF59342389C2043964523F713.[SortOrder]
FROM [fw].[DimServiceLine5] grpC0586B9CF59342389C2043964523F713 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimServiceLine6_auto
--Last Modified 8/1/2016 9:45 AM
CREATE VIEW [fw].[viewDimServiceLine6_auto]
AS
SELECT
   grpFAE2AC4E1DB34075B2113A9624D8EBDA.[ServiceLine6ID]
   ,grpFAE2AC4E1DB34075B2113A9624D8EBDA.[Name]
   ,grpFAE2AC4E1DB34075B2113A9624D8EBDA.[MemberGUID]
   ,grpFAE2AC4E1DB34075B2113A9624D8EBDA.[HistoryItemGUID]
   ,grpFAE2AC4E1DB34075B2113A9624D8EBDA.[PatientTypeID]
   ,grpFAE2AC4E1DB34075B2113A9624D8EBDA.[Rollup]
   ,grpFAE2AC4E1DB34075B2113A9624D8EBDA.[SortOrder]
FROM [fw].[DimServiceLine6] grpFAE2AC4E1DB34075B2113A9624D8EBDA (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimServiceLineRollup
CREATE VIEW [fw].[viewDimServiceLineRollup]
AS
SELECT
   grp634CA27B835D4A18B1E58F8992F1B031.[ServiceLineRollupID]
   ,grp634CA27B835D4A18B1E58F8992F1B031.[Name]
   ,grp634CA27B835D4A18B1E58F8992F1B031.[MemberGUID]
   ,grp634CA27B835D4A18B1E58F8992F1B031.[HistoryItemGUID]
   ,grp634CA27B835D4A18B1E58F8992F1B031.[TransactionID]
   ,grp634CA27B835D4A18B1E58F8992F1B031.[SortOrder]
FROM [fw].[DimServiceLineRollup] grp634CA27B835D4A18B1E58F8992F1B031 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimServiceLineRollupPH
CREATE VIEW [fw].[viewDimServiceLineRollupPH]
AS
SELECT
   grp6617B9B078794F479D91C0708CEED4F0.[ServiceLineRollupPHID]
   ,grp6617B9B078794F479D91C0708CEED4F0.[Name]
   ,grp6617B9B078794F479D91C0708CEED4F0.[MemberGUID]
   ,grp6617B9B078794F479D91C0708CEED4F0.[HistoryItemGUID]
   ,grp6617B9B078794F479D91C0708CEED4F0.[TransactionID]
FROM [fw].[DimServiceLineRollupPH] grp6617B9B078794F479D91C0708CEED4F0 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimServiceLine_source
CREATE VIEW [fw].[viewDimServiceLine_source]
AS
SELECT
   grpB9907EAC036D4FC5BFF43432DC038E7A.[ServiceLineID]
   ,grpB9907EAC036D4FC5BFF43432DC038E7A.[Name]
   ,grpB9907EAC036D4FC5BFF43432DC038E7A.[MemberGUID]
   ,grpB9907EAC036D4FC5BFF43432DC038E7A.[HistoryItemGUID]
   ,ISNULL([SERVICELINEROLLUP].[Name], 'Not Specified') as [Rollup]
   ,ISNULL([SERVICELINEROLLUP].[SortOrder], 0) as [RollupSortOrder]
FROM [fw].[DimServiceLine] grpB9907EAC036D4FC5BFF43432DC038E7A (readuncommitted)
   LEFT JOIN [fw].[viewDimServiceLineRollup] [SERVICELINEROLLUP]  on [SERVICELINEROLLUP].[ServiceLineRollupID] = [grpB9907EAC036D4FC5BFF43432DC038E7A].[RollupID]
GO


---------------------------------------------

-- fw.viewDimSourceOfSavings
--Last Modified 10/31/2018 9:48 AM
CREATE VIEW [fw].[viewDimSourceOfSavings]
AS
SELECT
   grp91260CC7FCE64FEE96459705BF43D6CB.[SourceOfSavingsID]
   ,grp91260CC7FCE64FEE96459705BF43D6CB.[Name]
   ,grp91260CC7FCE64FEE96459705BF43D6CB.[MemberGUID]
   ,grp91260CC7FCE64FEE96459705BF43D6CB.[HistoryItemGUID]
   ,grp91260CC7FCE64FEE96459705BF43D6CB.[TransactionID]
FROM [fw].[DimSourceOfSavings] grp91260CC7FCE64FEE96459705BF43D6CB (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimStaffingCategory_auto
--Last Modified 3/27/2023 4:41 PM
CREATE VIEW [fw].[viewDimStaffingCategory_auto]
AS
SELECT
   grp14EBA885F7334C2AA07343FD9886CAF6.[StaffingCategoryID]
  ,coalesce(grp14EBA885F7334C2AA07343FD9886CAF6.[Name],'') as [Name]
   ,grp14EBA885F7334C2AA07343FD9886CAF6.[TransactionID]
   ,grp14EBA885F7334C2AA07343FD9886CAF6.[MemberGUID]
   ,grp14EBA885F7334C2AA07343FD9886CAF6.[HistoryItemGUID]
   ,grp14EBA885F7334C2AA07343FD9886CAF6.[StaffingCategoryCode]
   ,grp14EBA885F7334C2AA07343FD9886CAF6.[Description]
FROM [fw].[DimStaffingCategory] grp14EBA885F7334C2AA07343FD9886CAF6 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimStrataDecisionServiceLine
--Last Modified 6/3/2015 4:41 PM
CREATE VIEW [fw].[viewDimStrataDecisionServiceLine]
AS
SELECT
   grp44649CCD9FB74ECF80BB88D6C5033A8C.[StrataDecisionServiceLineID]
   ,grp44649CCD9FB74ECF80BB88D6C5033A8C.[Name]
   ,grp44649CCD9FB74ECF80BB88D6C5033A8C.[TransactionID]
   ,grp44649CCD9FB74ECF80BB88D6C5033A8C.[MemberGUID]
   ,grp44649CCD9FB74ECF80BB88D6C5033A8C.[HistoryItemGUID]
   ,grp44649CCD9FB74ECF80BB88D6C5033A8C.[PatientTypeID]
FROM [fw].[DimStrataDecisionServiceLine] grp44649CCD9FB74ECF80BB88D6C5033A8C (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimSystem
CREATE VIEW [fw].[viewDimSystem]
AS
SELECT

[SystemID],
 COALESCE([Name],'') as [Name],
[Code],
[Description],
[SortOrder],
[SecureGroupID],
[TransactionID],
[HistoryItemGUID],
[MemberGUID],
[EliminationsDepartmentID]
FROM [fw].[DimSystem] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimSystemSection
create view [fw].[viewDimSystemSection]
	as
	select
		SS.SYSTEMSECTIONGUID as MemberGUID,
		SS.Name,
		SS.ImageName,
		coalesce(nullif(replace(replace(replace(substring(replace(SS.FullPath, 'SYSTEM\', ''), 1, patindex('%\%', replace(SS.FullPath, 'SYSTEM\', ''))), '\', ''), 'TOOLBAR_', ''), 'MENU_', ''), ''), 'System') as Area,
		coalesce(nullif(replace(substring(replace(SS.FullPath, 'SYSTEM\', ''), 1, patindex('%\%', replace(SS.FullPath, 'SYSTEM\', ''))), '\', ''), ''), 'System') as Section,
		coalesce(nullif(replace(replace(replace(substring(replace(SS.FullPath, 'SYSTEM\', ''), 1, patindex('%\%', replace(SS.FullPath, 'SYSTEM\', ''))), '\', ''), 'TOOLBAR_', ''), 'MENU_', ''), ''), 'System') 
		+ ' - ' +
		coalesce(nullif(replace(substring(replace(SS.FullPath, 'SYSTEM\', ''), 1, patindex('%\%', replace(SS.FullPath, 'SYSTEM\', ''))), '\', ''), ''), 'System') 
		+ ' - ' + SS.Name as [FullName],
		SS.ID,
		SS.LootID,
		coalesce(PSS.Name, 'System') as Parent,
		coalesce(PSS.LootID, '1F30ED4A-DFA5-4EA6-8457-20D23DB372C3') as ParentLootID,
		cast(0 as bit) as IsDeleted,
		dbo.ZeroGUID() as HistoryItemGUID
	from SystemSection SS
	left join SystemSection PSS on PSS.SystemSectionGUID = SS.ParentGUID
	--inner join S3Loot L on L.LootID = SS.LootID
	--inner join S3PermissionSet PS on PS.PermissionSetID = L.PermissionSetID  --why do we do this? AJK
	--where PS.Name like '%System%'
GO


---------------------------------------------

-- fw.viewDimSystem_source
CREATE VIEW [fw].[viewDimSystem_source]
AS
SELECT
   grpF27719422C1141E2BDF4C0F24660B263.[SystemID]
   ,grpF27719422C1141E2BDF4C0F24660B263.[Name]
   ,grpF27719422C1141E2BDF4C0F24660B263.[SecureGroupID]
   ,grpF27719422C1141E2BDF4C0F24660B263.[TransactionID]
   ,grpF27719422C1141E2BDF4C0F24660B263.[HistoryItemGUID]
   ,grpF27719422C1141E2BDF4C0F24660B263.[MemberGUID]
FROM [fw].[DimSystem] grpF27719422C1141E2BDF4C0F24660B263 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimTimeClass
CREATE VIEW [fw].[viewDimTimeClass]
AS
SELECT
   grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[MemberGUID]
   ,grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[TimeClassID]
   ,grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[Name]
   ,grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[TimeClassCode]
   ,grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[GlobalID]
   ,grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[IsSP]
   ,grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[SPIsISForecast]
   ,grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[HistoryItemGUID]
   ,grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[SortOrder]
, [grp5A23BD5828DE40AC868EBCB6F1CE3FF8].[Version]FROM [fw].[DimTimeClass] grp5A23BD5828DE40AC868EBCB6F1CE3FF8 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimTimeClassPH
CREATE VIEW [fw].[viewDimTimeClassPH]
AS
SELECT

[TimeClassPHID],
[Name],
[MemberGUID]
FROM [fw].[DimTimeClassPH] (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimTimeClassPH_source
CREATE VIEW [fw].[viewDimTimeClassPH_source]
AS
SELECT
   grp1132ACA8D57B494890AE52DD6857E83B.[TimeClassPHID]
   ,grp1132ACA8D57B494890AE52DD6857E83B.[MemberGUID]
FROM [fw].[DimTimeClassPH] grp1132ACA8D57B494890AE52DD6857E83B (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimTime_auto
--Last Modified 1/8/2019 1:37 PM
CREATE VIEW [fw].[viewDimTime_auto]
AS
SELECT
   grp35B3D1A6EEAC4E0CA47893B67CD0FD99.[TimeID]
   ,grp35B3D1A6EEAC4E0CA47893B67CD0FD99.[TransactionID]
  ,coalesce(grp35B3D1A6EEAC4E0CA47893B67CD0FD99.[Name],'') as [Name]
   ,grp35B3D1A6EEAC4E0CA47893B67CD0FD99.[Hour]
   ,grp35B3D1A6EEAC4E0CA47893B67CD0FD99.[Minute]
   ,grp35B3D1A6EEAC4E0CA47893B67CD0FD99.[MemberGUID]
   ,grp35B3D1A6EEAC4E0CA47893B67CD0FD99.[StandardTime]
   ,grp35B3D1A6EEAC4E0CA47893B67CD0FD99.[HistoryItemGUID]
, [grp35B3D1A6EEAC4E0CA47893B67CD0FD99].[Version]FROM [fw].[DimTime] grp35B3D1A6EEAC4E0CA47893B67CD0FD99 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimUnitType
CREATE VIEW [fw].[viewDimUnitType]
AS
SELECT
   grp7B1AFC84DBD346F9A5E90839ADF09065.[UnitTypeID]
   ,grp7B1AFC84DBD346F9A5E90839ADF09065.[Name]
   ,grp7B1AFC84DBD346F9A5E90839ADF09065.[GlobalID]
   ,grp7B1AFC84DBD346F9A5E90839ADF09065.[DisplayFormat]
   ,grp7B1AFC84DBD346F9A5E90839ADF09065.[SPDisplayFormat]
   ,grp7B1AFC84DBD346F9A5E90839ADF09065.[CapitalDisplayFormat]
   ,grp7B1AFC84DBD346F9A5E90839ADF09065.[MemberGUID]
   ,grp7B1AFC84DBD346F9A5E90839ADF09065.[HistoryItemGUID]
, [grp7B1AFC84DBD346F9A5E90839ADF09065].[Version]FROM [fw].[DimUnitType] grp7B1AFC84DBD346F9A5E90839ADF09065 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimUnit_auto
--Last Modified 10/22/2020 5:41 PM
CREATE VIEW [fw].[viewDimUnit_auto]
AS
SELECT
   grpB9BA9ECBC1214A079F252B81ED4DFE6F.[Name]
   ,grpB9BA9ECBC1214A079F252B81ED4DFE6F.[Abbreviation]
   ,grpB9BA9ECBC1214A079F252B81ED4DFE6F.[MemberGUID]
   ,grpB9BA9ECBC1214A079F252B81ED4DFE6F.[UnitID]
   ,grpB9BA9ECBC1214A079F252B81ED4DFE6F.[SortOrder]
   ,grpB9BA9ECBC1214A079F252B81ED4DFE6F.[IsActive]
, [grpB9BA9ECBC1214A079F252B81ED4DFE6F].[Version], [grpB9BA9ECBC1214A079F252B81ED4DFE6F].[HistoryItemGUID]FROM [fw].[DimUnit] grpB9BA9ECBC1214A079F252B81ED4DFE6F (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimUserProfile
CREATE view [fw].[viewDimUserProfile]
	as
	select 
		up.UserGUID as MemberGUID,
		up.UserGUID,
		up.UserName,
		up.NameFull,
		ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) AS IsSysAdmin,
		CAST (0 as bit) as IsDeleted,
		dbo.ZeroGUID() as HistoryItemGUID,
		CAST(UserGUID as varchar(36)) as LootID
	from UserProfile up
	left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator')
	where up.IsDisabled = 0
GO


---------------------------------------------

-- fw.viewDimUserRole
CREATE VIEW [fw].[viewDimUserRole]
AS
SELECT
   grp35E4A606568B4382851EBD0183D9C8CF.[Description]
   ,grp35E4A606568B4382851EBD0183D9C8CF.[Type]
   ,grp35E4A606568B4382851EBD0183D9C8CF.[Category]
   ,grp35E4A606568B4382851EBD0183D9C8CF.[RoleID]
   ,grp35E4A606568B4382851EBD0183D9C8CF.[Name]
   ,grp35E4A606568B4382851EBD0183D9C8CF.[MemberGUID]
   ,grp35E4A606568B4382851EBD0183D9C8CF.[HistoryItemGUID]
FROM [fw].[viewDimUserRoleInfo] grp35E4A606568B4382851EBD0183D9C8CF
GO


---------------------------------------------

-- fw.viewDimUserRoleInfo
create view fw.viewDimUserRoleInfo
as
	select
		UserRoleGUID as MemberGUID,
		RoleID,
		Name,
		Description,
		Type,
		Category,
		dbo.ZeroGUID() as HistoryItemGUID
	from 
		[dbo].[UserRole] with (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimUsers
CREATE view fw.viewDimUsers
AS
select
	UP.UserGUID as [MemberGUID],
	UP.UserGUID as [UserGUID],
	UP.UserName,
	UP.NameFirst,
	UP.NameLast,
	UP.NameFull,
	UP.EmailAddress,
	UP.PhoneNumber,
	ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) AS IsSysAdmin
from dbo.UserProfile UP
left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator')
GO


---------------------------------------------

-- fw.viewDimUsers_auto
CREATE VIEW [fw].[viewDimUsers_auto]
AS
SELECT
   grp1F25D2EFD624418E8482FEAB7BAE4841.[MemberGUID]
  ,coalesce(grp1F25D2EFD624418E8482FEAB7BAE4841.[UserName],'') as [UserName]
  ,coalesce(grp1F25D2EFD624418E8482FEAB7BAE4841.[NameFirst],'') as [NameFirst]
  ,coalesce(grp1F25D2EFD624418E8482FEAB7BAE4841.[NameLast],'') as [NameLast]
  ,coalesce(grp1F25D2EFD624418E8482FEAB7BAE4841.[EmailAddress],'') as [EmailAddress]
  ,coalesce(grp1F25D2EFD624418E8482FEAB7BAE4841.[PhoneNumber],'') as [PhoneNumber]
   ,grp1F25D2EFD624418E8482FEAB7BAE4841.[IsSysAdmin]
  ,coalesce(grp1F25D2EFD624418E8482FEAB7BAE4841.[NameFull],'') as [NameFull]
   ,grp1F25D2EFD624418E8482FEAB7BAE4841.[UserGUID]
FROM [fw].[viewDimUsers] grp1F25D2EFD624418E8482FEAB7BAE4841
GO


---------------------------------------------

-- fw.viewDimVariability
--Last Modified 12/9/2016 2:10 PM
CREATE VIEW [fw].[viewDimVariability]
AS
SELECT
   grp093B96C5E7324756BDD0329EB4A55B43.[VariabilityID]
   ,grp093B96C5E7324756BDD0329EB4A55B43.[Name]
   ,grp093B96C5E7324756BDD0329EB4A55B43.[TransactionID]
   ,grp093B96C5E7324756BDD0329EB4A55B43.[MemberGUID]
   ,grp093B96C5E7324756BDD0329EB4A55B43.[HistoryItemGUID]
FROM [fw].[DimVariability] grp093B96C5E7324756BDD0329EB4A55B43 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimVendor
CREATE VIEW [fw].[viewDimVendor] 
AS
	SELECT 
		VendorCode AS [VendorCode]
		,MemberGUID
		,VendorID AS [VendorID]
		,Name
		,VendorRollup
		,VendorDescription
		,IsActive
	FROM [cap].[DimVendor];
GO


---------------------------------------------

-- fw.viewDimVendor_auto
--Last Modified 7/18/2017 3:21 PM
CREATE VIEW [fw].[viewDimVendor_auto]
AS
SELECT
   grpA3C8AA18CD8446948E36DB868059BC19.[VendorCode]
   ,grpA3C8AA18CD8446948E36DB868059BC19.[MemberGUID]
   ,grpA3C8AA18CD8446948E36DB868059BC19.[VendorID]
  ,coalesce(grpA3C8AA18CD8446948E36DB868059BC19.[VendorRollup],'') as [VendorRollup]
   ,grpA3C8AA18CD8446948E36DB868059BC19.[VendorDescription]
   ,grpA3C8AA18CD8446948E36DB868059BC19.[IsActive]
   ,[grpA3C8AA18CD8446948E36DB868059BC19].[VendorCode] + ' - ' + [grpA3C8AA18CD8446948E36DB868059BC19].[VendorDescription] AS [Name]
FROM [fw].[viewDimVendor] grpA3C8AA18CD8446948E36DB868059BC19
GO


---------------------------------------------

-- fw.viewDimWorkWeek
--Last Modified 3/3/2015 10:40 AM
CREATE VIEW [fw].[viewDimWorkWeek]
AS
SELECT
   grpFDAFCE80DC5344DA9680D20E7596BC98.[MemberGUID]
   ,grpFDAFCE80DC5344DA9680D20E7596BC98.[WorkWeekID]
   ,grpFDAFCE80DC5344DA9680D20E7596BC98.[Name]
   ,grpFDAFCE80DC5344DA9680D20E7596BC98.[WorkWeekCode]
   ,grpFDAFCE80DC5344DA9680D20E7596BC98.[Type]
   ,grpFDAFCE80DC5344DA9680D20E7596BC98.[TransactionID]
   ,grpFDAFCE80DC5344DA9680D20E7596BC98.[HistoryItemGUID]
   ,grpFDAFCE80DC5344DA9680D20E7596BC98.[SortOrder]
FROM [fw].[DimWorkWeek] grpFDAFCE80DC5344DA9680D20E7596BC98 (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimWorkWeekPH
CREATE VIEW [fw].[viewDimWorkWeekPH]
AS
SELECT
   grp5B25135186E54281B07A9C0128CEBF9E.[MemberGUID]
   ,grp5B25135186E54281B07A9C0128CEBF9E.[WorkWeekPHID]
   ,grp5B25135186E54281B07A9C0128CEBF9E.[Name]
   ,grp5B25135186E54281B07A9C0128CEBF9E.[TransactionID]
   ,grp5B25135186E54281B07A9C0128CEBF9E.[HistoryItemGUID]
FROM [fw].[DimWorkWeekPH] grp5B25135186E54281B07A9C0128CEBF9E (readuncommitted)
GO


---------------------------------------------

-- fw.viewDimXPlan
CREATE view [fw].[viewDimXPlan]
as
	select
		P.PlanGUID as MemberGUID,
		ISNULL(case when P.IsDeletedPlan = 1 then 'DELETED ' + P.Name else P.Name end,'') as Name,
		P.PlanID,
		P.CachedLootID,
		P.IsDeletedPlan as IsDeleted,
		P.PlanTypeGUID,
		PT.Name as PlanTypeName
	from
		XPlan P (readuncommitted)
		inner join PlanType	PT (readuncommitted) on PT.PlanTypeGUID = P.PlanTypeGUID
GO


---------------------------------------------

-- fw.viewDimXPlan_auto
CREATE VIEW [fw].[viewDimXPlan_auto]
AS
SELECT
   grpF444702419784B9EB154D1C4369A77C8.[MemberGUID]
  ,coalesce(grpF444702419784B9EB154D1C4369A77C8.[Name],'') as [Name]
   ,grpF444702419784B9EB154D1C4369A77C8.[PlanID]
  ,coalesce(grpF444702419784B9EB154D1C4369A77C8.[CachedLootID],'') as [CachedLootID]
   ,grpF444702419784B9EB154D1C4369A77C8.[PlanTypeGUID]
   ,grpF444702419784B9EB154D1C4369A77C8.[PlanTypeName]
   ,grpF444702419784B9EB154D1C4369A77C8.[IsDeleted]
FROM [fw].[viewDimXPlan] grpF444702419784B9EB154D1C4369A77C8
GO


---------------------------------------------

-- fw.viewEliminationsDepartment
create view fw.viewEliminationsDepartment
as
	select 
		d.DepartmentID,
		d.Name 
	from 
		fw.viewDimDepartment d
	where
		d.DepartmentID != 0
		and (
			exists(select 1 from fw.DimSystem s where s.EliminationsDepartmentID = d.DepartmentID)
			or exists(select 1 from fw.DimEntity e where e.EliminationsDepartmentID = d.DepartmentID)
			or exists(select 1 from fw.DimDepartmentRollup1 r1 where r1.EliminationsDepartmentID = d.DepartmentID)
			or exists(select 1 from fw.DimDepartmentRollup2 r2 where r2.EliminationsDepartmentID = d.DepartmentID)
			or exists(select 1 from fw.DimDepartmentRollup3 r3 where r3.EliminationsDepartmentID = d.DepartmentID)
			or exists(select 1 from fw.DimDepartmentRollup4 r4 where r4.EliminationsDepartmentID = d.DepartmentID)
			or exists(select 1 from fw.DimDepartmentRollup5 r5 where r5.EliminationsDepartmentID = d.DepartmentID)
			or exists(select 1 from fw.DimDepartmentRollup6 r6 where r6.EliminationsDepartmentID = d.DepartmentID)
		)
GO


---------------------------------------------

-- fw.viewFactGLSampled
CREATE view [fw].[viewFactGLSampled] as 
select
	fact.DepartmentID,
	dept.DepartmentCode,
	fact.AccountID,
	acc.AccountCode,
	accrollup.LineName as AccountRollup,
	accrollup.Section as AccountCategory,
	accrollup.Name as FinancialReporting,
	fact.TimeClassID,
	tc.TimeClassCode,
	fact.FiscalYearID,
	fy.Name,
	fact.FiscalMonthID,
	fm.FiscalMonthCode,
	fm.SortOrder as FiscalMonthSortOrder,
	Dollars,
	DollarsYTD,
	DollarsPriorYear,
	DollarsPriorYTD,
	Units,
	UnitsYTD,
	UnitsPriorYear,
	UnitsPriorYTD

from 
	fw.FactGLSampled fact 
	left join fw.DimDepartment dept on dept.DepartmentID=fact.DepartmentID
	left join fw.DimAccount acc on acc.AccountID=fact.AccountID
	left join fw.DimTimeClass tc on tc.TimeClassID=fact.TimeClassID
	left join fw.DimFiscalMonth fm on fm.FiscalMonthID=fact.FiscalMonthID
	left join fw.DimFiscalYear fy on fy.FiscalYearID=fact.FiscalYearID
	left join [ob].[DimFinancialReporting] accrollup on acc.OBDollarsFinancialReportingID = accrollup.FinancialReportingID
where 
	fact.IsDeleted = 0
GO


---------------------------------------------

-- fw.viewFactPayrollSampledDailyDetailedHours
--recreate referenced view
CREATE   VIEW fw.viewFactPayrollSampledDailyDetailedHours
	WITH SCHEMABINDING
	AS  
SELECT
	pr.RowID,
	pr.PayCodeGroupID,
	pr.DateID,
	pr.DepartmentID,
	pr.EmployeeID,
	pr.JobCodeID,
	pr.TimeClassID,
	pr.PayPeriodID,
	pr.Hours
FROM
	fw.FactPayrollSampledDailyDetailed pr
WHERE
	pr.TimeClassID IN (1, 4, 20)
	AND pr.EmployeeID <> 0
	AND pr.Hours <> 0;
GO


---------------------------------------------

-- fw.viewFactPayrollSampledMonthly
CREATE view [fw].[viewFactPayrollSampledMonthly] as 

	
select
	fact.DepartmentID,
	dept.DepartmentCode,
	fact.JobCodeID,
	jc.JobCode,
	fact.PayCodeID,
	pc.PayCode,
	fact.TimeClassID,
	tc.TimeClassCode,
	fact.FiscalYearID,
	fy.Name,
	fact.FiscalMonthID,
	fm.FiscalMonthCode,
	fm.SortOrder as FiscalMonthSortOrder,
	Dollars,
	DollarsYTD,
	DollarsPriorYear,
	DollarsPriorYTD,
	Hours,
	HoursYTD,
	HoursPriorYear,
	HoursPriorYTD,
	fact.FTEs,
	fact.FTEsYTD,
	fact.FTEsPriorYear,
	fact.FTEsPriorYTD
from 
	fw.FactPayrollSampledMonthly fact 
	left join fw.DimDepartment dept on dept.DepartmentID=fact.DepartmentID
	left join fw.DimJobCode jc on jc.JobCodeID=fact.JobCodeID
	left join fw.DimPayCode pc on pc.PayCodeID=fact.PayCodeID
	left join fw.DimTimeClass tc on tc.TimeClassID=fact.TimeClassID
	left join fw.DimFiscalMonth fm on fm.FiscalMonthID=fact.FiscalMonthID
	left join fw.DimFiscalYear fy on fy.FiscalYearID=fact.FiscalYearID

where 
	fact.IsDeleted = 0
GO


---------------------------------------------

-- fw.viewFactStatiscticDailyWithReallocaitonAdjustments
/************************************************************
** Author: ipetriv
** Create Date: 2017-7-26
** Description: View to append to int.FactStatistic PR statistic reallocation adjustments
** Last Modified: 2017-7-26
** GM Release: 2018.1
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2017-7-26	IP		B-16752		Added section for daily spread adjustments
*************************************************************/
CREATE VIEW fw.[viewFactStatiscticDailyWithReallocaitonAdjustments]
as
SELECT 
	SubSelect.DepartmentID,
	SubSelect.AccountID,
	SubSelect.FiscalMonthID,
	SubSelect.FiscalYearID,
	DT.DateID,
	SubSelect.TimeClassID,
	SUM(SubSelect.Units) AS Units
FROM (
		select
			STAT.DepartmentID,
			STAT.AccountID,
			STAT.FiscalYearID,
			STAT.FiscalMonthID,
			STAT.TimeClassID,
			SUM(STAT.Value) AS Units
		from
			[int].[FactStatistic] STAT
			inner join [fw].[DimDepartment] D on D.Departmentid = STAT.Departmentid
		where
			STAT.FiscalMonthID != 0 
			and STAT.FiscalYearID != 0
			and STAT.IsDeleted = 0
			and STAT.Value != 0 
			and (D.IsPR = 1 or exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache dc where dc.DriverDepartmentID = D.DepartmentID))
			and stat.TimeClassID = 2
			and stat.DepartmentID != 0
		group by 
			STAT.DepartmentID,
			STAT.AccountID,
			STAT.FiscalMonthID,
			STAT.FiscalYearID,
			STAT.TimeClassID

			UNION ALL
	SELECT 
		SourceDepartmentID as DepartmentID,
		SourceAccountID as AccountID,
		FiscalYearID,
		FiscalMonthID,
		2 as TimeclassID,		
		Change * -1 as Value
	FROM [mr].[BudgetReallocation] b
	INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
	INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID
	inner join [fw].[DimDepartment] D on D.Departmentid = SourceDepartmentID and (D.IsPR = 1 or exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache dc where dc.DriverDepartmentID = D.DepartmentID))
	WHERE b.TargetDepartmentID<>0 AND b.TargetAccountID<>0
	and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/
UNION All
SELECT 
	TargetDepartmentID as DepartmentID,
	TargetAccountID as AccountID,
	FiscalYearID,
	FiscalMonthID,
	2 as TimeclassID,
	Change as Value
FROM [mr].[BudgetReallocation] b
INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID
inner join [fw].[DimDepartment] D on D.Departmentid = TargetDepartmentID and (D.IsPR = 1 or exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache dc where dc.DriverDepartmentID = D.DepartmentID))
WHERE b.TargetDepartmentID<>0 AND b.TargetAccountID<>0
and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/

--Spread Adjustments within same Department/Account
UNION All
SELECT 
	SourceDepartmentID as DepartmentID,
	SourceAccountID as AccountID,
	FiscalYearID,
	FiscalMonthID,
	2 as TimeclassID,
	Change as Value
FROM [mr].[BudgetReallocation] b
INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID
inner join [fw].[DimDepartment] D on D.Departmentid = SourceDepartmentID and (D.IsPR = 1 or exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache dc where dc.DriverDepartmentID = D.DepartmentID))
WHERE b.TargetDepartmentID=0 AND b.TargetAccountID=0
	and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/
) SubSelect
inner join [fw].[DimDate] DT on DT.CalendarMonth = SubSelect.FiscalMonthID and DT.FiscalYear = SubSelect.FiscalYearID
GROUP BY 
	SubSelect.DepartmentID,
	SubSelect.AccountID,
	SubSelect.FiscalMonthID,
	SubSelect.FiscalYearID,
	DT.DateID,
	SubSelect.TimeClassID
GO


---------------------------------------------

-- fw.viewFactStatiscticMonthlyWithReallocaitonAdjustments
CREATE View fw.[viewFactStatiscticMonthlyWithReallocaitonAdjustments] as 
/************************************************************
** Author: ipetriv
** Create Date: 2017-7-26
** Description: View to append to int.FactStatistic MR statistic reallocation adjustments
** Last Modified: 2017-7-26
** GM Release: 2018.1
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2017-7-26	IP		B-16752		Added section for monthly spread adjustments
*************************************************************/

SELECT 
		DepartmentID,
		AccountID,
		FiscalYearID,
		FiscalMonthID,
		TimeClassID,
		SUM(Amount) as Amount
FROM (
	select
		stat.DepartmentID,
		stat.AccountID,
		stat.FiscalYearID,
		stat.FiscalMonthID,
		stat.TimeClassID,
		STAT.Value as Amount
	from
		int.FactStatistic stat 
		inner join fw.DimAccount A on A.Accountid = STAT.Accountid
		inner join fw.DimDepartment D on D.Departmentid = STAT.Departmentid
		where 
		A.IsStat = 1
		AND stat.IsDeleted = 0
		and stat.Value != 0
UNION ALL
	SELECT 
		SourceDepartmentID as DepartmentID,
		SourceAccountID as AccountID,
		FiscalYearID,
		FiscalMonthID,
		2 as TimeclassID,		
		Change * -1 as Value
	FROM [mr].[BudgetReallocation] b
	INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
	INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID
	WHERE b.TargetDepartmentID<>0 AND b.TargetAccountID<>0
	and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/
UNION All
SELECT 
	TargetDepartmentID as DepartmentID,
	TargetAccountID as AccountID,
	FiscalYearID,
	FiscalMonthID,
	2 as TimeclassID,
	Change as Value
FROM [mr].[BudgetReallocation] b
INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID
WHERE b.TargetDepartmentID<>0 AND b.TargetAccountID<>0
and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/

--Spread Adjustments within same Department/Account
UNION All
SELECT 
	SourceDepartmentID as DepartmentID,
	SourceAccountID as AccountID,
	FiscalYearID,
	FiscalMonthID,
	2 as TimeclassID,
	Change as Value
FROM [mr].[BudgetReallocation] b
INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID
WHERE b.TargetDepartmentID=0 AND b.TargetAccountID=0
	and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/
) SubSelect
GROUP BY 
		DepartmentID,
		AccountID,
		FiscalYearID,
		FiscalMonthID,
		TimeClassID
GO


---------------------------------------------

-- fw.viewFactStatiscticPrimaryMonthlyWithReallocaitonAdjustments
CREATE View fw.[viewFactStatiscticPrimaryMonthlyWithReallocaitonAdjustments] as 
/************************************************************
** Author: ipetriv
** Create Date: 2017-7-26
** Description: View to append to int.FactStatistic MR statistic reallocation adjustments
** Last Modified: 2017-7-26
** GM Release: 2018.1
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2017-7-26	IP		B-16752		Added section for monthly spread adjustments
*************************************************************/

SELECT 
		DepartmentID,
		AccountID,
		FiscalYearID,
		FiscalMonthID,
		TimeClassID,
		SUM(Amount) as Amount
FROM (
	select
		stat.DepartmentID,
		stat.AccountID,
		stat.FiscalYearID,
		stat.FiscalMonthID,
		stat.TimeClassID,
		STAT.Value as Amount
	from
		int.FactStatistic stat 
		inner join fw.DimAccount A on A.Accountid = STAT.Accountid
		inner join fw.DimDepartment D on D.Departmentid = STAT.Departmentid
		inner join [fw].[viewStatisticPrimaryConfiguration] V on V.AccountID=stat.AccountID and V.DepartmentID=stat.DepartmentID
		where 
		A.IsStat = 1
		AND stat.IsDeleted = 0
		and stat.Value != 0
UNION ALL
	SELECT 
		SourceDepartmentID as DepartmentID,
		SourceAccountID as AccountID,
		FiscalYearID,
		FiscalMonthID,
		2 as TimeclassID,		
		Change * -1 as Value
	FROM [mr].[BudgetReallocation] b
	INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
	INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID
	inner join [fw].[viewStatisticPrimaryConfiguration] V on V.AccountID=A.AccountID and V.DepartmentID=SourceDepartmentID
	WHERE b.TargetDepartmentID<>0 AND b.TargetAccountID<>0
	and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/
UNION All
SELECT 
	TargetDepartmentID as DepartmentID,
	TargetAccountID as AccountID,
	FiscalYearID,
	FiscalMonthID,
	2 as TimeclassID,
	Change as Value
FROM [mr].[BudgetReallocation] b
INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID
inner join [fw].[viewStatisticPrimaryConfiguration] V on V.AccountID=A.AccountID and V.DepartmentID=TargetDepartmentID
WHERE b.TargetDepartmentID<>0 AND b.TargetAccountID<>0
and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/

--Spread Adjustments within same Department/Account
UNION All
SELECT 
	SourceDepartmentID as DepartmentID,
	SourceAccountID as AccountID,
	FiscalYearID,
	FiscalMonthID,
	2 as TimeclassID,
	Change as Value
FROM [mr].[BudgetReallocation] b
INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID
inner join [fw].[viewStatisticPrimaryConfiguration] V on V.AccountID=A.AccountID and V.DepartmentID=SourceDepartmentID
WHERE b.TargetDepartmentID=0 AND b.TargetAccountID=0
	and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/
) SubSelect
GROUP BY 
		DepartmentID,
		AccountID,
		FiscalYearID,
		FiscalMonthID,
		TimeClassID
GO


---------------------------------------------

-- fw.viewFactStatisticByPayPeriodWithReallocaitonAdjustments
CREATE VIEW fw.viewFactStatisticByPayPeriodWithReallocaitonAdjustments
/************************************************************
** Author: ipetriv
** Create Date: 2017-7-26
** Description: View to append to int.FactStatistic MR statistic reallocation adjustments
** Last Modified: 2017-7-26
** GM Release: 2018.1
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2017-7-26	IP		B-16752		Added section for monthly spread adjustments
*************************************************************/

AS
SELECT DepartmentID,
	AccountID,
	PayPeriodID,
	TimeClassID,
	sum(Value) AS Value
FROM (
	SELECT STAT.DepartmentID,
		STAT.AccountID,
		STAT.PayPeriodID,
		STAT.TimeClassID,
		STAT.Value
	FROM [int].[FactStatisticsbyPayPeriod] STAT
	INNER JOIN [fw].[DimDepartment] D
		ON D.Departmentid = STAT.Departmentid
	WHERE STAT.Value != 0
		AND STAT.Isdeleted = 0
		AND STAT.PayPeriodID != 0
		AND (
			D.IsPR = 1
			OR EXISTS (
				SELECT 1
				FROM client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache dc
				WHERE dc.DriverDepartmentID = D.DepartmentID
				)
			)
		AND STAT.TimeClassID IN (1,2)
		AND stat.DepartmentID <> 0
	--ADD ADJUSTMENTS 
	
	UNION ALL
	
	SELECT ADJ.DepartmentID,
		ADJ.AccountID,
		PP.PayPeriodID,
		2 AS TimeClassID,
		Adj.Amount * PP.PreriodWeight AS Units
	FROM (
		SELECT DepartmentID,
			AccountID,
			FiscalYearID,
			FiscalMonthID,
			TimeClassID,
			SUM(Value) AS Amount
		FROM (
			SELECT SourceDepartmentID AS DepartmentID,
				SourceAccountID AS AccountID,
				FiscalYearID,
				FiscalMonthID,
				2 AS TimeclassID,
				Change * - 1 AS Value
			FROM [mr].[BudgetReallocation] b
			INNER JOIN [mr].[BudgetReallocationAdjustment] ba
				ON b.BudgetReallocationGUID = ba.BudgetReallocationGUID
			INNER JOIN [fw].[DimAccount] A
				ON SourceAccountID = A.AccountID
			WHERE b.TargetDepartmentID <> 0
				AND b.TargetAccountID <> 0
				AND ba.UnitTypeID = 145 /*select * from fw.dimUnitType where Name = 'Units'*/
			
			UNION ALL
			
			SELECT TargetDepartmentID AS DepartmentID,
				TargetAccountID AS AccountID,
				FiscalYearID,
				FiscalMonthID,
				2 AS TimeclassID,
				Change AS Value
			FROM [mr].[BudgetReallocation] b
			INNER JOIN [mr].[BudgetReallocationAdjustment] ba
				ON b.BudgetReallocationGUID = ba.BudgetReallocationGUID
			INNER JOIN [fw].[DimAccount] A
				ON SourceAccountID = A.AccountID
			WHERE b.TargetDepartmentID <> 0
				AND b.TargetAccountID <> 0
				AND ba.UnitTypeID = 145 /*select * from fw.dimUnitType where Name = 'Units'*/
			--Spread Adjustments within same Department/Account
			
			UNION ALL
			
			SELECT SourceDepartmentID AS DepartmentID,
				SourceAccountID AS AccountID,
				FiscalYearID,
				FiscalMonthID,
				2 AS TimeclassID,
				Change AS Value
			FROM [mr].[BudgetReallocation] b
			INNER JOIN [mr].[BudgetReallocationAdjustment] ba
				ON b.BudgetReallocationGUID = ba.BudgetReallocationGUID
			INNER JOIN [fw].[DimAccount] A
				ON SourceAccountID = A.AccountID
			WHERE b.TargetDepartmentID = 0
				AND b.TargetAccountID = 0
				AND ba.UnitTypeID = 145 /*select * from fw.dimUnitType where Name = 'Units'*/
			) SubSelect
		GROUP BY DepartmentID,
			AccountID,
			FiscalYearID,
			FiscalMonthID,
			TimeClassID
		) AS Adj
	INNER JOIN fw.DimDepartment dd
		ON adj.DepartmentID = dd.DepartmentID
	INNER JOIN (
		SELECT [PayPeriodID],
			PayCycleID,
			[PeriodNumber],
			[FiscalMonthIDStart] AS FiscalMonthID,
			[FiscalYearIDStart] AS FiscalYearID,
			[PeriodWeightStart] AS PreriodWeight
		FROM [fw].[DimPayPeriod]
		
		UNION ALL
		
		SELECT [PayPeriodID],
			PayCycleID,
			[PeriodNumber],
			FiscalMonthIDSecond AS FiscalMonthID,
			FiscalYearIDSecond AS FiscalYearID,
			PeriodWeightSecond AS PreriodWeight
		FROM [fw].[DimPayPeriod]
		) PP
		ON PP.FiscalYearID = Adj.FiscalYearID
			AND pp.FiscalMonthID = adj.FiscalMonthID
			AND pp.PayCycleID = dd.PayCycleID
		AND Adj.Amount * PP.PreriodWeight <> 0
	) SubSelect
GROUP BY DepartmentID,
	AccountID,
	PayPeriodID,
	TimeClassID
GO


---------------------------------------------

-- fw.viewFactStatisticRollupPrimarySampledMonthly
CREATE VIEW [fw].[viewFactStatisticRollupPrimarySampledMonthly]
AS
SELECT 
	cfg.RollupLevel,
	cfg.RollupMemberID,
	fs.AccountID,
	fs.FiscalYearID,
	fs.FiscalMonthID,
	fs.TimeClassID,
	sum(fs.Amount) as Amount,
	sum(fs.AmountYTD) as AmountYTD,
	sum(fs.AmountPriorYear) as AmountPriorYear,
	sum(fs.AmountPriorYTD) as AmountPriorYTD,
	min(cast(fs.IsSystemGenerated AS INT)) AS IsSystemGenerated
FROM [fw].FactStatisticSampledMonthly fs
INNER JOIN fw.DimDepartment dd ON fs.DepartmentID = dd.DepartmentID
INNER JOIN fw.PrimaryStatisticsRollupsConfiguration cfg ON (
		(cfg.RollupLevel = 'DepartmentRollup1' AND cfg.RollupMemberID = dd.DepartmentRollup1ID)
		OR (cfg.RollupLevel = 'DepartmentRollup2' AND cfg.RollupMemberID = dd.DepartmentRollup2ID)
		OR (cfg.RollupLevel = 'DepartmentRollup3' AND cfg.RollupMemberID = dd.DepartmentRollup3ID)
		OR (cfg.RollupLevel = 'DepartmentRollup4' AND cfg.RollupMemberID = dd.DepartmentRollup4ID)
		OR (cfg.RollupLevel = 'DepartmentRollup5' AND cfg.RollupMemberID = dd.DepartmentRollup5ID)
		OR (cfg.RollupLevel = 'DepartmentRollup6' AND cfg.RollupMemberID = dd.DepartmentRollup6ID)
		OR (cfg.RollupLevel = 'Entity' AND cfg.RollupMemberID = dd.EntityID)
		OR (cfg.RollupLevel = 'System' AND cfg.RollupMemberID = dd.SystemID)
		)	AND fs.AccountID = cfg.AccountID
WHERE fs.IsDeleted = 0
AND IsMRMetricTracking = 1
GROUP BY 
	cfg.RollupLevel,
	cfg.RollupMemberID,
	fs.AccountID,
	fs.FiscalYearID,
	fs.FiscalMonthID,
	fs.TimeClassID
GO


---------------------------------------------

-- fw.viewFactStatisticSampledMonthly
CREATE view [fw].[viewFactStatisticSampledMonthly] as 
select
	fact.DepartmentID,
	dept.DepartmentCode,
	fact.AccountID,
	acc.AccountCode,
	accrollup.LineName as AccountRollup,
	accrollup.Section as AccountCategory,
	accrollup.Name as FinancialReporting,
	fact.TimeClassID,
	tc.TimeClassCode,
	fact.FiscalYearID,
	fy.Name,
	fact.FiscalMonthID,
	fm.FiscalMonthCode,
	fm.SortOrder as FiscalMonthSortOrder,
	fact.Amount,
	fact.AmountPriorYear,
	fact.AmountPriorYTD,
	fact.AmountYTD

from 
	fw.FactStatisticSampledMonthly fact 
	left join fw.DimDepartment dept on dept.DepartmentID=fact.DepartmentID
	left join fw.DimAccount acc on acc.AccountID=fact.AccountID
	left join fw.DimTimeClass tc on tc.TimeClassID=fact.TimeClassID
	left join fw.DimFiscalMonth fm on fm.FiscalMonthID=fact.FiscalMonthID
	left join fw.DimFiscalYear fy on fy.FiscalYearID=fact.FiscalYearID
	left join [ob].[DimFinancialReporting] accrollup on acc.OBDollarsFinancialReportingID = accrollup.FinancialReportingID
where 
	fact.IsDeleted = 0
GO


---------------------------------------------

-- fw.viewFactStatisticSecondaryMonthlyWithReallocaitonAdjustments
CREATE View fw.[viewFactStatisticSecondaryMonthlyWithReallocaitonAdjustments] as 
/************************************************************
** Author: ipetriv
** Create Date: 2017-7-26
** Description: View to append to int.FactStatistic MR statistic reallocation adjustments
** Last Modified: 2017-7-26
** GM Release: 2018.1
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2017-7-26	IP		B-16752		Added section for monthly spread adjustments
*************************************************************/

		SELECT 
		DepartmentID,
		AccountID,
		FiscalYearID,
		FiscalMonthID,
		TimeClassID,
		SUM(Amount) as Amount
FROM (
	select
		stat.DepartmentID,
		stat.AccountID,
		stat.FiscalYearID,
		stat.FiscalMonthID,
		stat.TimeClassID,
		STAT.Value as Amount
	from
		int.FactStatistic stat 
		inner join fw.DimAccount A on A.Accountid = STAT.Accountid
		inner join fw.DimDepartment D on D.Departmentid = STAT.Departmentid
		inner join [fw].[viewStatisticSecondaryConfiguration] V on V.AccountID=stat.AccountID and V.DepartmentID=stat.DepartmentID
		where 
		A.IsStat = 1
		AND stat.IsDeleted = 0
		and stat.Value != 0
UNION ALL
	SELECT 
		SourceDepartmentID as DepartmentID,
		SourceAccountID as AccountID,
		FiscalYearID,
		FiscalMonthID,
		2 as TimeclassID,		
		Change * -1 as Value
	FROM [mr].[BudgetReallocation] b
	INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
	INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID
	inner join [fw].[viewStatisticPrimaryConfiguration] V on V.AccountID=A.AccountID and V.DepartmentID=SourceDepartmentID
	WHERE b.TargetDepartmentID<>0 AND b.TargetAccountID<>0
	and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/
UNION All
SELECT 
	TargetDepartmentID as DepartmentID,
	TargetAccountID as AccountID,
	FiscalYearID,
	FiscalMonthID,
	2 as TimeclassID,
	Change as Value
FROM [mr].[BudgetReallocation] b
INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID
inner join [fw].[viewStatisticSecondaryConfiguration] V on V.AccountID=A.AccountID and V.DepartmentID=TargetDepartmentID
WHERE b.TargetDepartmentID<>0 AND b.TargetAccountID<>0
and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/

--Spread Adjustments within same Department/Account
UNION All
SELECT 
	SourceDepartmentID as DepartmentID,
	SourceAccountID as AccountID,
	FiscalYearID,
	FiscalMonthID,
	2 as TimeclassID,
	Change as Value
FROM [mr].[BudgetReallocation] b
INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID
inner join [fw].[viewStatisticSecondaryConfiguration] V on V.AccountID=A.AccountID and V.DepartmentID=SourceDepartmentID
WHERE b.TargetDepartmentID=0 AND b.TargetAccountID=0
	and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/
) SubSelect
GROUP BY 
		DepartmentID,
		AccountID,
		FiscalYearID,
		FiscalMonthID,
		TimeClassID
GO


---------------------------------------------

-- fw.viewFiscalYearMonth
CREATE VIEW [fw].[viewFiscalYearMonth] AS 
	SELECT 	
		ROW_NUMBER() over (order by y.fiscalyearid, m.sortorder) as FiscalTimeID,
		FiscalMonthID, m.Name as [FiscalMonth],
		y.FiscalYearID, y.Name as [FiscalYear]		
	FROM 
		fw.DimFiscalMonth m
	CROSS JOIN
		fw.DimFiscalYear y
	WHERE 
		m.FiscalMonthID <> 0 AND y.FiscalYearID <> 0
GO


---------------------------------------------

-- fw.viewLeapYearByFiscalYear
CREATE VIEW fw.viewLeapYearByFiscalYear
AS
SELECT DISTINCT 
	CalendarYear, 
	FiscalYear,
	CASE WHEN (FiscalYear % 4 = 0 AND FiscalYear % 100 != 0) OR FiscalYear % 400 = 0 THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END AS IsLeapYear
FROM [fw].[DimDate] 
WHERE CalendarMonth = 2
GO


---------------------------------------------

-- fw.viewMRGLBudgetCostPerRVUbyMonth
CREATE VIEW [fw].[viewMRGLBudgetCostPerRVUbyMonth] AS
	
	SELECT
		 A.DepartmentID
		,B.AccountID
		,A.ChargeCodeID
		,A.CostComponentID
		,A.FiscalMonthID
		,A.FiscalYearID
		,A.ChargeVolume
		,B.CostingResultID
		,B.TimeClassID
		,(A.ChargeVolume * A.RVU * B.VariableDirectUnitCostPerRVU) as ExtendedVariableDirectCost
		,B.TotalCost
		,B.TotalVariableDirectCost
	FROM
		(SELECT 
			  b.DepartmentID
			, b.ChargeCodeID
			, ca.CostComponentID
			, b.FiscalMonthID
			, b.FiscalYearID
			, MAX(ca.RVU) as RVU
			, SUM(Volume) as ChargeVolume
		 FROM [dss].[FactDepartmentChargeSummary] b
			  INNER JOIN [dss].[ChargeAllocation] ca
				ON ca.ChargeCodeID = b.ChargeCodeID 
				and ca.DepartmentID = b.DepartmentID
				and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0
		 GROUP BY
			b.DepartmentID, b.ChargeCodeID, ca.CostComponentID, b.FiscalMonthID, b.FiscalYearID) A
	
	INNER JOIN 
	
		(SELECT
			  OriginalAccountID as AccountID
			, gl.OriginalDepartmentID as DepartmentID
			, gl.FiscalYearID
			, gl.CostComponentID
			, gl.CostingResultID
			, gl.TimeClassID
			, SUM(gl.VariableDirectUnitCost)/SUM(ca.RVU) as VariableDirectUnitCostPerRVU
			, SUM(gl.VariableDirectUnitCost * gl.Volume) as TotalVariableDirectCost
			, SUM(gl.TotalCost) as TotalCost
		FROM [dss].[FactCostingOutDetailGL] gl
			INNER JOIN [dss].[CostingResult] cr on gl.CostingResultID = cr.CostingResultID
			INNER JOIN [dss].[CostingConfig] con on cr.CostingConfigGuid = con.CostingConfigGuid
			INNER JOIN [dss].[ChargeAllocation] ca on
				ca.CostingConfigGuid = con.CostingConfigGUID
				and ca.ChargeCodeID = gl.ChargeCodeID 
				and ca.DepartmentID = gl.OriginalDepartmentID
				and ca.CostComponentID = gl.CostComponentID
				and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0
		WHERE 
			gl.CostingResultID in (select CostingResultID from
										(select FiscalYearID, max(CostingResultID) as CostingResultID
										 from [dss].[CostingResult] cr3
										      inner join [dss].[CostingConfig] cfg on cfg.CostingConfigGuid = cr3.CostingConfigGuid
										 where cr3.IsActivityBasedDetail = 1 and cr3.IsMarkedForDeletion = 0 and cr3.IsFailure = 0
									     group by FiscalYearID) C)
		GROUP BY
			  gl.OriginalAccountID
			, gl.OriginalDepartmentID
			, gl.FiscalYearID
			, gl.CostComponentID
			, gl.CostingResultID
			, gl.TimeClassID) B
	ON 
		A.DepartmentID = B.DepartmentID 
		and A.CostComponentID = B.CostComponentID
		and A.FiscalYearID = b.FiscalYearID
GO


---------------------------------------------

-- fw.viewMRPayrollBudgetCostPerRVUbyMonth
CREATE VIEW [fw].[viewMRPayrollBudgetCostPerRVUbyMonth] AS
	
	SELECT
		 A.DepartmentID
		,B.JobCodeID
		,B.PayCodeGroupID
		,A.ChargeCodeID
		,A.CostComponentID
		,A.FiscalMonthID
		,A.FiscalYearID
		,A.ChargeVolume
		,B.CostingResultID
		,B.TimeClassID
		,(A.ChargeVolume * A.RVU * B.VariableDirectUnitCostPerRVU) as ExtendedVariableDirectCost
		,B.TotalCost
		,B.TotalVariableDirectCost
	FROM
		(SELECT 
			  b.DepartmentID
			, b.ChargeCodeID
			, ca.CostComponentID
			, b.FiscalMonthID
			, b.FiscalYearID
			, MAX(ca.RVU) as RVU
			, SUM(Volume) as ChargeVolume
		 FROM [dss].[FactDepartmentChargeSummary] b
			  INNER JOIN [dss].[ChargeAllocation] ca
				ON ca.ChargeCodeID = b.ChargeCodeID 
				and ca.DepartmentID = b.DepartmentID
				and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0
		 GROUP BY
			b.DepartmentID, b.ChargeCodeID, ca.CostComponentID, b.FiscalMonthID, b.FiscalYearID) A
	
	INNER JOIN 
	
		(SELECT
			  OriginalJobCodeID as JobCodeID
			, pc.PayCodeGroupID
			, pay.OriginalDepartmentID as DepartmentID
			, pay.FiscalYearID
			, pay.CostComponentID
			, pay.CostingResultID
			, pay.TimeClassID
			, SUM(pay.VariableDirectUnitCost)/SUM(ca.RVU) as VariableDirectUnitCostPerRVU
			, SUM(pay.VariableDirectUnitCost * pay.Volume) as TotalVariableDirectCost
			, SUM(pay.TotalCost) as TotalCost
		FROM [dss].[FactCostingOutDetailPayroll] pay
			INNER JOIN [dss].[CostingResult] cr on pay.CostingResultID = cr.CostingResultID
			INNER JOIN [dss].[CostingConfig] con on cr.CostingConfigGuid = con.CostingConfigGuid
			INNER JOIN [dss].[ChargeAllocation] ca on
				ca.CostingConfigGuid = con.CostingConfigGUID
				and ca.ChargeCodeID = pay.ChargeCodeID 
				and ca.DepartmentID = pay.OriginalDepartmentID
				and ca.CostComponentID = pay.CostComponentID
				and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0
			INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = pay.OriginalPayCodeID
		WHERE 
			pay.CostingResultID in (select CostingResultID from
							(select FiscalYearID, max(CostingResultID) as CostingResultID
							 from [dss].[CostingResult] cr3
							      inner join [dss].[CostingConfig] cfg on cfg.CostingConfigGuid = cr3.CostingConfigGuid
							 where cr3.IsActivityBasedDetail = 1 and cr3.IsMarkedForDeletion = 0 and cr3.IsFailure = 0
						     group by FiscalYearID) C)
		GROUP BY
			  pay.OriginalJobCodeID
			, pc.PayCodeGroupID
			, pay.OriginalDepartmentID
			, pay.FiscalYearID
			, pay.CostComponentID
			, pay.CostingResultID
			, pay.TimeClassID) B
	ON 
		A.DepartmentID = B.DepartmentID 
		and A.CostComponentID = B.CostComponentID
		and A.FiscalYearID = B.FiscalYearID
GO


---------------------------------------------

-- fw.viewPrimaryStatisticsByPayPeriod
-- primary statistics (by pay period) driver accounts
CREATE view [fw].[viewPrimaryStatisticsByPayPeriod] as 
	SELECT [DepartmentID], [AccountID], [PayPeriodID], [TimeClassID], SUM([Units]) as Units, SUM([UnitsYTD]) as UnitsYTD, SUM([UnitsPriorYear]) as UnitsPriorYear, SUM([UnitsPriorYTD]) as UnitsPriorYTD, cast(MIN([IsSystemGenerated]) as bit) as IsSystemGenerated
	FROM
	
	(SELECT fs.DepartmentID, fs.AccountID, fs.PayPeriodID, fs.TimeClassID, fs.Units, fs.UnitsYTD, fs.UnitsPriorYear, fs.UnitsPriorYTD, cast(fs.IsSystemGenerated as int) as IsSystemGenerated
	 FROM [fw].[FactStatisticSampledPayPeriod] fs
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID
	 WHERE fs.IsDeleted = 0 AND cfg.IsDeleted = 0
	 AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID)
	 
	 UNION ALL
	 
	 SELECT pp.DepartmentID, pp.AccountID, pp.PayPeriodID, pp.TimeClassID, pp.Units, pp.UnitsYTD, pp.UnitsPriorYear, pp.UnitsPriorYTD, cast(0 as int) as IsSystemGenerated
	 FROM [fw].[FactStatisticDriverDepartmentSampledPayPeriod] pp
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON pp.DepartmentID = cfg.DepartmentID AND pp.AccountID = cfg.AccountID
	 WHERE pp.IsDeleted = 0 AND cfg.IsDeleted = 0) allData
	 
	 GROUP BY [DepartmentID], [AccountID], [PayPeriodID], [TimeClassID]
GO


---------------------------------------------

-- fw.viewPrimaryStatisticsDaily
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI			Description
** 1        2022-09-13  HV			JAZZ-38145  PR Metrics Definition - Calculate Configured Daily Metrics
*************************************************************/

CREATE view [fw].[viewPrimaryStatisticsDaily]
as 
	SELECT [DepartmentID], [AccountID], [PayPeriodID], [DateID], [TimeClassID], SUM([Units]) as Units
	FROM
	
	(SELECT fs.DepartmentID, fs.AccountID, fs.PayPeriodID, fs.DateID, fs.TimeClassID, fs.Units
	 FROM [fw].[FactStatisticSampledDaily] fs
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID
	 WHERE fs.IsDeleted = 0 AND cfg.IsDeleted = 0
	 AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID)
	 
	 UNION ALL
	 
	 SELECT pp.DepartmentID, pp.AccountID, pp.PayPeriodID, pp.DateID, pp.TimeClassID, pp.Units
	 FROM [fw].[FactStatisticDriverDepartmentSampledDaily] pp
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON pp.DepartmentID = cfg.DepartmentID AND pp.AccountID = cfg.AccountID
	 WHERE pp.IsDeleted = 0 AND cfg.IsDeleted = 0) allData
	 
	 GROUP BY [DepartmentID], [AccountID], [PayPeriodID], [DateID], [TimeClassID]
GO


---------------------------------------------

-- fw.viewPrimaryStatisticsNonStaffingExpenseByPayPeriod
-- primary statistics (by month) non-staffing driver accounts
CREATE view [fw].[viewPrimaryStatisticsNonStaffingExpenseByPayPeriod] as 

	SELECT [DepartmentID], [AccountID], [PayPeriodID], [TimeClassID], SUM([Units]) as Units, SUM([UnitsYTD]) as UnitsYTD, SUM([UnitsPriorYear]) as UnitsPriorYear, SUM([UnitsPriorYTD]) as UnitsPriorYTD, MAX([RowID]) as RowID, cast(MAX(cast([IsDeleted] as int)) as bit) as IsDeleted, cast(MIN([IsSystemGenerated]) as bit) as IsSystemGenerated
	FROM
	
	(SELECT fs.DepartmentID, fs.AccountID, fs.PayPeriodID, fs.TimeClassID, fs.Units, fs.UnitsYTD, fs.UnitsPriorYear, fs.UnitsPriorYTD, fs.RowID, fs.IsDeleted, cast(fs.IsSystemGenerated as int) as IsSystemGenerated
	 FROM [fw].[FactStatisticSampledPayPeriod] fs
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID
	 WHERE cfg.NonStaffingExpense = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0
	 AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID)
	 
	 UNION ALL
	 
	 SELECT pp.DepartmentID, pp.AccountID, pp.PayPeriodID, pp.TimeClassID, pp.Units, pp.UnitsYTD, pp.UnitsPriorYear, pp.UnitsPriorYTD, pp.RowID, pp.IsDeleted, cast(0 as int) as IsSystemGenerated
	 FROM [fw].[FactStatisticDriverDepartmentSampledPayPeriod] pp
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON pp.DepartmentID = cfg.DepartmentID AND pp.AccountID = cfg.AccountID
	 WHERE cfg.NonStaffingExpense = 1 AND pp.IsDeleted = 0 AND cfg.IsDeleted = 0) allData
	 
	 GROUP BY [DepartmentID], [AccountID], [PayPeriodID], [TimeClassID]
GO


---------------------------------------------

-- fw.viewPrimaryStatisticsNonStaffingExpenseDaily
CREATE view [fw].[viewPrimaryStatisticsNonStaffingExpenseDaily] 
as 
	SELECT [DepartmentID], [AccountID], [PayPeriodID], [DateID], [TimeClassID], SUM([Units]) as Units
	FROM
	
	(SELECT fs.DepartmentID, fs.AccountID, fs.PayPeriodID, fs.DateID, fs.TimeClassID, fs.Units
	 FROM [fw].[FactStatisticSampledDaily] fs
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID
	 WHERE cfg.NonStaffingExpense = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0
	 AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID)
	 
	 UNION ALL
	 
	 SELECT pp.DepartmentID, pp.AccountID, pp.PayPeriodID, pp.DateID, pp.TimeClassID, pp.Units
	 FROM [fw].[FactStatisticDriverDepartmentSampledDaily] pp
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON pp.DepartmentID = cfg.DepartmentID AND pp.AccountID = cfg.AccountID
	 WHERE cfg.NonStaffingExpense = 1 AND pp.IsDeleted = 0 AND cfg.IsDeleted = 0) allData
	 
	 GROUP BY [DepartmentID], [AccountID], [PayPeriodID], [DateID], [TimeClassID]
GO


---------------------------------------------

-- fw.viewPrimaryStatisticsNonStaffingExpenseMonthly
-- primary statistics (by month) non-staffing driver accounts
CREATE view [fw].[viewPrimaryStatisticsNonStaffingExpenseMonthly] as 

	SELECT [RowID], [DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID], SUM([Amount]) as Amount, SUM([AmountYTD]) as AmountYTD, SUM([AmountPriorYear]) as AmountPriorYear, SUM([AmountPriorYTD]) as AmountPriorYTD, cast(0 as bit) as IsDeleted, cast(MIN([IsSystemGenerated]) as bit) as IsSystemGenerated
	FROM
	
	(SELECT fs.RowID, fs.DepartmentID, fs.AccountID, fs.FiscalYearID, fs.FiscalMonthID, fs.TimeClassID, fs.Amount, fs.AmountYTD, fs.AmountPriorYear, fs.AmountPriorYTD, cast(fs.IsSystemGenerated as int) as IsSystemGenerated
	 FROM [fw].[FactStatisticSampledMonthly] fs
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID
	 WHERE cfg.NonStaffingExpense = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0
	 AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID)
	 
	 UNION ALL
	 
	 SELECT mo.RowID, mo.DepartmentID, mo.AccountID, mo.FiscalYearID, mo.FiscalMonthID, mo.TimeClassID, mo.Amount, mo.AmountYTD, mo.AmountPriorYear, mo.AmountPriorYTD, cast(0 as int) as IsSystemGenerated
	 FROM [fw].[FactStatisticDriverDepartmentSampledMonthly] mo
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON mo.DepartmentID = cfg.DepartmentID AND mo.AccountID = cfg.AccountID
	 WHERE cfg.NonStaffingExpense = 1 AND mo.IsDeleted = 0 AND cfg.IsDeleted = 0) allData
	 
	 GROUP BY [RowID], [DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID]
GO


---------------------------------------------

-- fw.viewPrimaryStatisticsRevenueByPayPeriod
-- primary statistics (by pay period) revenue driver accounts
CREATE view [fw].[viewPrimaryStatisticsRevenueByPayPeriod] as

	SELECT [DepartmentID], [AccountID], [PayPeriodID], [TimeClassID], SUM([Units]) as Units, SUM([UnitsYTD]) as UnitsYTD, SUM([UnitsPriorYear]) as UnitsPriorYear, SUM([UnitsPriorYTD]) as UnitsPriorYTD, MAX([RowID]) as RowID, cast(MAX(cast([IsDeleted] as int)) as bit) as IsDeleted, cast(MIN([IsSystemGenerated]) as bit) as IsSystemGenerated
	FROM
	
	(SELECT fs.DepartmentID, fs.AccountID, fs.PayPeriodID, fs.TimeClassID, fs.Units, fs.UnitsYTD, fs.UnitsPriorYear, fs.UnitsPriorYTD, fs.RowID, fs.IsDeleted, cast(fs.IsSystemGenerated as int) as IsSystemGenerated
	 FROM [fw].[FactStatisticSampledPayPeriod] fs
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID
	 WHERE cfg.Revenue = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0
	 AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID)
	 
	 UNION ALL
	 
	 SELECT pp.DepartmentID, pp.AccountID, pp.PayPeriodID, pp.TimeClassID, pp.Units, pp.UnitsYTD, pp.UnitsPriorYear, pp.UnitsPriorYTD, pp.RowID, pp.IsDeleted, cast(0 as int) as IsSystemGenerated
	 FROM [fw].[FactStatisticDriverDepartmentSampledPayPeriod] pp
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON pp.DepartmentID = cfg.DepartmentID AND pp.AccountID = cfg.AccountID
	 WHERE cfg.Revenue = 1 AND pp.IsDeleted = 0 AND cfg.IsDeleted = 0) allData
	 
	 GROUP BY [DepartmentID], [AccountID], [PayPeriodID], [TimeClassID]
GO


---------------------------------------------

-- fw.viewPrimaryStatisticsRevenueDaily
CREATE view [fw].[viewPrimaryStatisticsRevenueDaily] 
as 
	SELECT [DepartmentID], [AccountID], [PayPeriodID], [DateID], [TimeClassID], SUM([Units]) as Units
	FROM
	
	(SELECT fs.DepartmentID, fs.AccountID, fs.PayPeriodID, fs.DateID, fs.TimeClassID, fs.Units
	 FROM [fw].[FactStatisticSampledDaily] fs
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID
	 WHERE cfg.Revenue = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0
	 AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID)
	 
	 UNION ALL
	 
	 SELECT pp.DepartmentID, pp.AccountID, pp.PayPeriodID, pp.DateID, pp.TimeClassID, pp.Units
	 FROM [fw].[FactStatisticDriverDepartmentSampledDaily] pp
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON pp.DepartmentID = cfg.DepartmentID AND pp.AccountID = cfg.AccountID
	 WHERE cfg.Revenue = 1 AND pp.IsDeleted = 0 AND cfg.IsDeleted = 0) allData
	 
	 GROUP BY [DepartmentID], [AccountID], [PayPeriodID], [DateID], [TimeClassID]
GO


---------------------------------------------

-- fw.viewPrimaryStatisticsRevenueMonthly
-- primary statistics (by month) revenue driver accounts
CREATE view [fw].[viewPrimaryStatisticsRevenueMonthly] as

	SELECT [RowID], [DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID], SUM([Amount]) as Amount, SUM([AmountYTD]) as AmountYTD, SUM([AmountPriorYear]) as AmountPriorYear, SUM([AmountPriorYTD]) as AmountPriorYTD, cast(0 as bit) as IsDeleted, cast(MIN([IsSystemGenerated]) as bit) as IsSystemGenerated
	FROM
	
	(SELECT fs.RowID, fs.DepartmentID, fs.AccountID, fs.FiscalYearID, fs.FiscalMonthID, fs.TimeClassID, fs.Amount, fs.AmountYTD, fs.AmountPriorYear, fs.AmountPriorYTD, cast(fs.IsSystemGenerated as int) as IsSystemGenerated
	 FROM [fw].[FactStatisticSampledMonthly] fs
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID
	 WHERE cfg.Revenue = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0
	 AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID)
	 
	 UNION ALL
	 
	 SELECT mo.RowID, mo.DepartmentID, mo.AccountID, mo.FiscalYearID, mo.FiscalMonthID, mo.TimeClassID, mo.Amount, mo.AmountYTD, mo.AmountPriorYear, mo.AmountPriorYTD, cast(0 as int) as IsSystemGenerated
	 FROM [fw].[FactStatisticDriverDepartmentSampledMonthly] mo
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON mo.DepartmentID = cfg.DepartmentID AND mo.AccountID = cfg.AccountID
	 WHERE cfg.Revenue = 1 AND mo.IsDeleted = 0 AND cfg.IsDeleted = 0) allData
	 
	 GROUP BY [RowID], [DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID]
GO


---------------------------------------------

-- fw.viewPrimaryStatisticsRollupNonStaffingExpenseMonthly
CREATE VIEW [fw].[viewPrimaryStatisticsRollupNonStaffingExpenseMonthly]
AS
	SELECT 
		cfg.RollupLevel,
		cfg.RollupMemberID,
		fs.AccountID,
		fs.FiscalYearID,
		fs.FiscalMonthID,
		fs.TimeClassID,
		sum(fs.Amount) as Amount,
		sum(fs.AmountYTD) as AmountYTD,
		sum(fs.AmountPriorYear) as AmountPriorYear,
		sum(fs.AmountPriorYTD) as AmountPriorYTD,
		min(cast(fs.IsSystemGenerated AS INT)) AS IsSystemGenerated
	FROM [fw].[FactStatisticSampledMonthly] fs
	INNER JOIN fw.DimDepartment dd ON fs.DepartmentID = dd.DepartmentID
	INNER JOIN fw.PrimaryStatisticsRollupsConfiguration cfg ON (
			(cfg.RollupLevel = 'DepartmentRollup1' AND cfg.RollupMemberID = dd.DepartmentRollup1ID)
			OR (cfg.RollupLevel = 'DepartmentRollup2' AND cfg.RollupMemberID = dd.DepartmentRollup2ID)
			OR (cfg.RollupLevel = 'DepartmentRollup3' AND cfg.RollupMemberID = dd.DepartmentRollup3ID)
			OR (cfg.RollupLevel = 'DepartmentRollup4' AND cfg.RollupMemberID = dd.DepartmentRollup4ID)
			OR (cfg.RollupLevel = 'DepartmentRollup5' AND cfg.RollupMemberID = dd.DepartmentRollup5ID)
			OR (cfg.RollupLevel = 'DepartmentRollup6' AND cfg.RollupMemberID = dd.DepartmentRollup6ID)
			OR (cfg.RollupLevel = 'Entity' AND cfg.RollupMemberID = dd.EntityID)
			OR (cfg.RollupLevel = 'System' AND cfg.RollupMemberID = dd.SystemID)
			)		AND fs.AccountID = cfg.AccountID
	WHERE cfg.NonStaffing = 1
		AND fs.IsDeleted = 0
		AND IsMRMetricTracking = 1
	GROUP BY 
		cfg.RollupLevel,
		cfg.RollupMemberID,
		fs.AccountID,
		fs.FiscalYearID,
		fs.FiscalMonthID,
		fs.TimeClassID
GO


---------------------------------------------

-- fw.viewPrimaryStatisticsRollupRevenueMonthly
CREATE VIEW [fw].[viewPrimaryStatisticsRollupRevenueMonthly]
AS
SELECT 	cfg.RollupLevel,
	cfg.RollupMemberID,
	fs.AccountID,
	fs.FiscalYearID,
	fs.FiscalMonthID,
	fs.TimeClassID,
	sum(fs.Amount) as Amount,
	sum(fs.AmountYTD) as AmountYTD,
	sum(fs.AmountPriorYear) as AmountPriorYear,
	sum(fs.AmountPriorYTD) as AmountPriorYTD,
	min(cast(fs.IsSystemGenerated AS INT)) AS IsSystemGenerated
FROM [fw].[FactStatisticSampledMonthly] fs
INNER JOIN fw.DimDepartment dd ON fs.DepartmentID = dd.DepartmentID
INNER JOIN fw.PrimaryStatisticsRollupsConfiguration cfg ON (
		(cfg.RollupLevel = 'DepartmentRollup1' AND cfg.RollupMemberID = dd.DepartmentRollup1ID)
		OR (cfg.RollupLevel = 'DepartmentRollup2' AND cfg.RollupMemberID = dd.DepartmentRollup2ID)
		OR (cfg.RollupLevel = 'DepartmentRollup3' AND cfg.RollupMemberID = dd.DepartmentRollup3ID)
		OR (cfg.RollupLevel = 'DepartmentRollup4' AND cfg.RollupMemberID = dd.DepartmentRollup4ID)
		OR (cfg.RollupLevel = 'DepartmentRollup5' AND cfg.RollupMemberID = dd.DepartmentRollup5ID)
		OR (cfg.RollupLevel = 'DepartmentRollup6' AND cfg.RollupMemberID = dd.DepartmentRollup6ID)
		OR (cfg.RollupLevel = 'Entity' AND cfg.RollupMemberID = dd.EntityID)
		OR (cfg.RollupLevel = 'System' AND cfg.RollupMemberID = dd.SystemID)
		)
	AND fs.AccountID = cfg.AccountID
WHERE cfg.Revenue = 1
	AND fs.IsDeleted = 0
	AND IsMRMetricTracking = 1
GROUP BY 
	cfg.RollupLevel,
	cfg.RollupMemberID,
	fs.AccountID,
	fs.FiscalYearID,
	fs.FiscalMonthID,
	fs.TimeClassID
GO


---------------------------------------------

-- fw.viewPrimaryStatisticsRollupStaffingMonthly
CREATE VIEW [fw].[viewPrimaryStatisticsRollupStaffingMonthly]
AS
	SELECT 	cfg.RollupLevel,
	cfg.RollupMemberID,
	fs.AccountID,
	fs.FiscalYearID,
	fs.FiscalMonthID,
	fs.TimeClassID,
	sum(fs.Amount) as Amount,
	sum(fs.AmountYTD) as AmountYTD,
	sum(fs.AmountPriorYear) as AmountPriorYear,
	sum(fs.AmountPriorYTD) as AmountPriorYTD,
	min(cast(fs.IsSystemGenerated AS INT)) AS IsSystemGenerated
	FROM [fw].[FactStatisticSampledMonthly] fs
	INNER JOIN fw.DimDepartment dd ON fs.DepartmentID = dd.DepartmentID
	INNER JOIN fw.PrimaryStatisticsRollupsConfiguration cfg ON (
			(cfg.RollupLevel = 'DepartmentRollup1' AND cfg.RollupMemberID = dd.DepartmentRollup1ID)
			OR (cfg.RollupLevel = 'DepartmentRollup2' AND cfg.RollupMemberID = dd.DepartmentRollup2ID)
			OR (cfg.RollupLevel = 'DepartmentRollup3' AND cfg.RollupMemberID = dd.DepartmentRollup3ID)
			OR (cfg.RollupLevel = 'DepartmentRollup4' AND cfg.RollupMemberID = dd.DepartmentRollup4ID)
			OR (cfg.RollupLevel = 'DepartmentRollup5' AND cfg.RollupMemberID = dd.DepartmentRollup5ID)
			OR (cfg.RollupLevel = 'DepartmentRollup6' AND cfg.RollupMemberID = dd.DepartmentRollup6ID)
			OR (cfg.RollupLevel = 'Entity' AND cfg.RollupMemberID = dd.EntityID)
			OR (cfg.RollupLevel = 'System' AND cfg.RollupMemberID = dd.SystemID)
			)
		AND fs.AccountID = cfg.AccountID
	WHERE cfg.Staffing = 1
		AND fs.IsDeleted = 0
		AND IsMRMetricTracking = 1		
	GROUP BY 
		cfg.RollupLevel,
		cfg.RollupMemberID,
		fs.AccountID,
		fs.FiscalYearID,
		fs.FiscalMonthID,
		fs.TimeClassID
GO


---------------------------------------------

-- fw.viewPrimaryStatisticsStaffingByPayPeriod
CREATE view [fw].[viewPrimaryStatisticsStaffingByPayPeriod] as 

	SELECT [DepartmentID], [AccountID], [PayPeriodID], [TimeClassID], SUM([Units]) as Units, SUM([UnitsYTD]) as UnitsYTD, SUM([UnitsPriorYear]) as UnitsPriorYear, SUM([UnitsPriorYTD]) as UnitsPriorYTD, MAX([RowID]) as RowID, cast(MAX(cast([IsDeleted] as int)) as bit) as IsDeleted, cast(MIN([IsSystemGenerated]) as bit) as IsSystemGenerated
	FROM
	
	(SELECT fs.DepartmentID, fs.AccountID, fs.PayPeriodID, fs.TimeClassID, fs.Units, fs.UnitsYTD, fs.UnitsPriorYear, fs.UnitsPriorYTD, fs.RowID, fs.IsDeleted, cast(fs.IsSystemGenerated as int) as IsSystemGenerated
	 FROM [fw].[FactStatisticSampledPayPeriod] fs
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID
	 WHERE cfg.Staffing = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0
	 AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID)
	 
	 UNION ALL
	 
	 SELECT pp.DepartmentID, pp.AccountID, pp.PayPeriodID, pp.TimeClassID, pp.Units, pp.UnitsYTD, pp.UnitsPriorYear, pp.UnitsPriorYTD, pp.RowID, pp.IsDeleted, cast(0 as int) as IsSystemGenerated
	 FROM [fw].[FactStatisticDriverDepartmentSampledPayPeriod] pp
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON pp.DepartmentID = cfg.DepartmentID AND pp.AccountID = cfg.AccountID
	 WHERE cfg.Staffing = 1 AND pp.IsDeleted = 0 AND cfg.IsDeleted = 0) allData
	 
	 GROUP BY [DepartmentID], [AccountID], [PayPeriodID], [TimeClassID]
GO


---------------------------------------------

-- fw.viewPrimaryStatisticsStaffingDaily
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI			  Description
** 1      2016-04-22  gforeman            initial implementation
** 2      2022-07-28  BS      JAZZ-39738  Daily flexing - Payroll Hours and Dollars
** 3      2024-02-16  KF      JAZZ-67769  Add BigRowID to fw.FactStatisticSampledDaily and fw.viewPrimaryStatisticsStaffingDaily
*************************************************************/
CREATE view [fw].[viewPrimaryStatisticsStaffingDaily]
as 
	SELECT [DepartmentID], [AccountID], [PayPeriodID], [DateID], [TimeClassID], SUM([Units]) as Units, MAX([RowID]) as RowID, cast(MAX(cast([IsDeleted] as int)) as bit) as IsDeleted, CAST(MAX(RowID) AS BIGINT) as BigRowID
	FROM
	
	(SELECT fs.DepartmentID, fs.AccountID, fs.PayPeriodID, fs.DateID, fs.TimeClassID, fs.Units, fs.RowID, fs.IsDeleted
	 FROM [fw].[FactStatisticSampledDaily] fs
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID
	 WHERE cfg.Staffing = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0
	 AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID)
	 
	 UNION ALL
	 
	 SELECT pp.DepartmentID, pp.AccountID, pp.PayPeriodID, pp.DateID, pp.TimeClassID, pp.Units, pp.RowID, pp.IsDeleted
	 FROM [fw].[FactStatisticDriverDepartmentSampledDaily] pp
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON pp.DepartmentID = cfg.DepartmentID AND pp.AccountID = cfg.AccountID
	 WHERE cfg.Staffing = 1 AND pp.IsDeleted = 0 AND cfg.IsDeleted = 0) allData
	 
	 GROUP BY [DepartmentID], [AccountID], [PayPeriodID], [DateID], [TimeClassID]
GO


---------------------------------------------

-- fw.viewPrimaryStatisticsStaffingMonthly
-- primary statistics (by month) staffing driver accounts
CREATE view [fw].[viewPrimaryStatisticsStaffingMonthly] as 

	SELECT [RowID], [DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID], SUM([Amount]) as Amount, SUM([AmountYTD]) as AmountYTD, SUM([AmountPriorYear]) as AmountPriorYear, SUM([AmountPriorYTD]) as AmountPriorYTD, cast(0 as bit) as IsDeleted, cast(MIN([IsSystemGenerated]) as bit) as IsSystemGenerated
	FROM
	
	(SELECT fs.RowID, fs.DepartmentID, fs.AccountID, fs.FiscalYearID, fs.FiscalMonthID, fs.TimeClassID, fs.Amount, fs.AmountYTD, fs.AmountPriorYear, fs.AmountPriorYTD, cast(fs.IsSystemGenerated as int) as IsSystemGenerated
	 FROM [fw].[FactStatisticSampledMonthly] fs
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID
	 WHERE cfg.Staffing = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0
	 AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID)
	 
	 UNION ALL
	 
	 SELECT mo.RowID, mo.DepartmentID, mo.AccountID, mo.FiscalYearID, mo.FiscalMonthID, mo.TimeClassID, mo.Amount, mo.AmountYTD, mo.AmountPriorYear, mo.AmountPriorYTD, cast(0 as int) as IsSystemGenerated
	 FROM [fw].[FactStatisticDriverDepartmentSampledMonthly] mo
	   INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON mo.DepartmentID = cfg.DepartmentID AND mo.AccountID = cfg.AccountID
	 WHERE cfg.Staffing = 1 AND mo.IsDeleted = 0 AND cfg.IsDeleted = 0) allData
	 
	 GROUP BY [RowID], [DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID]
GO


---------------------------------------------

-- fw.viewReportCurrentUsers
CREATE VIEW [fw].[viewReportCurrentUsers] AS
	SELECT DISTINCT up.NameFirst, up.NameLast, up.PhoneNumber, CASE WHEN MIN(DATEDIFF(MI, LastActionStampUtc, GETUTCDATE())) < 0 THEN 0 ELSE MIN(DATEDIFF(MI, LastActionStampUtc, GETUTCDATE())) END AS InactiveMinutes   
	FROM CurrentUser cu INNER JOIN [dbo].[UserProfile] up 
	ON cu.UserGUID = up.UserGUID
	WHERE tokentype = 0
	GROUP BY up.NameFirst, up.NameLast, up.PhoneNumber
	HAVING up.NameFirst IS NOT NULL
GO


---------------------------------------------

-- fw.viewReportDimensionExceptions
CREATE VIEW [fw].[viewReportDimensionExceptions]
AS
select AccountCode As DataMember, 'Account' As Identifier, 'fw.DimAccount' As Source, 'Blank Description or Blank GL Rollup' As Explanation, trans.Files As FilePath, trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimAccount acct inner join [dbo].[viewIntTransaction] trans on acct.TransactionID = trans.TransactionID 
where Description='' or GLRollup=''
union
select AccountCode As DataMember, 'Account' As Identifier, 'fw.DimAccount' As Source, 'Blank Account Code'  As Explanation, trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimAccount acct inner join [dbo].[viewIntTransaction] trans on acct.TransactionID = trans.TransactionID 
where AccountCode=''
union
select Description As DataMember, 'Account' As Identifier, 'fw.DimAccount' As Source, 'Modified Zero member Description'  As Explanation, trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimAccount acct inner join [dbo].[viewIntTransaction] trans on acct.TransactionID = trans.TransactionID 
where AccountID=0 and Description<>'Not Specified'
union
select Code As DataMember, 'Entity' As Identifier, 'fw.DimEntity' As Source, 'Blank Description'  As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimEntity Ent inner join [dbo].[viewIntTransaction] trans on Ent.TransactionID = trans.TransactionID 
where Description=''
union
select Code As DataMember, 'Entity' As Identifier, 'fw.DimEntity' As Source, 'Blank Entity Code'  As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimEntity Ent inner join [dbo].[viewIntTransaction] trans on Ent.TransactionID = trans.TransactionID 
where Code='' 
union
select Description As DataMember, 'Entity' As Identifier, 'fw.DimEntity' As Source, 'Modified Zero member Description'  As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimEntity Ent inner join [dbo].[viewIntTransaction] trans on Ent.TransactionID = trans.TransactionID 
where Ent.EntityID = 0 and ent.Description<>'Not Specified'
union
select DepartmentCode As DataMember, 'Department' As Identifier, 'fw.DimDepartment' As Source, 'Blank Description'  As Explanation  , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimDepartment dept inner join [dbo].[viewIntTransaction] trans on dept.TransactionID = trans.TransactionID 
where Dept.Description=''
union
select DepartmentCode As DataMember, 'Department' As Identifier, 'fw.DimDepartment' As Source, 'Blank Department Code'  As Explanation , trans.Files As FilePath ,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimDepartment dept inner join [dbo].[viewIntTransaction] trans on dept.TransactionID = trans.TransactionID 
where Dept.Departmentcode=''
union
select DepartmentCode As DataMember, 'Department' As Identifier, 'fw.DimDepartment' As Source, 'Entity Not Assigned'  As Explanation  , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimDepartment dept inner join [dbo].[viewIntTransaction] trans on dept.TransactionID = trans.TransactionID 
where Dept.EntityID=0 and Dept.DepartmentID<>0
union
select Description As DataMember, 'Department' As Identifier, 'fw.DimDepartment' As Source, 'Modified Zero member Description'  As Explanation  , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimDepartment dept inner join [dbo].[viewIntTransaction] trans on dept.TransactionID = trans.TransactionID 
where DepartmentID=0 and (Description<>'Not Specified' or EntityID<>0)
union
select JobCode As DataMember, 'Job Code' As Identifier, 'fw.DimJobCode' As Source, 'Blank Description'  As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimJobCode JC inner join [dbo].[viewIntTransaction] trans on JC.TransactionID = trans.TransactionID 
where Description=''
union
select JobCode As DataMember, 'Job Code' As Identifier, 'fw.DimJobCode' As Source, 'Blank Job Code'  As Explanation , trans.Files As FilePath ,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimJobCode JC inner join [dbo].[viewIntTransaction] trans on JC.TransactionID = trans.TransactionID 
where JobCode=''
union
select Description As DataMember, 'Job Code' As Identifier, 'fw.DimJobCode' As Source, 'Modified Zero member Description'  As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimJobCode JC inner join [dbo].[viewIntTransaction] trans on JC.TransactionID = trans.TransactionID 
where JobCodeID=0 and Description<>'Not Specified'
union
select PayCode As DataMember, 'Pay Code' As Identifier, 'fw.DimPayCode' As Source, 'Blank Description'  As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimPayCode PC inner join [dbo].[viewIntTransaction] trans on PC.TransactionID = trans.TransactionID 
where Description=''
union
select PayCode As DataMember, 'Pay Code' As Identifier, 'fw.DimPayCode' As Source, 'Blank Pay Code'  As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimPayCode PC inner join [dbo].[viewIntTransaction] trans on PC.TransactionID = trans.TransactionID 
where PayCode=''
union
select Description As DataMember, 'Pay Code' As Identifier, 'fw.DimPayCode' As Source, 'Modified Zero member Description'  As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimPayCode PC inner join [dbo].[viewIntTransaction] trans on PC.TransactionID = trans.TransactionID 
where PayCodeID=0 and Description<>'Not Specified'
union
select Number As DataMember, 'Employee' As Identifier, 'fw.DimEmployee' As Source, 'Blank First Name or Blank Last Name'  As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimEmployee emp inner join [dbo].[viewIntTransaction] trans on emp.TransactionID = trans.TransactionID 
where NameFirst='' or NameLast=''
union
select Number As DataMember, 'Employee' As Identifier, 'fw.DimEmployee' As Source, 'Blank Employee Number'  As Explanation, trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimEmployee emp inner join [dbo].[viewIntTransaction] trans on emp.TransactionID = trans.TransactionID 
where Number=''
union
select Number As DataMember, 'Employee' As Identifier, 'fw.DimEmployee' As Source, 'Job Code not set for Employee'  As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimEmployee emp inner join [dbo].[viewIntTransaction] trans on emp.TransactionID = trans.TransactionID 
where JobCodeID=0 and EmployeeID<>0
union
select Name  As DataMember, 'Employee' As Identifier, 'fw.DimEmployee' As Source, 'Modified Zero member Description'  As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from fw.DimEmployee emp inner join [dbo].[viewIntTransaction] trans on emp.TransactionID = trans.TransactionID 
where EmployeeID=0 and Name<>'Not Specified [0] (UNKNWN)'
union
select Code As DataMember, 'Fund' As Identifier, 'fw.DimFund' As Source, 'Blank Description'  As Explanation  , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from [fw].[DimFund] DF inner join [dbo].[viewIntTransaction] trans on DF.TransactionID = trans.TransactionID 
where Description=''
union
select Code As DataMember, 'Fund' As Identifier, 'fw.DimFund' As Source, 'Blank Fund Code'  As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username  As UserName, trans.ConfigName as IntegrationConfig
from [fw].[DimFund] DF inner join [dbo].[viewIntTransaction] trans on DF.TransactionID = trans.TransactionID 
where Code=''
union
select Description As DataMember, 'Fund' As Identifier, 'fw.DimFund' As Source, 'Modified Zero member Description'  As Explanation  , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from [fw].[DimFund] DF inner join [dbo].[viewIntTransaction] trans on DF.TransactionID = trans.TransactionID 
where FundID=0 and (Description<>'Not Specified')
union
select Code As DataMember, 'Project' As Identifier, 'fw.DimProject' As Source, 'Blank Description'  As Explanation  , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from [fw].[DimProject] DP inner join [dbo].[viewIntTransaction] trans on DP.TransactionID = trans.TransactionID 
where Description=''
union
select Code As DataMember, 'Project' As Identifier, 'fw.DimProject' As Source, 'Blank Project Code'  As Explanation  , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from [fw].[DimProject] DP inner join [dbo].[viewIntTransaction] trans on DP.TransactionID = trans.TransactionID 
where Code=''
union
select Description As DataMember, 'Project' As Identifier, 'fw.DimProject' As Source, 'Modified Zero member Description'  As Explanation  , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from [fw].[DimProject] DP inner join [dbo].[viewIntTransaction] trans on DP.TransactionID = trans.TransactionID 
where ProjectID=0 and (Description<>'Not Specified')
union
select Code As DataMember, 'Program' As Identifier, 'fw.DimProgram' As Source, 'Blank Description'  As Explanation  , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from [fw].DimProgram Prog inner join [dbo].[viewIntTransaction] trans on Prog.TransactionID = trans.TransactionID 
where Description=''
union
select Code As DataMember, 'Program' As Identifier, 'fw.DimProgram' As Source, 'Blank Program Code'  As Explanation  , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from [fw].DimProgram Prog inner join [dbo].[viewIntTransaction] trans on Prog.TransactionID = trans.TransactionID 
where Code=''
union
select Description As DataMember, 'Program' As Identifier, 'fw.DimProgram' As Source, 'Modified Zero member Description'  As Explanation  , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from [fw].DimProgram Prog inner join [dbo].[viewIntTransaction] trans on Prog.TransactionID = trans.TransactionID 
where ProgramID=0 and (Description<>'Not Specified')
union
select Code As DataMember, 'Home Department' As Identifier, 'fw.DimHomeDepartment' As Source, 'Blank Description'  As Explanation , trans.Files As FilePath ,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from [fw].[DimHomeDepartment] HD inner join [dbo].[viewIntTransaction] trans on HD.TransactionID = trans.TransactionID 
where Description=''
union
select Code As DataMember, 'Home Department' As Identifier, 'fw.DimHomeDepartment' As Source, 'Blank Program Code'  As Explanation  , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from [fw].[DimHomeDepartment] HD inner join [dbo].[viewIntTransaction] trans on HD.TransactionID = trans.TransactionID 
where Code=''
union
select Description As DataMember, 'Home Department' As Identifier, 'fw.DimHomeDepartment' As Source, 'Modified Zero member Description'  As Explanation  , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig
from [fw].[DimHomeDepartment] HD inner join [dbo].[viewIntTransaction] trans on HD.TransactionID = trans.TransactionID 
where HomeDepartmentID=0 and (Description<>'Not Specified')
GO


---------------------------------------------

-- fw.viewReportDirectoryActionHistory
CREATE VIEW [fw].[viewReportDirectoryActionHistory]
AS

select 
	case when SubAction like 'Initial Load -%' 
		then 'Initial Load'
	else 
		replace(SubAction, 'Grid Action - ', '')
	End as SubAction,
	Username,
	YEAR(datetimestamp) as [Year],
	MONTH(datetimestamp) as [Month],
	DateTimeStamp,
	Duration,
	1 as [Count]
from ActionLog 
where [Action] = 'Directory20' and SubAction not in ('RefreshTabNames', 'Grid Action - init')
GO


---------------------------------------------

-- fw.viewReportExceptionSummary
create view [fw].[viewReportExceptionSummary]
as
	select
		ReportName,
		ExceptionCount
	from
		fw.FactReportException
GO


---------------------------------------------

-- fw.viewReportFactGLConsolidated
CREATE view [fw].[viewReportFactGLConsolidated] as 

	
	select
		S.DepartmentID
		,S.AccountID
		,S.TimeClassID
		,S.FiscalYearID
		,S.FiscalMonthID
		,(s.Units) as Units
		,(s.UnitsYTD) as UnitsYTD
		,(s.UnitsPriorYear) as UnitsPriorYear
		,(S.UnitsPriorYTD) as UnitsPriorYTD
		,(s.Dollars) as Dollars
		,(S.DollarsYTD) as DollarsYTD
		,(S.DollarsPriorYear) as DollarsPriorYear
		,(S.DollarsPriorYTD) as DollarsPriorYTD
	from 
		fw.FactGLSampled S

	where 
		s.IsDeleted = 0
GO


---------------------------------------------

-- fw.viewReportFactPayrollMonthlyConsolidated
CREATE view [fw].[viewReportFactPayrollMonthlyConsolidated] as 


	select
		DepartmentID, 
		JobCodeID, 
		PayCodeID, 
		FiscalYearID, 
		FiscalMonthID, 
		TimeClassID,
		(Hours) as Hours, 
		(HoursYTD) as HoursYTD, 
		(HoursPriorYear) as HoursPriorYear, 
		(HoursPriorYTD) as HoursPriorYTD, 
		(Dollars) as Dollars,
		(DollarsYTD) as DollarsYTD, 
		(DollarsPriorYear) as DollarsPriorYear, 
		(DollarsPriorYTD) as DollarsPriorYTD
	from 
		fw.FactPayrollSampledMonthly S
	where 
		s.IsDeleted = 0
GO


---------------------------------------------

-- fw.viewReportFactStatMonthlyConsolidated
CREATE view [fw].[viewReportFactStatMonthlyConsolidated] as 


	select
		DepartmentID, 
		AccountID, 
		FiscalYearID, 
		FiscalMonthID, 
		TimeClassID,
		Amount,
		AmountYTD, 
		AmountPriorYear, 
		AmountPriorYTD
	from 
		fw.FactStatisticSampledMonthly S
	where 
		s.IsDeleted = 0
		and (Amount <> 0 or AmountYTD <> 0 or AmountPriorYear <> 0 or AmountPriorYTD <> 0)
GO


---------------------------------------------

-- fw.viewReportFactStatPayPeriodConsolidated
CREATE view [fw].[viewReportFactStatPayPeriodConsolidated] as 


	select
		DepartmentID, 
		AccountID, 
		TimeClassID, 
		PayPeriodID,
		Units
	from 
		fw.FactStatisticSampledPayPeriod S
	where 
		s.IsDeleted = 0
		and Units <> 0
GO


---------------------------------------------

-- fw.viewReportGeneralConsolidatedFinancialReporting
create view [fw].[viewReportGeneralConsolidatedFinancialReporting] as

/************************************************************
** Author:  FW Dev
** Create Date:  akowalski
** Description:  Generates the list of Consolidated financial reporting members for expanding reports
** Last Modified: 2013-03-26
** GM Release: Lightningbug
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

select
	ConsolidatedFinancialReportingID
from 
	[fw].[DimConsolidatedFinancialReporting]
GO


---------------------------------------------

-- fw.viewReportGroupAssignment
create view fw.viewReportGroupAssignment
as
select 
	UP.NameLast as [LastName],
	UP.NameFirst as [FirstName],
	UP.UserName as [UserName],
	UP.EmailAddress as [EmailAddress],
	G.UserGroupName
from UserProfile UP
inner join viewS3GroupAssignment G on G.UserGUID = UP.UserGUID
GO


---------------------------------------------

-- fw.viewReportLockedPlans
CREATE VIEW fw.viewReportLockedPlans
AS
SELECT     
	dbo.GetPlanName(L.ItemGUID) AS PlanName, 
	PT.Name As PlanType,
	TEM.Name AS ModelTemplate, 
	CAST(L.DateLocked AS varchar(30)) AS LockDate, 
	CAST(L.DateLastActive AS varchar(30)) AS LastActive, 
	COALESCE (UP.NameFirst + ' ' + UP.NameLast, '') AS UserName
FROM         
	dbo.Lock AS L LEFT OUTER JOIN
    dbo.UserProfile AS UP ON L.UserGUID = UP.UserGUID LEFT OUTER JOIN
    dbo.XPlan AS X ON X.PlanGUID = L.ItemGUID LEFT OUTER JOIN
	[dbo].[PlanType] as PT on PT.PlanTypeGUID=X.PlanTypeGUID LEFT OUTER JOIN
	dbo.EMFModelTemplate AS TEM ON X.ModelTemplateGUID = TEM.ModelTemplateGUID
WHERE     (L.LockGroup = 'PlanLock') and X.IsDeletedPlan=0
GO


---------------------------------------------

-- fw.viewReportPayPeriod
CREATE VIEW [fw].[viewReportPayPeriod] AS 
	SELECT 
		m.CalendarDaysSecond,
		m.CalendarDaysStart,		
		m.DaysInPeriodWeightSecond,
		m.DaysInPeriodWeightStart,
		m.FiscalMonthIDSecond,
		m.FiscalMonthIDStart,
		m.FiscalYearIDSecond,
		m.FiscalYearIDStart,
		m.PayPeriodCode,
		m.Name as PayPeriod,
		m.PayPeriodID,
		m.PayPeriodID as ReportingPayPeriodID,
		m.PeriodDays,
		m.PeriodDaysSecond,
		m.PeriodDaysStart,
		m.PeriodEndCalendarDate,
		m.PeriodEndCalendarDate as DateEnd,
		m.PeriodNumber,
		m.PeriodStartCalendarDate,
		m.PeriodWeightSecond,
		m.PeriodWeightStart
	FROM 
		fw.DimPayPeriod m
GO


---------------------------------------------

-- fw.viewReportReportRunHistory
CREATE VIEW [fw].[viewReportReportRunHistory]
AS

select 
	L.Username as [User Name],
	case L.Action
		when 'ZEROVIEWER' then 'Excel'
		when 'Excel Reporter' then 'Excel'
		when 'SQL Report' then 'SQL'
		else 'Not Specified'
	end as [Report Type],		
	replace(coalesce(R.Name, L.SubAction) , 'BATCH_', '')as [Report Name],
	L.DatetimeStamp as [Launch Time],
	L.Duration/1000 as [Duration in Seconds]
from 
	ActionLog L 
	inner join REReport R on RIGHT(L.SubAction, 36) = cast(R.ReportGUID as nvarchar(36)) or replace(L.SubAction, 'BATCH_', '')=R.Name
where 
	L.Action in ('ZEROVIEWER', 'Excel Reporter', 'SQL Report')	
	and L.SubAction not like 'DrillDown%'

union all

select 
	UserName as [User Name],
	'Excel' as [Report Type],
	ReportName as [Report Name],
	LaunchTime as [Launch Time],
	datediff(ss, LaunchTime, FinishTime) as [Duration in Seconds]
from (
	select 
		modifierusername as UserName,
		replace(usercomments, 'BATCH_', '') as ReportName,
		max(case when [Description]='Report Created' then datetimestamp else null end) as LaunchTime,
		max(case when [Description]='Report Deleted' then datetimestamp else null end) as FinishTime
	from historyitem
	where category='Report Action' and UserComments like 'BATCH_%' 
	group by modifierusername, usercomments
	) P
GO


---------------------------------------------

-- fw.viewReportSecurityDetail
--==========================================================================================


CREATE view [fw].[viewReportSecurityDetail] as 

SELECT 
	E.NAME AS ModelTemplate,
	P.NAME AS Plans,
	P.planguid,
	U.NameFull as UserName,
	ROLENAME AS UserRole,
	DET.RoleID as UserRoleID,
	CASE  
		WHEN IdentityName = U.NAMELAST+', '+U.NAMEFIRST THEN 'Direct'
		ELSE IDENTITYNAME END AS GROUPNAME
FROM VIEWS3ROLEASSIGNMENTDETAIL DET
INNER JOIN VIEWPLANS P ON DET.LOOTID = P.CachedLootID
INNER JOIN EMFMODELTEMPLATE E ON P.MODELTEMPLATEGUID = E.MODELTEMPLATEGUID
INNER JOIN UserProfile U on U.UserGUID = DET.UserGUID
GO


---------------------------------------------

-- fw.viewReportSystemSectionSecurity
CREATE view [fw].[viewReportSystemSectionSecurity] as 


SELECT 
	SS.NAME AS SYSTEMSECTION,
	SS.FULLPATH,
	DET.USERNAME,
	ROLENAME AS USERROLE,
	CASE  
		WHEN IdentityName = p.NAMELAST+', '+p.NAMEFIRST THEN ''
		ELSE IDENTITYNAME END AS GROUPNAME
FROM VIEWS3ROLEASSIGNMENTDETAIL DET (readuncommitted)
INNER JOIN SystemSection SS(readuncommitted) ON DET.LOOTID = SS.LOOTID
inner join [dbo].[UserProfile] p on DET.UserGUID=p.UserGUID
GO


---------------------------------------------

-- fw.viewReportSystemSectionSecuritybySection
create view [fw].[viewReportSystemSectionSecuritybySection] as 

select 
	ss.Area, 
	ss.Section, 
	ss.Name as [System Section], 
	ur.NAME as Role, 
	case when G.NAME is null then u.NameFull else g.NAME end as [Group or User]
from [fw].[viewDimSystemSection] ss
inner join [dbo].[S3RoleAssignment] ra on ss.LootID=ra.LootGroupID
inner join [dbo].[UserRole] ur on ur.RoleID=ra.RoleID
left join [dbo].[UserGroup] G on G.USERGROUPGUID=ra.IdentityGUID
left join [dbo].[UserProfile] u on u.USERGUID=ra.IdentityGUID
GO


---------------------------------------------

-- fw.viewReportSystemUsers
CREATE VIEW [fw].[viewReportSystemUsers] AS

SELECT UP.*,
	ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) AS IsSysAdmin
from userprofile UP
left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator')
GO


---------------------------------------------

-- fw.viewReportUserLastLogin
create view [fw].[viewReportUserLastLogin]
as
	select Name, LastLogin, NumLogins
	from viewuserloginhistory
	where lastlogin > '2010-01-01'
GO


---------------------------------------------

-- fw.viewReportUserLoginHistory
create view [fw].[viewReportUserLoginHistory] as


select 
Name,
LastLogin,
cast(DATEDIFF(day,LastLogin,CURRENT_TIMESTAMP) as float) as DaysSinceLogin 
from dbo.viewUserLoginHistory 
where Name NOT LIKE '%zStrata%'
GO


---------------------------------------------

-- fw.viewReportWorkflowSignoffs
CREATE view [fw].[viewReportWorkflowSignoffs]
as
	select
		RV.EntityGUID as PlanGUID,
		E.EntityName as Plans,
		WFM.Name as WorkflowMapName,
		WFS.Name as WorkflowStepName,
		UP.NameFull as ReviewerName,
		RVT.Name as ReviewValue,
		RV.Comments,
		cast(WFP.DisplayOrder as nvarchar(8)) + '\' + cast(WFS.DisplayOrder as nvarchar(8)) as DisplayOrder,
		E.CachedLootID as LootID
	from
		WFReviewValue RV
		inner join dbo.viewWFEntity E on E.EntityGUID = RV.EntityGUID
		inner join UserProfile UP on UP.UserGUID = RV.IdentityGUID
		inner join WFReviewValueType RVT on RVT.ReviewValueTypeGUID = RV.ReviewValueTypeGUID
		inner join WFWorkflowStep WFS on WFS.WorkflowStepGUID = RV.WorkflowStepGUID
		inner join WFProcessStepLink WFL on WFL.WorkflowStepGUID = WFS.WorkflowStepGUID
		inner join WFProcess WFP on WFP.ProcessGUID = WFL.ProcessGUID
		inner join WFWorkflowMap WFM on WFM.WorkflowMapGUID = WFS.WorkflowMapGUID
GO


---------------------------------------------

-- fw.viewSectionSecurityImport
CREATE VIEW [fw].[viewSectionSecurityImport]
as
select 
	case when SSI.GroupName = 'None' then 'Strata Administrator' else SSI.GroupName end as GroupName,
	'Basic' as SectionType,
	'Global' as Parent,
	SS.Name,
	SS.SystemSectionGUID
from 
	fw.SectionSecurityImport SSI
	inner join SystemSection SS on SS.SystemSectionGUID = SSI.BasicGUID
union all
select 
	case when SSI.GroupName = 'None' then 'Strata Administrator' else SSI.GroupName end as GroupName,
	'Advanced' as SectionType,
	SSP.Name as Parent,
	SS.Name,
	SS.SystemSectionGUID
from 
	fw.SectionSecurityImport SSI
	inner join SystemSection SS on SS.SystemSectionGUID = SSI.AdvancedGUID
	left join SystemSection SSP on SSP.SystemSectionGUID = SS.ParentGUID
GO


---------------------------------------------

-- fw.viewStatisticPrimaryConfiguration
/************************************************************
** Author: jgerber
** Create Date: 2013-11-06
** Description: View for Primary Statistic Driver (Defaults using the Primary Statistic Config)
** Last Modified: 2013-11-06
** GM Release: 2013-11-18
**************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
**	1		01.08.16	MJS			D-03823	Added filter: IsDeleted=0
**	2		2020-01-30	KF			D-09156	Accounts being excluded from metrics when using non staffing expenses
*************************************************************/
CREATE VIEW [fw].[viewStatisticPrimaryConfiguration]

as 
select 
		DepartmentID, 
		AccountID
from 
		[client].[FactDepartmentPrimaryStatisticConfiguration]
where
		(Revenue=1 OR Staffing=1 OR NonStaffingExpense=1)
		and IsDeleted=0
GO


---------------------------------------------

-- fw.viewStatisticSecondaryConfiguration
/************************************************************
** Author: jgerber
** Create Date: 2013-11-06
** Description: View for Secondary Statistic Driver (Defaults using the Secondary Statistic Config)
** Last Modified: 2013-11-06
** GM Release: 2013-11-18
**************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI			Description
**	1		01.08.16	MJS			D-03823	Added filter: IsDeleted=0
**	2		2020-01-30	KF			D-09156	Accounts being excluded from metrics when using non staffing expenses
*************************************************************/
CREATE VIEW [fw].[viewStatisticSecondaryConfiguration]

as 
--THIS IS EDITABLE
select 
		DepartmentID, 
		AccountID
from 
		[client].[FactDepartmentPrimaryStatisticConfiguration]
where	
		(Revenue=1 OR Staffing=1 OR NonStaffingExpense=1)
		and IsDeleted=0
GO


---------------------------------------------

---------------------------------------------
--  PROCEDURES
---------------------------------------------

-- fw.PrepareStatistics
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2018-06-04	IP 		TK-58587	re-applying changes  (2018-05-16  D-07187 Budget adjustment effecting historical budget fiscal years)
** 2		2024-12-23	HV 		JAZZ-81810	[Spike] - Analyze and cover with integration tests for JAZZ-81233: MR - Budget Adj is getting applied to all prior years
													Apply fix proposed by Scott Evens
*************************************************************/
CREATE PROCEDURE [fw].[PrepareStatistics] (@FiscalYearID int =0, @StatisticType tinyint)
as
	IF OBJECT_ID('tempdb..#StatisticTempTable') IS NOT NULL DROP TABLE #StatisticTempTable
	declare @iteration int = 1 
	create table #StatisticTempTable (
		DepartmentID int,
		AccountID int,
		FiscalYearID smallint,
		FiscalMonthID tinyint,
		TimeClassID tinyint,
		Amount numeric(25,4),
		ApplyDate datetime,
		Src varchar(max),
		UNIQUE NONCLUSTERED (DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID) 
)
	INSERT INTO #StatisticTempTable	(DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src)
	SELECT
		stat.DepartmentID,
		stat.AccountID,
		stat.FiscalYearID,
		stat.FiscalMonthID,
		stat.TimeClassID,
		sum(STAT.Value) as Amount,
		cast('1900-01-01' as datetime) as ApplyDate,
		cast('int_1' as varchar(max))+'V' as src
	from
		int.FactStatistic stat  
		inner join fw.DimDepartment D on D.Departmentid = STAT.Departmentid
	where 
		stat.IsDeleted = 0
		and stat.Value != 0
		and (stat.FiscalYearID = @FiscalYearID or @FiscalYearID = 0)
	Group by stat.DepartmentID,
		stat.AccountID,
		stat.FiscalYearID,
		stat.FiscalMonthID,
		stat.TimeClassID

--select count(*)	from #StatisticTempTable

DECLARE @BudgetReallocationGUID uniqueidentifier,@date datetime,@BudgetReallocationType varchar(50)

PRINT '-------- Vendor Products Report --------';  

DECLARE BRA_cursor CURSOR FOR   
SELECT distinct BudgetReallocationGUID,date,BudgetReallocationType from fw.BudgetReallocationWithDefinedType
WHERE (FiscalYearID = @FiscalYearID or @FiscalYearID = 0)
ORDER BY date;  

OPEN BRA_cursor  

FETCH NEXT FROM BRA_cursor   
INTO @BudgetReallocationGUID,@date,@BudgetReallocationType   

WHILE @@FETCH_STATUS = 0  
BEGIN  

--select @iteration,@BudgetReallocationGUID,@date,@BudgetReallocationType,* from #StatisticTempTable where DepartmentID = 359 and AccountID = 791 and FiscalYearID = 2015 and FiscalMonthID = 9 and TimeClassID = 2

	IF @BudgetReallocationType = 'ReallocateSingle'
	BEGIN -- Insert rows with "correcting" values 
		UPDATE STT
		SET Amount = Amount + Change,
		stt.ApplyDate = b.Date,
		src = SRC + '[Added_'+cast(Change as varchar(50))+'_from_'+cast(SourceDepartmentID as varchar(10))+']'
		FROM #StatisticTempTable STT
		INNER JOIN [mr].[BudgetReallocation] b ON b.TargetDepartmentID = stt.DepartmentID and b.TargetAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID  and stt.FiscalMonthID = ba.FiscalMonthID
		WHERE Change <> 0
			  and b.BudgetReallocationGUID = @BudgetReallocationGUID
			  and UnitTypeID = 145
			  and TimeClassID = 2

		UPDATE STT
		SET Amount = Amount - Change,
		stt.ApplyDate = b.Date,
		src = SRC + '[Removed_'+cast(Change as varchar(50))+'_to_'+cast(TargetDepartmentID as varchar(10))+']'
		FROM #StatisticTempTable STT
		INNER JOIN [mr].[BudgetReallocation] b ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID  and stt.FiscalMonthID = ba.FiscalMonthID
		WHERE Change <> 0
			  and b.BudgetReallocationGUID = @BudgetReallocationGUID
			  and UnitTypeID = 145
			  and TimeClassID = 2
			
		INSERT INTO #StatisticTempTable	(DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src)
		SELECT 
				b.SourceDepartmentID as DepartmentID,
				b.SourceAccountID as AccountID,
				b.FiscalYearID,
				ba.FiscalMonthID,
				2 as TimeclassID,		
				SUM(Change * -1) as Value,
				max(b.Date) as ApplyDate,
				'ra_1_m' as src
		FROM [mr].[BudgetReallocation] b
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		LEFT JOIN (select DepartmentID,AccountID,FiscalYearID,FiscalMonthID,max(ApplyDate) as ApplyDate from #StatisticTempTable where TimeClassID = 2 group by DepartmentID,AccountID,FiscalYearID,FiscalMonthID) STT ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID
		where Change <> 0
				  and b.BudgetReallocationGUID = @BudgetReallocationGUID
				  and stt.DepartmentID is null
				  and UnitTypeID = 145
		GROUP BY b.SourceDepartmentID,
				b.SourceAccountID,
				b.FiscalYearID,
				ba.FiscalMonthID
		UNION All
		SELECT 
				b.TargetDepartmentID as DepartmentID,
				b.TargetAccountID as AccountID,
				b.FiscalYearID,
				ba.FiscalMonthID,
				2 as TimeclassID,
				sum(Change) as Value,
				max(b.Date) as ApplyDate,
				'ra_1_p' as src
		FROM [mr].[BudgetReallocation] b
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		LEFT JOIN (select DepartmentID,AccountID,FiscalYearID,FiscalMonthID,max(ApplyDate) as ApplyDate from #StatisticTempTable where TimeClassID = 2 group by DepartmentID,AccountID,FiscalYearID,FiscalMonthID) STT ON b.TargetDepartmentID = stt.DepartmentID and b.TargetAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID
		where Change <> 0
				  and b.BudgetReallocationGUID = @BudgetReallocationGUID
				  and stt.DepartmentID is null
				  and UnitTypeID = 145
		group by 
				b.TargetDepartmentID,
				b.TargetAccountID,
				b.FiscalYearID,
				ba.FiscalMonthID
		------------------


		
	END
	ELSE
IF @BudgetReallocationType = 'ReallocateMulti'
	BEGIN
		Update stt
		set 
				stt.Amount = stt.Amount + stt_src.Amount,
				stt.ApplyDate = b.Date,
				stt.Src = stt.Src + '[RealMulti_'+cast(stt_src.Amount as varchar(50))+'_from_'+cast(stt_src.DepartmentID as varchar(10))+']'
		FROM #StatisticTempTable STT
		INNER JOIN [mr].[BudgetReallocation] b on b.TargetDepartmentID = stt.DepartmentID and b.TargetAccountID = stt.AccountID and b.Date >= stt.ApplyDate and b.FiscalYearID = stt.FiscalYearID
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID
		INNER JOIN #StatisticTempTable STT_SRC on STT_SRC.DepartmentID = b.SourceDepartmentID and STT_SRC.AccountID = b.SourceAccountID and STT_SRC.FiscalYearID = b.FiscalYearID and STT_SRC.FiscalMonthID = ba.FiscalMonthID and stt.TimeClassID = stt_src.TimeClassID
		where 
			b.BudgetReallocationGUID = @BudgetReallocationGUID
			and ba.UnitTypeID = 145
			and Change <> 0
			and stt.TimeClassID = 2
	--select 'X',* from #StatisticTempTable where DepartmentId = 279 and AccountID = 791 and FiscalYearID = 2015 and FiscalMonthID = 5 and TimeClassID = 2
	INSERT INTO #StatisticTempTable	(DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src)
	SELECT --'Y',
		b.TargetDepartmentID as DepartmentID,
		b.TargetAccountID as AccountID,
		b.FiscalYearID,
		ba.FiscalMonthID,
		2 as TimeclassID,
		sum(Change) as Value,
		max(b.Date) as ApplyDate,
		'ReallocateMulti' as src
	FROM [mr].[BudgetReallocation] b
	INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID 
	INNER JOIN #StatisticTempTable STT_SRC on STT_SRC.DepartmentID = b.SourceDepartmentID and STT_SRC.AccountID = b.SourceAccountID and STT_SRC.FiscalYearID = b.FiscalYearID and stt_src.FiscalMonthID = ba.FiscalMonthID  and STT_SRC.TimeClassID = 2
	LEFT JOIN #StatisticTempTable STT on STT.DepartmentID = b.TargetDepartmentID and STT.AccountID = b.TargetAccountID and STT.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID and STT.TimeClassID = 2
	where stt.DepartmentID is null
		and Change <> 0
		and ba.UnitTypeID =145
		and b.Date >= isnull(stt.ApplyDate,'1900-01-01')
		and b.BudgetReallocationGUID = @BudgetReallocationGUID
	GROUP BY 
		b.TargetDepartmentID,
		b.TargetAccountID,
		b.FiscalYearID,
		ba.FiscalMonthID
	UPDATE STT_SRC
		SET 
				stt_src.Amount = 0,
				stt_src.ApplyDate = b.Date,
				stt_src.Src = stt_src.Src + '[RealMulti_'+cast(stt_src.Amount as varchar(50))+'_to_'+cast(stt.DepartmentID as varchar(10))+']'
	FROM #StatisticTempTable STT
	INNER JOIN [mr].[BudgetReallocation] b on b.TargetDepartmentID = stt.DepartmentID and b.TargetAccountID = stt.AccountID and b.Date >= stt.ApplyDate and b.FiscalYearID = stt.FiscalYearID
	INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID
	INNER JOIN #StatisticTempTable STT_SRC on STT_SRC.DepartmentID = b.SourceDepartmentID and STT_SRC.AccountID = b.SourceAccountID and STT_SRC.FiscalYearID = b.FiscalYearID and stt_SRC.FiscalMonthID = ba.FiscalMonthID and STT_SRC.TimeClassID = 2
	where 
			b.BudgetReallocationGUID = @BudgetReallocationGUID
			and ba.UnitTypeID = 145
			and Change <> 0
	END
	ELSE
	IF @BudgetReallocationType = 'AdjustMontly'
	BEGIN
	
	UPDATE STT
	SET 
			stt.Amount = stt.Amount+Change,
			stt.ApplyDate = b.Date,
			stt.Src = stt.Src + '[AdjustMontly_'+cast(Change as varchar(50))+']'
	FROM #StatisticTempTable STT
	INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and b.Date >= stt.ApplyDate and b.FiscalYearID = stt.FiscalYearID
	INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID
	where 
		b.BudgetReallocationGUID = @BudgetReallocationGUID
		and ba.UnitTypeID = 145
		and Change <> 0
		and b.Date >= isnull(stt.ApplyDate,'1900-01-01')
		and TimeClassID = 2
	
	INSERT INTO #StatisticTempTable	(DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src)
	SELECT 
		b.SourceDepartmentID as DepartmentID,
		b.SourceAccountID as AccountID,
		b.FiscalYearID,
		ba.FiscalMonthID,
		2 as TimeclassID,
		SUM(Change) as Value,
		MAX(b.date) as ApplyDate,
		'ra_3' as src
	FROM [mr].[BudgetReallocation] b
	INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
	LEFT JOIN #StatisticTempTable STT ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID and TimeClassID = 2 
	where Change <> 0
		and stt.DepartmentID is null
		and ba.UnitTypeID =145
		and b.Date >= isnull(stt.ApplyDate,'1900-01-01')
		and b.BudgetReallocationGUID = @BudgetReallocationGUID
	GROUP BY 
		b.SourceDepartmentID,
		b.SourceAccountID,
		b.FiscalYearID,
		ba.FiscalMonthID
	END
	ELSE
	IF @BudgetReallocationType = 'ManualFile'
	BEGIN
		UPDATE STT
			SET 
				stt.Amount = ba.NewSourceValue,
				stt.ApplyDate = b.Date,
				stt.Src = stt.Src + '[ManualFile_'+cast(NewSourceValue as varchar(50))+']'				
		FROM #StatisticTempTable STT
		INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and b.Date >= stt.ApplyDate and b.FiscalYearID = stt.FiscalYearID
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID
		where 
			b.BudgetReallocationGUID = @BudgetReallocationGUID
			and ba.UnitTypeID = 145
			and TimeClassID = 2
			--and Change <> 0
		
		INSERT INTO #StatisticTempTable	(DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src)
		SELECT 
			b.SourceDepartmentID as DepartmentID,
			b.SourceAccountID as AccountID,
			b.FiscalYearID,
			ba.FiscalMonthID,
			2 as TimeclassID,
			SUM(NewSourceValue) as Value,
			MAX(b.date) as ApplyDate,
			'ManualFile' as src
		FROM [mr].[BudgetReallocation] b
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		LEFT JOIN #StatisticTempTable STT ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID and TimeClassID = 2 
		where Change <> 0
			and stt.DepartmentID is null
			and ba.UnitTypeID =145
			and b.Date >= isnull(stt.ApplyDate,'1900-01-01')
			and b.BudgetReallocationGUID = @BudgetReallocationGUID
		GROUP BY b.SourceDepartmentID,
			b.SourceAccountID,
			b.FiscalYearID,
			ba.FiscalMonthID
	END

	set @iteration  = @iteration +1

	FETCH NEXT FROM BRA_cursor   
	INTO @BudgetReallocationGUID,@date,@BudgetReallocationType   
END   
CLOSE BRA_cursor;  
DEALLOCATE BRA_cursor;  

if @StatisticType  = 1 
begin
SELECT DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,SUM(Amount) as Amount 
FROM (
	SELECT stt.DepartmentID,stt.AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,src
	from #StatisticTempTable stt
	inner join [fw].[viewStatisticPrimaryConfiguration] V on V.AccountID=stt.AccountID and V.DepartmentID=stt.DepartmentID
	UNION ALL
	SELECT stat.DepartmentID,stat.AccountID,FiscalYearID,FiscalMonthID,stat.TimeClassID,0 as Amount,cast('just0' as varchar(max)) as src
	from int.FactStatistic stat  
	inner join [fw].[viewStatisticPrimaryConfiguration] V on V.AccountID=stat.AccountID and V.DepartmentID=stat.DepartmentID
	WHERE stat.IsDeleted = 0
		and stat.Value != 0
		and (stat.FiscalYearID = @FiscalYearID or @FiscalYearID = 0)
) SubSelect
GROUP BY DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID
end
else if @StatisticType = 2 
begin
SELECT DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,SUM(Amount) as Amount 
FROM (
	SELECT stt.DepartmentID,stt.AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,src
	from #StatisticTempTable stt
	inner join [fw].[viewStatisticSecondaryConfiguration] V on V.AccountID=stt.AccountID and V.DepartmentID=stt.DepartmentID
	UNION ALL
	SELECT stat.DepartmentID,stat.AccountID,FiscalYearID,FiscalMonthID,stat.TimeClassID,0 as Amount,cast('just0' as varchar(max)) as src
	from int.FactStatistic stat  
	inner join [fw].[viewStatisticSecondaryConfiguration] V on V.AccountID=stat.AccountID and V.DepartmentID=stat.DepartmentID
	WHERE stat.IsDeleted = 0
		and stat.Value != 0
		and (stat.FiscalYearID = @FiscalYearID or @FiscalYearID = 0)
) SubSelect
GROUP BY DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID

end
else 
begin
SELECT DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,SUM(Amount) as Amount 
FROM (
	SELECT stt.DepartmentID,stt.AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,src
	from #StatisticTempTable stt
	UNION ALL
	SELECT stat.DepartmentID,stat.AccountID,FiscalYearID,FiscalMonthID,stat.TimeClassID,0 as Amount,cast('just0' as varchar(max)) as src
	from int.FactStatistic stat 
	WHERE 	stat.IsDeleted = 0
		and stat.Value != 0
		and (stat.FiscalYearID = @FiscalYearID or @FiscalYearID = 0)	
) SubSelect
GROUP BY DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID
IF OBJECT_ID('tempdb..#StatisticTempTable') IS NOT NULL DROP TABLE #StatisticTempTable
end
GO


---------------------------------------------

-- fw.PrepareStatisticsPayPeriod
CREATE PROCEDURE [fw].[PrepareStatisticsPayPeriod] (
	@FiscalYearID INT = 0,
	@departmentIDs NVARCHAR(max) = NULL,
	@StatisticType INT = 0,
	@isPrMetricConfigurationOn BIT = 0
	)
/************************************************************
** Author: ipetriv
** Create Date: 2017-7-26
** Description: procedure to append to [int].[FactStatisticsbyPayPeriod] MR statistic reallocation adjustments
** Last Modified: 2017-7-26
** GM Release: 2018.1
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2017-7-26	IP		B-16752		Added section for monthly spread adjustments
** 2		2017-10-11	IP		D-06489		Fixed difference between "by year" and "all years" end numbers 
** 3		2018-01-17	IP		B-16703		Omit archived budget adjustments
** 4		2018-03-15	IP		D-06997		Replaced table variable by temp tables 
** 5		2018-04-27	IP		TK-56559	Adding grouping to fix integration test
** 6		2018-05-14	IP		TK-57807	Reallocate between departments fix
** 7		2019-02-12	IP		D-06606		PR Statistics sampling with adjustments is incorrectly calculating first Pay Period values
** 8		2020-03-20	vfay	D-08997	[fw].[PrepareStatisticsPayPeriod] is reporting incorrect adjustment amounts
** 9		2023-04-11	HV		JAZZ-52032	Create and fill caching table for charge-based statistics pay period data
*************************************************************/
AS
	IF OBJECT_ID('tempdb..#StatisticSampledTempTable') IS NOT NULL  DROP TABLE #StatisticSampledTempTable
	IF OBJECT_ID('tempdb..#departments') IS NOT NULL  DROP TABLE #departments
	IF OBJECT_ID('tempdb..#departmentsBudgetAllocations') IS NOT NULL  DROP TABLE #departmentsBudgetAllocations
	IF OBJECT_ID('tempdb..#FDPSD') IS NOT NULL DROP TABLE #FDPSD
	IF OBJECT_ID('tempdb..#StatisticInsertTempTable') IS NOT NULL  DROP TABLE #StatisticInsertTempTable
	IF OBJECT_ID('tempdb..#payperiods') IS NOT NULL  DROP TABLE #payperiods
	IF OBJECT_ID('tempdb..#StatisticTempTableBackup') IS NOT NULL  DROP TABLE #StatisticTempTableBackup

	DECLARE @iteration INT = 1
	CREATE TABLE #FDPSD (DepartmentID INT PRIMARY KEY)

	INSERT INTO #FDPSD
	SELECT DISTINCT DriverDepartmentID AS DepartmentID
	FROM client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache

	CREATE TABLE #departments (val INT PRIMARY KEY)
	CREATE TABLE #departmentsBudgetAllocations (val INT PRIMARY KEY)

	INSERT INTO #departments SELECT val FROM ConvertCSValuesToTable(@departmentIDs, ',')

	INSERT INTO #departments
	SELECT 
		SourceDepartmentID AS DepartmentID 
	FROM 
		mr.BudgetReallocationAdjustment a
		INNER JOIN mr.BudgetReallocation r ON r.BudgetReallocationGUID=a.BudgetReallocationGUID
		INNER JOIN #departments d ON d.val = r.TargetDepartmentID -- Filtering all departments that move data TO selected
	UNION  -- unique
	SELECT 
		TargetDepartmentID AS DepartmentID
	FROM 
		mr.BudgetReallocationAdjustment a
		INNER JOIN mr.BudgetReallocation r ON r.BudgetReallocationGUID=a.BudgetReallocationGUID
		INNER JOIN #departments d ON d.val = r.SourceDepartmentID -- Filtering all departments that move data FROM selected

	INSERT INTO #departmentsBudgetAllocations (val)
	SELECT 
		SourceDepartmentID AS DepartmentID 
	FROM 
		mr.BudgetReallocationAdjustment a
		INNER JOIN mr.BudgetReallocation r ON r.BudgetReallocationGUID = a.BudgetReallocationGUID
		INNER JOIN FW.DimDepartment d ON d.DepartmentID = r.TargetDepartmentID AND d.IsPR = 1
	WHERE SourceDepartmentID <> 0
	UNION  -- unique
	SELECT 
		TargetDepartmentID AS DepartmentID
	FROM 
		mr.BudgetReallocationAdjustment a
		INNER JOIN mr.BudgetReallocation r ON r.BudgetReallocationGUID=a.BudgetReallocationGUID
		INNER JOIN FW.DimDepartment d ON d.DepartmentID = r.SourceDepartmentID and d.IsPR = 1 -- Filtering all departments that move data FROM selected
	where TargetDepartmentID <> 0

	CREATE TABLE #payperiods(val SMALLINT PRIMARY KEY, PayCycleID int, PeriodStartCalendarDate date, PeriodEndCalendarDate date)
	INSERT INTO #payperiods (val, PayCycleID, PeriodStartCalendarDate, PeriodEndCalendarDate) 
	SELECT PayPeriodID, PayCycleID, PeriodStartCalendarDate, PeriodEndCalendarDate
	FROM fw.DimPayPeriod 
	WHERE FiscalYearIDSecond = @fiscalYearID or @fiscalYearID = 0

	--run custom scripts
	EXEC [client].[procStatisticSampledInsertPayPeriodPreprocess] 
      	
	CREATE TABLE #StatisticSampledTempTable 
	(
		DepartmentID int, 
		AccountID int, 
		PayPeriodID int, 
		TimeClassID int, 
		Units decimal(18, 6)
	)

	--pull new data - Pay Period Actuals from GL
	INSERT INTO #StatisticSampledTempTable (DepartmentID, AccountID, PayPeriodID, TimeClassID, Units)
	SELECT
		stat.[DepartmentID],
		stat.[AccountID],
		stat.[PayPeriodID],
		stat.[TimeClassID],
		SUM(stat.[Value]) AS Units
	FROM
		[int].[FactStatisticsbyPayPeriod] stat
		inner join [fw].[DimDepartment] D on D.DepartmentID = stat.DepartmentID
		left join #FDPSD FDPSD on FDPSD.DepartmentID = stat.DepartmentID
	WHERE
		stat.[Value] <> 0 AND stat.Isdeleted = 0 AND stat.PayPeriodID != 0
		AND (D.IsPR = 1 or exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache dc where dc.DriverDepartmentID = D.DepartmentID))
		AND stat.TimeClassID=1
		AND stat.DepartmentID <> 0
		AND (D.IsPR = 1 or FDPSD.DepartmentID is not null)
		AND (@departmentIDs is null or stat.DepartmentID in (select val from #departments))
		AND (@fiscalYearID = 0 or stat.PayPeriodID in (select val from #payperiods))
	GROUP BY
		stat.DepartmentID,
		stat.AccountID,
		stat.PayPeriodID,
		stat.TimeClassID

	--pull new data - Aggregation of daily GL Actuals where not already sampled
	INSERT INTO #StatisticSampledTempTable (DepartmentID, AccountID, PayPeriodID, TimeClassID, Units)
	SELECT
		stat.[DepartmentID],
		stat.[AccountID],
		PP.[PayPeriodID],
		stat.[TimeClassID],
		SUM(STAT.[Value]) as Units
	FROM
		[int].[FactSharedImportDailyStatistics] stat
		inner join [fw].[DimDate] DATE on stat.DateID=DATE.DateID
		inner join [fw].[DimDepartment] D on D.Departmentid = STAT.Departmentid
		inner join [fw].[DimPayPeriod] PP on D.PayCycleID=PP.PayCycleID and DATE.CalendarDateTime between PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate
		left join #FDPSD FDPSD ON  FDPSD.DepartmentID = STAT.DepartmentID
		left join #StatisticSampledTempTable ex on ex.DepartmentID = stat.DepartmentID and ex.AccountID = stat.AccountID and ex.PayPeriodID = PP.PayPeriodID and ex.TimeClassID = 1
	WHERE 
		stat.[Value] <> 0 and STAT.Isdeleted = 0 and PP.PayPeriodID != 0
		and (D.IsPR = 1 or FDPSD.DepartmentID is not null)
		and stat.TimeClassID = 1
		and stat.DepartmentID <> 0
		and ex.DepartmentID IS NULL 
		and (@departmentIDs is null or stat.DepartmentID in (select val from #departments))
		and (@fiscalYearID = 0 or pp.FiscalYearIDSecond = @fiscalYearID)
	GROUP BY
		stat.DepartmentID,
		stat.AccountID,
		stat.TimeClassID,
		PP.PayPeriodID

	--pull new data - Aggregation of daily charge-based Actuals where not already sampled
	INSERT INTO #StatisticSampledTempTable (DepartmentID, AccountID, PayPeriodID, TimeClassID, Units)
	SELECT
		STAT.DepartmentID,
		STAT.AccountID,
		PP.PayPeriodID,
		1 as TimeClassID,
		SUM(STAT.Value) AS Units
	FROM
		[fw].[FactChargeBasedStatistics] STAT
		inner join [fw].[DimDate] DATE on STAT.DateID=DATE.DateID
		inner join [fw].[DimDepartment] D on STAT.DepartmentID=D.DepartmentID
		inner join [fw].[DimPayPeriod] PP on D.PayCycleID=PP.PayCycleID and DATE.CalendarDateTime between PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate
		left join #FDPSD FDPSD ON FDPSD.DepartmentID = STAT.DepartmentID
		left join #StatisticSampledTempTable ex on ex.DepartmentID = stat.DepartmentID and ex.AccountID = stat.AccountID and ex.PayPeriodID = PP.PayPeriodID and ex.TimeClassID = 1
	WHERE
		STAT.Value != 0 and STAT.IsDeleted = 0 and PP.PayPeriodID != 0
		and (D.IsPR = 1 or FDPSD.DepartmentID is not null)
		and ex.DepartmentID IS NULL 
		and (@departmentIDs is null or STAT.DepartmentID in (select val from #departments))
		and (@fiscalYearID = 0 or pp.FiscalYearIDSecond = @fiscalYearID)
	GROUP BY
		STAT.DepartmentID,
		STAT.AccountID,
		PP.PayPeriodID

	--pull new data - Pay Period Budget from GL for all Departments and Accounts
	INSERT INTO #StatisticSampledTempTable (DepartmentID, AccountID, PayPeriodID, TimeClassID, Units)
	SELECT
		stat.[DepartmentID],
		stat.[AccountID],
		STAT.[PayPeriodID],
		stat.[TimeClassID],
		SUM(STAT.[Value]) as Units
	FROM
		[int].[FactStatisticsbyPayPeriod] stat 
		inner join [fw].[DimDepartment] D on D.Departmentid = STAT.[Departmentid]
		left join #FDPSD FDPSD ON FDPSD.DepartmentID = STAT.[DepartmentID]
		left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID
	WHERE 
		STAT.[Value] != 0 and STAT.Isdeleted = 0 and STAT.PayPeriodID != 0
		and (D.IsPR = 1 or FDPSD.DepartmentID is not null or dba.val is not null)
		and stat.TimeClassID = 2
		and stat.DepartmentID <> 0
		and (@departmentIDs is null or stat.DepartmentID in (select val from #departments))
		and (@fiscalYearID = 0 or stat.PayPeriodID in (select val from #payperiods))
	GROUP BY
		stat.DepartmentID,
		stat.AccountID,
		STAT.PayPeriodID,
		stat.TimeClassID

	CREATE TABLE #StatisticInsertTempTable
	(
		DepartmentID int,
		AccountID int,
		PayPeriodID int,
		TimeClassID int,
		Units decimal(18, 6)
	)

	CREATE TABLE #StatisticTempTableBackup
	(
		DepartmentID int,
		AccountID int,
		PayPeriodID int,
		TimeClassID int,
		Units decimal(18, 6)
	)

	INSERT INTO #StatisticTempTableBackup(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units)
	SELECT DepartmentID, AccountID, PayPeriodID, TimeClassID, Units from #StatisticSampledTempTable

	DECLARE @BudgetReallocationGUID UNIQUEIDENTIFIER,
		@date DATETIME,
		@BudgetReallocationType VARCHAR(50)

	PRINT '-------- Vendor Products Report --------';

	DECLARE BRA_cursor CURSOR
	FOR
	SELECT DISTINCT 
		BudgetReallocationGUID, [DATE], BudgetReallocationType
	FROM fw.BudgetReallocationWithDefinedType br
		INNER JOIN [fw].DimPayPeriod pp ON (
			(br.FiscalMonthID = pp.FiscalMonthIDStart AND br.FiscalYearID = pp.FiscalYearIDStart) OR 
			(br.FiscalMonthID = pp.FiscalMonthIDSecond AND br.FiscalYearID = pp.FiscalYearIDSecond))
		INNER JOIN #payperiods pay ON pay.val = pp.PayPeriodID
	WHERE br.BudgetReallocationType IS NOT NULL
	ORDER BY DATE;

	OPEN BRA_cursor

	FETCH NEXT
	FROM BRA_cursor
	INTO @BudgetReallocationGUID, @date, @BudgetReallocationType

	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @BudgetReallocationType = 'ReallocateSingle'
		BEGIN

			--update target 
			UPDATE stt
			SET 
				Units = Units + ba.Change * pp.PeriodWeightStart
			FROM 
				#StatisticSampledTempTable stt
				INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID
				INNER JOIN [mr].[BudgetReallocation] b ON 
					b.TargetDepartmentID = stt.DepartmentID AND 
					b.TargetAccountID = stt.AccountID AND 
					b.FiscalYearID = pp.FiscalYearIDStart
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON 
					b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND
					ba.FiscalMonthID = pp.FiscalMonthIDStart
			WHERE 
				ba.Change <> 0 AND 
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				ba.UnitTypeID = 145 AND
				stt.TimeClassID = 2 AND
				b.Archived = 0

			UPDATE stt
			SET
				Units = Units + ba.Change * pp.PeriodWeightSecond
			FROM
				#StatisticSampledTempTable stt
				INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID
				INNER JOIN [mr].[BudgetReallocation] b ON
					b.TargetDepartmentID = stt.DepartmentID AND 
					b.TargetAccountID = stt.AccountID AND 
					b.FiscalYearID = pp.FiscalYearIDSecond
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON
					b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND
					ba.FiscalMonthID = pp.FiscalMonthIDSecond
			WHERE 
				ba.Change <> 0 AND 
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				ba.UnitTypeID = 145 AND
				stt.TimeClassID = 2 AND
				b.Archived = 0

			--update source
			UPDATE stt
			SET 
				Units = Units - ba.Change * pp.PeriodWeightStart
			FROM  
				#StatisticSampledTempTable stt
				INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID
				INNER JOIN [mr].[BudgetReallocation] b ON 
					b.SourceDepartmentID = stt.DepartmentID AND 
					b.SourceAccountID = stt.AccountID AND 
					b.FiscalYearID = pp.FiscalYearIDStart
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON 
					b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND
					ba.FiscalMonthID = pp.FiscalMonthIDStart
			WHERE 
				ba.Change <> 0 AND 
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				ba.UnitTypeID = 145 AND
				stt.TimeClassID = 2 AND
				b.Archived = 0

			UPDATE stt
			SET
				Units = Units - ba.Change * pp.PeriodWeightSecond
			FROM
				#StatisticSampledTempTable stt
				INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID
				INNER JOIN [mr].[BudgetReallocation] b ON
					b.SourceDepartmentID = stt.DepartmentID AND 
					b.SourceAccountID = stt.AccountID AND 
					b.FiscalYearID = pp.FiscalYearIDSecond
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON
					b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND
					ba.FiscalMonthID = pp.FiscalMonthIDSecond
				WHERE
					ba.Change <> 0 AND 
					b.BudgetReallocationGUID = @BudgetReallocationGUID AND
					ba.UnitTypeID = 145 AND
					stt.TimeClassID = 2 AND
					b.Archived = 0
			
			--clear records in temp insert table
			TRUNCATE TABLE #StatisticInsertTempTable

			-- insert missing source records
			INSERT INTO #StatisticInsertTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units)
			SELECT 
				b.SourceDepartmentID AS DepartmentID,
				b.SourceAccountID AS AccountID,
				pp.PayPeriodID,
				2 AS TimeclassID,
				SUM((ba.Change * pp.PeriodWeightStart)*-1) AS Units
			FROM
				[mr].[BudgetReallocation] b
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID
				INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.SourceDepartmentID
				INNER JOIN [fw].[DimPayPeriod] pp ON 
					pp.PayCycleID = dep.PayCycleID AND
					pp.FiscalMonthIDStart = ba.FiscalMonthID AND
					pp.FiscalYearIDStart = b.FiscalYearID
				INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val
				LEFT JOIN #StatisticSampledTempTable stt ON 
					b.SourceDepartmentID = stt.DepartmentID AND 
					b.SourceAccountID = stt.AccountID AND
					pp.PayPeriodId = stt.PayPeriodID AND
					stt.TimeClassID = 2
			WHERE 
				ba.Change <> 0 AND
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				stt.DepartmentID IS NULL AND 
				ba.UnitTypeID = 145 AND
				b.Archived = 0				  
			GROUP BY 
				b.SourceDepartmentID,
				b.SourceAccountID,
				pp.PayPeriodID	
			UNION ALL
			SELECT 
				b.SourceDepartmentID AS DepartmentID,
				b.SourceAccountID AS AccountID,
				pp.PayPeriodID,
				2 AS TimeclassID,
				SUM((ba.Change * pp.PeriodWeightSecond)*-1) AS Units
			FROM
				[mr].[BudgetReallocation] b
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID
				INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.SourceDepartmentID
				INNER JOIN [fw].[DimPayPeriod] pp ON 
					pp.PayCycleID = dep.PayCycleID AND
					pp.FiscalMonthIDSecond = ba.FiscalMonthID AND
					pp.FiscalYearIDSecond = b.FiscalYearID
				INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val
				LEFT JOIN #StatisticSampledTempTable stt ON 
					b.SourceDepartmentID = stt.DepartmentID AND 
					b.SourceAccountID = stt.AccountID AND
					pp.PayPeriodId = stt.PayPeriodID AND
					stt.TimeClassID = 2
			WHERE 
				ba.Change <> 0 AND
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				stt.DepartmentID IS NULL AND 
				ba.UnitTypeID = 145 AND
				b.Archived = 0		  
			GROUP BY 
				b.SourceDepartmentID,
				b.SourceAccountID,
				pp.PayPeriodID 
		
			--insert missing target records
			INSERT INTO #StatisticInsertTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units)
			SELECT 
				b.TargetDepartmentID AS DepartmentID,
				b.TargetAccountID AS AccountID,
				pp.PayPeriodID,
				2 AS TimeclassID,
				SUM((ba.Change * pp.PeriodWeightStart)) AS Units
			FROM
				[mr].[BudgetReallocation] b
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID
				INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.TargetDepartmentID
				INNER JOIN [fw].[DimPayPeriod] pp ON 
					pp.PayCycleID = dep.PayCycleID AND
					pp.FiscalMonthIDStart = ba.FiscalMonthID AND
					pp.FiscalYearIDStart = b.FiscalYearID
				INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val
				LEFT JOIN #StatisticSampledTempTable stt ON 
					b.TargetDepartmentID = stt.DepartmentID AND 
					b.TargetAccountID = stt.AccountID AND
					pp.PayPeriodId = stt.PayPeriodID AND
					stt.TimeClassID = 2
			WHERE 
				ba.Change <> 0 AND
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				stt.DepartmentID IS NULL AND 
				ba.UnitTypeID = 145 AND
				b.Archived = 0				  
			GROUP BY 
				b.TargetDepartmentID,
				b.TargetAccountID,
				pp.PayPeriodID 
			UNION ALL
			SELECT 
				b.TargetDepartmentID AS DepartmentID,
				b.TargetAccountID AS AccountID,
				pp.PayPeriodID,
				2 AS TimeclassID,
				SUM((ba.Change * pp.PeriodWeightSecond)) AS Units
			FROM
				[mr].[BudgetReallocation] b
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID
				INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.TargetDepartmentID
				INNER JOIN [fw].[DimPayPeriod] pp ON 
					pp.PayCycleID = dep.PayCycleID AND
					pp.FiscalMonthIDSecond = ba.FiscalMonthID AND
					pp.FiscalYearIDSecond = b.FiscalYearID
				INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val
				LEFT JOIN #StatisticSampledTempTable stt ON 
					b.TargetDepartmentID = stt.DepartmentID AND 
					b.TargetAccountID = stt.AccountID AND
					pp.PayPeriodId = stt.PayPeriodID AND
					stt.TimeClassID = 2
			WHERE 
				ba.Change <> 0 AND
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				stt.DepartmentID IS NULL AND 
				ba.UnitTypeID = 145 AND
				b.Archived = 0				  
			GROUP BY 
				b.TargetDepartmentID,
				b.TargetAccountID,
				pp.PayPeriodID 

			--insert to statistic temp table
			INSERT INTO #StatisticSampledTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units)
			SELECT 
				DepartmentID, 
				AccountID,
				PayPeriodID, 
				TimeClassID,
				SUM(Units)
			FROM #StatisticInsertTempTable
			GROUP BY
				DepartmentID,
				AccountID,
				PayPeriodID, 
				TimeClassID
		END

		IF @BudgetReallocationType = 'ReallocateMulti'
		BEGIN
			--update target
			UPDATE stt
			SET 
				Units = stt.Units + stt_src_back.Units * pp.DaysInPeriodWeightStart
			FROM 
				#StatisticSampledTempTable stt
				INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID
				INNER JOIN [mr].[BudgetReallocation] b ON 
					b.TargetDepartmentID = stt.DepartmentID AND 
					b.TargetAccountID = stt.AccountID AND 
					b.FiscalYearID = pp.FiscalYearIDStart
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON 
					b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND
					ba.FiscalMonthID = pp.FiscalMonthIDStart
				INNER JOIN #StatisticTempTableBackup stt_src_back ON
					stt_src_back.DepartmentID = b.SourceDepartmentID AND 
					stt_src_back.AccountID = b.SourceAccountID AND 
					stt_src_back.PayPeriodID = stt.PayPeriodID AND
					stt_src_back.TimeClassID = stt.TimeClassID
			WHERE 
				ba.Change <> 0 AND 
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				ba.UnitTypeID = 145 AND
				stt.TimeClassID = 2 AND
				b.Archived = 0

			UPDATE stt
			SET 
				Units = stt.Units + stt_src_back.Units * pp.DaysInPeriodWeightSecond
			FROM 
				#StatisticSampledTempTable stt
				INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID
				INNER JOIN [mr].[BudgetReallocation] b ON 
					b.TargetDepartmentID = stt.DepartmentID AND 
					b.TargetAccountID = stt.AccountID AND 
					b.FiscalYearID = pp.FiscalYearIDSecond
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON 
					b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND
					ba.FiscalMonthID = pp.FiscalMonthIDSecond
				INNER JOIN #StatisticTempTableBackup stt_src_back ON
					stt_src_back.DepartmentID = b.SourceDepartmentID AND 
					stt_src_back.AccountID = b.SourceAccountID AND 
					stt_src_back.PayPeriodID = stt.PayPeriodID AND
					stt_src_back.TimeClassID = stt.TimeClassID
			WHERE 
				ba.Change <> 0 AND 
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				ba.UnitTypeID = 145 AND
				stt.TimeClassID = 2 AND
				b.Archived = 0
			
			--clear records in temp insert table
			TRUNCATE TABLE #StatisticInsertTempTable

			-- insert missing target records
			INSERT INTO #StatisticInsertTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units)
			SELECT 
				b.TargetDepartmentID AS DepartmentID,
				b.TargetAccountID AS AccountID,
				pp.PayPeriodID,
				2 AS TimeclassID,
				SUM(stt_src_back.Units * pp.DaysInPeriodWeightStart) AS Units
			FROM
				[mr].[BudgetReallocation] b
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID
				INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.TargetDepartmentID
				INNER JOIN [fw].[DimPayPeriod] pp ON 
					pp.PayCycleID = dep.PayCycleID AND
					pp.FiscalMonthIDStart = ba.FiscalMonthID AND
					pp.FiscalYearIDStart = b.FiscalYearID
				INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val
				INNER JOIN #StatisticTempTableBackup stt_src_back ON
					stt_src_back.DepartmentID = b.SourceDepartmentID AND 
					stt_src_back.AccountID = b.SourceAccountID AND
					stt_src_back.PayPeriodID = PP.PayPeriodID AND
					stt_src_back.TimeClassID = 2
				LEFT JOIN #StatisticSampledTempTable stt ON 
					stt.DepartmentID = b.TargetDepartmentID AND 
					stt.AccountID = b.TargetAccountID AND
					stt.PayPeriodID = pp.PayPeriodID AND
					stt.TimeClassID = 2
			WHERE 
				stt.DepartmentID IS NULL AND
				ba.Change <> 0 AND
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				ba.UnitTypeID = 145 AND
				b.Archived = 0				  
			GROUP BY 
				b.TargetDepartmentID,
				b.TargetAccountID,
				pp.PayPeriodID	
			UNION ALL
			SELECT 
				b.TargetDepartmentID AS DepartmentID,
				b.TargetAccountID AS AccountID,
				pp.PayPeriodID,
				2 AS TimeclassID,
				SUM(stt_src_back.Units * pp.DaysInPeriodWeightSecond) AS Units
			FROM
				[mr].[BudgetReallocation] b
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID
				INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.TargetDepartmentID
				INNER JOIN [fw].[DimPayPeriod] pp ON 
					pp.PayCycleID = dep.PayCycleID AND
					pp.FiscalMonthIDSecond = ba.FiscalMonthID AND
					pp.FiscalYearIDSecond = b.FiscalYearID
				INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val
				INNER JOIN #StatisticTempTableBackup stt_src_back ON
					stt_src_back.DepartmentID = b.SourceDepartmentID AND 
					stt_src_back.AccountID = b.SourceAccountID AND
					stt_src_back.PayPeriodID = PP.PayPeriodID AND
					stt_src_back.TimeClassID = 2
				LEFT JOIN #StatisticSampledTempTable stt ON 
					stt.DepartmentID = b.TargetDepartmentID AND 
					stt.AccountID = b.TargetAccountID AND
					stt.PayPeriodID = pp.PayPeriodID AND
					stt.TimeClassID = 2
			WHERE 
				stt.DepartmentID IS NULL AND
				ba.Change <> 0 AND
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				ba.UnitTypeID = 145 AND
				b.Archived = 0				  
			GROUP BY 
				b.TargetDepartmentID,
				b.TargetAccountID,
				pp.PayPeriodID	 
			
			--insert to statistic temp table
			INSERT INTO #StatisticSampledTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units)
			SELECT 
				DepartmentID, 
				AccountID,
				PayPeriodID, 
				TimeClassID,
				SUM(Units)
			FROM #StatisticInsertTempTable
			GROUP BY
				DepartmentID,
				AccountID,
				PayPeriodID, 
				TimeClassID
			
			--update source
			UPDATE stt_src
			SET 
				Units = stt_src.Units - stt_src_back.Units * DaysInPeriodWeightStart
			FROM 
				#StatisticSampledTempTable stt_src
				INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt_src.PayPeriodID
				INNER JOIN [mr].[BudgetReallocation] b ON 
					b.SourceDepartmentID = stt_src.DepartmentID AND 
					b.SourceAccountID = stt_src.AccountID AND 
					b.FiscalYearID = pp.FiscalYearIDStart
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON 
					b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND
					ba.FiscalMonthID = pp.FiscalMonthIDStart
				INNER JOIN #StatisticTempTableBackup stt_src_back ON
					stt_src.AccountID = stt_src_back.AccountID AND 
					stt_src.DepartmentID = stt_src_back.DepartmentID AND
					stt_src.PayPeriodID = stt_src_back.PayPeriodID AND
					stt_src.TimeClassID = stt_src_back.TimeClassID
				LEFT JOIN #StatisticSampledTempTable stt ON
					stt.DepartmentID = b.TargetDepartmentID and 
					stt.AccountID = b.TargetAccountID and 
					stt.TimeClassID = 2 and 
					stt.PayPeriodID = stt_src.PayPeriodID
			WHERE 
				ba.Change <> 0 AND 
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				ba.UnitTypeID = 145 AND
				b.Archived = 0

			UPDATE stt_src
			SET 
				Units = stt_src.Units - stt_src_back.Units * DaysInPeriodWeightSecond
			FROM 
				#StatisticSampledTempTable stt_src
				INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt_src.PayPeriodID
				INNER JOIN [mr].[BudgetReallocation] b ON 
					b.SourceDepartmentID = stt_src.DepartmentID AND 
					b.SourceAccountID = stt_src.AccountID AND 
					b.FiscalYearID = pp.FiscalYearIDSecond
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON 
					b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND
					ba.FiscalMonthID = pp.FiscalMonthIDSecond
				INNER JOIN #StatisticTempTableBackup stt_src_back ON
					stt_src.AccountID = stt_src_back.AccountID AND 
					stt_src.DepartmentID = stt_src_back.DepartmentID AND
					stt_src.PayPeriodID = stt_src_back.PayPeriodID AND
					stt_src.TimeClassID = stt_src_back.TimeClassID
				LEFT JOIN #StatisticSampledTempTable stt ON
					stt.DepartmentID = b.TargetDepartmentID and 
					stt.AccountID = b.TargetAccountID and 
					stt.TimeClassID = 2 and 
					stt.PayPeriodID = stt_src.PayPeriodID
			WHERE 
				ba.Change <> 0 AND 
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				ba.UnitTypeID = 145 AND
				b.Archived = 0

		END

		IF @BudgetReallocationType = 'AdjustMontly'
		BEGIN

			--update source
			UPDATE stt
			SET 
				Units = Units + ba.Change * pp.PeriodWeightStart
			FROM  
				#StatisticSampledTempTable stt
				INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID
				INNER JOIN [mr].[BudgetReallocation] b ON 
					b.SourceDepartmentID = stt.DepartmentID AND 
					b.SourceAccountID = stt.AccountID AND 
					b.FiscalYearID = pp.FiscalYearIDStart
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON 
					b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND
					ba.FiscalMonthID = pp.FiscalMonthIDStart
			WHERE 
				ba.Change <> 0 AND 
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				ba.UnitTypeID = 145 AND
				stt.TimeClassID = 2 AND
				b.Archived = 0

			UPDATE stt
			SET
				Units = Units + ba.Change * pp.PeriodWeightSecond
			FROM
				#StatisticSampledTempTable stt
				INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID
				INNER JOIN [mr].[BudgetReallocation] b ON
					b.SourceDepartmentID = stt.DepartmentID AND 
					b.SourceAccountID = stt.AccountID AND 
					b.FiscalYearID = pp.FiscalYearIDSecond
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON
					b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND
					ba.FiscalMonthID = pp.FiscalMonthIDSecond
			WHERE
				ba.Change <> 0 AND 
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				ba.UnitTypeID = 145 AND
				stt.TimeClassID = 2 AND
				b.Archived = 0

			--clear records in temp insert table
			TRUNCATE TABLE #StatisticInsertTempTable

			-- insert missing source records
			INSERT INTO #StatisticInsertTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units)
			SELECT 
				b.SourceDepartmentID AS DepartmentID,
				b.SourceAccountID AS AccountID,
				pp.PayPeriodID,
				2 AS TimeclassID,
				SUM(ba.Change * pp.PeriodWeightStart) AS Units
			FROM
				[mr].[BudgetReallocation] b
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID
				INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.SourceDepartmentID
				INNER JOIN [fw].[DimPayPeriod] pp ON 
					pp.PayCycleID = dep.PayCycleID AND
					pp.FiscalMonthIDStart = ba.FiscalMonthID AND
					pp.FiscalYearIDStart = b.FiscalYearID
				INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val
				LEFT JOIN #StatisticSampledTempTable stt ON 
					b.SourceDepartmentID = stt.DepartmentID AND 
					b.SourceAccountID = stt.AccountID AND
					pp.PayPeriodID = stt.PayPeriodID AND
					stt.TimeClassID = 2
			WHERE 
				ba.Change <> 0 and
				b.BudgetReallocationGUID = @BudgetReallocationGUID and
				stt.DepartmentID is null and 
				ba.UnitTypeID = 145 and
				b.Archived = 0				  
			GROUP BY 
				b.SourceDepartmentID,
				b.SourceAccountID,
				pp.PayPeriodID	
			UNION ALL
			SELECT 
				b.SourceDepartmentID AS DepartmentID,
				b.SourceAccountID AS AccountID,
				pp.PayPeriodID,
				2 AS TimeclassID,
				SUM(ba.Change * pp.PeriodWeightSecond) AS Units
			FROM
				[mr].[BudgetReallocation] b
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID
				INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.SourceDepartmentID
				INNER JOIN [fw].[DimPayPeriod] pp ON 
					pp.PayCycleID = dep.PayCycleID AND
					pp.FiscalMonthIDSecond = ba.FiscalMonthID AND
					pp.FiscalYearIDSecond = b.FiscalYearID
				INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val
				LEFT JOIN #StatisticSampledTempTable stt ON 
					b.SourceDepartmentID = stt.DepartmentID AND 
					b.SourceAccountID = stt.AccountID AND
					pp.PayPeriodID = stt.PayPeriodID AND
					stt.TimeClassID = 2
			WHERE 
				ba.Change <> 0 and
				b.BudgetReallocationGUID = @BudgetReallocationGUID and
				stt.DepartmentID is null and 
				ba.UnitTypeID = 145 and
				b.Archived = 0				  
			GROUP BY 
				b.SourceDepartmentID,
				b.SourceAccountID,
				pp.PayPeriodID

			--insert to statistic temp table
			INSERT INTO #StatisticSampledTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units)
			SELECT 
				DepartmentID, 
				AccountID,
				PayPeriodID, 
				TimeClassID,
				SUM(Units)
			FROM #StatisticInsertTempTable
			GROUP BY
				DepartmentID,
				AccountID,
				PayPeriodID, 
				TimeClassID
		END

		IF @BudgetReallocationType = 'ManualFile'
		BEGIN
			--update source 
			UPDATE stt
			SET 
				stt.Units = stt.Units - stt_src_back.Units * pp.DaysInPeriodWeightStart
			FROM 
				#StatisticSampledTempTable stt
				INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID
				INNER JOIN [mr].[BudgetReallocation] b ON 
					b.SourceDepartmentID = stt.DepartmentID AND 
					b.SourceAccountID = stt.AccountID AND 
					b.FiscalYearID = pp.FiscalYearIDStart
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON 
					b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND
					ba.FiscalMonthID = pp.FiscalMonthIDStart
				INNER JOIN #StatisticTempTableBackup stt_src_back ON
					stt.AccountID = stt_src_back.AccountID AND 
					stt.DepartmentID = stt_src_back.DepartmentID AND
					stt.PayPeriodID = stt_src_back.PayPeriodID AND
					stt.TimeClassID = stt_src_back.TimeClassID
			WHERE 
				ba.Change <> 0 AND 
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				ba.UnitTypeID = 145 AND
				stt.TimeClassID = 2 AND
				b.Archived = 0

			UPDATE stt
			SET 
				stt.Units =  stt.Units - stt_src_back.Units * pp.DaysInPeriodWeightSecond
			FROM 
				#StatisticSampledTempTable stt
				INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID
				INNER JOIN [mr].[BudgetReallocation] b ON 
					b.SourceDepartmentID = stt.DepartmentID AND 
					b.SourceAccountID = stt.AccountID AND 
					b.FiscalYearID = pp.FiscalYearIDSecond
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON 
					b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND
					ba.FiscalMonthID = pp.FiscalMonthIDSecond
				INNER JOIN #StatisticTempTableBackup stt_src_back ON
					stt.AccountID = stt_src_back.AccountID AND 
					stt.DepartmentID = stt_src_back.DepartmentID AND
					stt.PayPeriodID = stt_src_back.PayPeriodID AND
					stt.TimeClassID = stt_src_back.TimeClassID
			WHERE 
				ba.Change <> 0 AND 
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				ba.UnitTypeID = 145 AND
				stt.TimeClassID = 2 AND
				b.Archived = 0

			UPDATE stt
			SET 
				Units = Units + ba.NewSourceValue * pp.PeriodWeightStart
			FROM 
				#StatisticSampledTempTable stt
				INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID
				INNER JOIN [mr].[BudgetReallocation] b ON 
					b.SourceDepartmentID = stt.DepartmentID AND 
					b.SourceAccountID = stt.AccountID AND 
					b.FiscalYearID = pp.FiscalYearIDStart
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON 
					b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND
					ba.FiscalMonthID = pp.FiscalMonthIDStart
			WHERE 
				ba.Change <> 0 AND 
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				ba.UnitTypeID = 145 AND
				stt.TimeClassID = 2 AND
				b.Archived = 0

			UPDATE stt
			SET
				Units = Units + ba.NewSourceValue * pp.PeriodWeightSecond
			FROM
				#StatisticSampledTempTable stt
				INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID
				INNER JOIN [mr].[BudgetReallocation] b ON
					b.SourceDepartmentID = stt.DepartmentID AND 
					b.SourceAccountID = stt.AccountID AND 
					b.FiscalYearID = pp.FiscalYearIDSecond
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON
					b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND
					ba.FiscalMonthID = pp.FiscalMonthIDSecond
			WHERE 
				ba.Change <> 0 AND 
				b.BudgetReallocationGUID = @BudgetReallocationGUID AND
				ba.UnitTypeID = 145 AND
				stt.TimeClassID = 2 AND
				b.Archived = 0

			--clear records in temp insert table
			TRUNCATE TABLE #StatisticInsertTempTable

			-- insert missing source records
			INSERT INTO #StatisticInsertTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units)
			SELECT 
				b.SourceDepartmentID AS DepartmentID,
				b.SourceAccountID AS AccountID,
				pp.PayPeriodID,
				2 AS TimeclassID,
				SUM(ba.NewSourceValue * pp.PeriodWeightStart) AS Units
			FROM
				[mr].[BudgetReallocation] b
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID
				INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.SourceDepartmentID
				INNER JOIN [fw].[DimPayPeriod] pp ON 
					pp.PayCycleID = dep.PayCycleID AND
					pp.FiscalMonthIDStart = ba.FiscalMonthID AND
					pp.FiscalYearIDStart = b.FiscalYearID
				INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val
				LEFT JOIN #StatisticSampledTempTable stt ON 
					b.SourceDepartmentID = stt.DepartmentID AND 
					b.SourceAccountID = stt.AccountID AND
					pp.PayPeriodID = stt.PayPeriodID AND
					stt.TimeClassID = 2
			WHERE 
				ba.Change <> 0 and
				b.BudgetReallocationGUID = @BudgetReallocationGUID and
				stt.DepartmentID is null and 
				ba.UnitTypeID = 145 and
				b.Archived = 0				  
			GROUP BY 
				b.SourceDepartmentID,
				b.SourceAccountID,
				pp.PayPeriodID	
			UNION ALL
			SELECT 
				b.SourceDepartmentID AS DepartmentID,
				b.SourceAccountID AS AccountID,
				pp.PayPeriodID,
				2 AS TimeclassID,
				SUM(ba.NewSourceValue * pp.PeriodWeightSecond) AS Units
			FROM
				[mr].[BudgetReallocation] b
				INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID
				INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.SourceDepartmentID
				INNER JOIN [fw].[DimPayPeriod] pp ON 
					pp.PayCycleID = dep.PayCycleID AND
					pp.FiscalMonthIDSecond = ba.FiscalMonthID AND
					pp.FiscalYearIDSecond = b.FiscalYearID
				INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val
				LEFT JOIN #StatisticSampledTempTable stt ON 
					b.SourceDepartmentID = stt.DepartmentID AND 
					b.SourceAccountID = stt.AccountID AND
					pp.PayPeriodID = stt.PayPeriodID AND
					stt.TimeClassID = 2
			WHERE 
				ba.Change <> 0 and
				b.BudgetReallocationGUID = @BudgetReallocationGUID and
				stt.DepartmentID is null and 
				ba.UnitTypeID = 145 and
				b.Archived = 0				  
			GROUP BY 
				b.SourceDepartmentID,
				b.SourceAccountID,
				pp.PayPeriodID 

			--insert to statistic temp table
			INSERT INTO #StatisticSampledTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units)
			SELECT 
				DepartmentID, 
				AccountID,
				PayPeriodID, 
				TimeClassID,
				SUM(Units)
			FROM #StatisticInsertTempTable
			GROUP BY
				DepartmentID,
				AccountID,
				PayPeriodID, 
				TimeClassID
		END

		SET @iteration = @iteration + 1

		FETCH NEXT
		FROM BRA_cursor
		INTO @BudgetReallocationGUID,
			@date,
			@BudgetReallocationType
	END

	CLOSE BRA_cursor;

	DEALLOCATE BRA_cursor;

	IF @StatisticType = 2
		SELECT stat.*
		FROM 
			#StatisticSampledTempTable stat
			INNER JOIN [fw].[viewStatisticSecondaryConfiguration] V ON 
				V.AccountID = stat.AccountID AND 
				V.DepartmentID = stat.DepartmentID
	ELSE IF @StatisticType = 1
		SELECT 
			stat.*
		FROM 
			#StatisticSampledTempTable stat
			INNER JOIN [fw].[viewStatisticPrimaryConfiguration] V ON 
				V.AccountID = stat.AccountID AND 
				V.DepartmentID = stat.DepartmentID
	ELSE
		SELECT stat.*
		FROM #StatisticSampledTempTable stat
		
-- Fill Charge Based Statistics Sampled Keys
IF @isPrMetricConfigurationOn = 1
BEGIN
	IF @FiscalYearID = 0
	BEGIN
		TRUNCATE TABLE fw.FactChargeBasedStatisticsPayPeriodKeys
	END
	ELSE
	BEGIN
		DELETE F FROM fw.FactChargeBasedStatisticsPayPeriodKeys F
		INNER JOIN #payperiods PP ON PP.val = F.PayPeriodID
	END

	INSERT INTO fw.FactChargeBasedStatisticsPayPeriodKeys (DepartmentID, AccountID, PayPeriodID)
	SELECT DISTINCT CB.DepartmentID, CB.AccountID, PP.val
	FROM fw.FactChargeBasedStatistics CB
	INNER JOIN fw.DimDate DT ON DT.DateID = CB.DateID
	INNER JOIN fw.DimDepartment DEPT ON DEPT.DepartmentID = CB.DepartmentID
	INNER JOIN #payperiods PP ON PP.PayCycleID = DEPT.PayCycleID AND DT.CalendarDateTime BETWEEN PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate 
	LEFT JOIN int.FactSharedImportDailyStatistics DS ON DS.DepartmentID = CB.DepartmentID AND DS.AccountID = CB.AccountID AND DS.DateID = CB.DateID AND DS.TimeClassID = 1
	LEFT JOIN int.FactStatisticsbyPayPeriod FS ON FS.DepartmentID = CB.DepartmentID AND FS.AccountID = CB.AccountID AND FS.PayPeriodID = PP.val AND FS.TimeClassID = 1
	LEFT JOIN #FDPSD FDPSD on FDPSD.DepartmentID = CB.DepartmentID
	WHERE
		CB.IsDeleted = 0
		AND CB.DepartmentID != 0
		AND PP.val != 0
		AND CB.Value != 0
		AND DS.RowID IS NULL
		AND FS.RowID IS NULL
		AND (DEPT.IsPR = 1 OR FDPSD.DepartmentID IS NOT NULL)
END

IF OBJECT_ID('tempdb..#StatisticSampledTempTable') IS NOT NULL  DROP TABLE #StatisticSampledTempTable
IF OBJECT_ID('tempdb..#departments') IS NOT NULL  DROP TABLE #departments
IF OBJECT_ID('tempdb..#departmentsBudgetAllocations') IS NOT NULL  DROP TABLE #departmentsBudgetAllocations
IF OBJECT_ID('tempdb..#FDPSD') IS NOT NULL DROP TABLE #FDPSD
IF OBJECT_ID('tempdb..#StatisticInsertTempTable') IS NOT NULL  DROP TABLE #StatisticInsertTempTable
IF OBJECT_ID('tempdb..#payperiods') IS NOT NULL  DROP TABLE #payperiods
IF OBJECT_ID('tempdb..#StatisticTempTableBackup') IS NOT NULL  DROP TABLE #StatisticTempTableBackup
GO


---------------------------------------------

-- fw.procABBFlexingReconcilationSampling
CREATE PROCEDURE [fw].[procABBFlexingReconcilationSampling]
 
AS
BEGIN
 
	BEGIN TRANSACTION
 		TRUNCATE TABLE [fw].[ABBFlexingReconciliationCostingData]
		TRUNCATE TABLE [fw].[ABBBudgetedCostPerRVU]
	COMMIT

	BEGIN TRANSACTION
	INSERT INTO [fw].[ABBBudgetedCostPerRVU]
	([DepartmentID], [AccountID], [JobCodeID], [PayCodeID], [CostComponentID], [CostingConfigGuid], [VariableDirectUnitCostPerRVU], [TotalVariableDirectCost], [TotalCost])
			  
		SELECT
			gl.DepartmentID
			, OriginalAccountID as AccountID
			, 0 as JobCodeID
			, 0 as PayCodeID
			, gl.CostComponentID
			, cr.CostingConfigGuid
			, SUM(gl.VariableDirectUnitCost)/SUM(ca.RVU) as VariableDirectUnitCostPerRVU
			, SUM(gl.VariableDirectUnitCost * gl.Volume) as TotalVariableDirectCost
			, SUM(gl.TotalCost) as TotalCost
		FROM [dss].[FactCostingOutDetailGL] gl
			INNER JOIN [dss].[CostingResult] cr on gl.CostingResultID = cr.CostingResultID
			INNER JOIN [fp].[EntityGroupConfig] ec on cr.CostingConfigGuid = ec.CostingConfigGUID
			INNER JOIN [dss].[ChargeAllocation] ca on
				ca.CostingConfigGuid = cr.CostingConfigGUID
				and ca.ChargeCodeID = gl.ChargeCodeID 
				and ca.DepartmentID = gl.DepartmentID
				and ca.CostComponentID = gl.CostComponentID
				and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0
		WHERE 
		--[BL] need to only run this for the costing config specified on the system center MR page
			gl.CostingResultID in (select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = '7f3c4d40-be55-4fde-88b5-93cdf8401090' and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0)
			and gl.TimeClassID = ec.CostingConfigTimeClassID and gl.VariableDirectUnitCost<>0
		GROUP BY
			  gl.OriginalAccountID
			, gl.DepartmentID
			, gl.CostComponentID
			, cr.CostingConfigGuid
			
		UNION ALL
		
		SELECT
			pr.DepartmentID
			, ISNULL(cw.AccountID,0) as AccountID
			, pr.OriginalJobCodeID as JobCodeID
			, pr.OriginalPayCodeID as PayCodeID
			, pr.CostComponentID
			, cr.CostingConfigGuid
			, SUM(pr.VariableDirectUnitCost)/SUM(ca.RVU) as VariableDirectUnitCostPerRVU
			, SUM(pr.VariableDirectUnitCost * pr.Volume) as TotalVariableDirectCost
			, SUM(pr.TotalCost) as TotalCost
		FROM [dss].[FactCostingOutDetailPayroll] pr
			INNER JOIN [dss].[CostingResult] cr on pr.CostingResultID = cr.CostingResultID
			INNER JOIN [fp].[EntityGroupConfig] ec on cr.CostingConfigGuid = ec.CostingConfigGUID
			INNER JOIN [fw].[DimPayCode] pc on pr.OriginalPayCodeID=pc.PayCodeID
			INNER JOIN [dss].[ChargeAllocation] ca on
				ca.CostingConfigGuid = cr.CostingConfigGUID
				and ca.ChargeCodeID = pr.ChargeCodeID 
				and ca.DepartmentID = pr.DepartmentID
				and ca.CostComponentID = pr.CostComponentID
				and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0
			LEFT JOIN [clientob].[FactPayrollToAccountCrosswalk] cw on pr.OriginalJobCodeID = cw.JobCodeID AND pc.PayCodeGroupID = cw.PayCodeGroupID AND cw.UnitTypeID = 34
		WHERE 
		--[BL] need to only run this for the costing config specified on the system center MR page
			pr.CostingResultID in (select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = '7f3c4d40-be55-4fde-88b5-93cdf8401090' and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0)
			and pr.TimeClassID = ec.CostingConfigTimeClassID and pr.VariableDirectUnitCost<>0
		GROUP BY
			  cw.AccountID
			, pr.OriginalJobCodeID
			, pr.OriginalPayCodeID
			, pr.DepartmentID
			, pr.CostComponentID
			, cr.CostingConfigGuid
	
	COMMIT		

	DECLARE @DepartmentCursor CURSOR,
		@DepartmentID INT,
		@DepartmentName Nvarchar(200),
		@TotalNumberDepts nvarchar(10),
		@CurrentDepartment nvarchar(10),
		@Message NvarChar(400),
		@time char(8)

	SET @DepartmentCursor = CURSOR FOR (SELECT DISTINCT DepartmentID FROM (Select DepartmentID from [dss].[FactDepartmentChargeSummary] WHERE IsDeleted = 0
																			UNION ALL
																			Select DepartmentID from [int].[FactCDM]) A 
																			)
	SET @TotalNumberDepts = (SELECT COUNT(distinct DepartmentID) FROM (Select DepartmentID from [dss].[FactDepartmentChargeSummary] WHERE IsDeleted = 0
																			UNION ALL
																			Select DepartmentID from [int].[FactCDM]) A 
																			)
	SET @CurrentDepartment = 0
	OPEN @DepartmentCursor 
	FETCH NEXT FROM @DepartmentCursor 
	INTO @DepartmentID
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		
		SET @CurrentDepartment = @CurrentDepartment + 1
		SET @DepartmentName = (SELECT NAME FROM FW.DimDepartment WHERE DepartmentID=@DepartmentID)
		Set @Message = 'Department: ' + @DepartmentName + ' ' + @CurrentDepartment + ' of ' + @TotalNumberDepts
		SET @time= convert (varchar(30), getdate(), 8)
		RAISERROR (@Message, 0, 1, @time) WITH NOWAIT

		BEGIN TRANSACTION
		INSERT INTO [fw].[ABBFlexingReconciliationCostingData]
		
		SELECT
		     charge.CostingConfigGUID
		    , dept.EntityID
		    , Volume.DepartmentID AS OriginalDepartmentID
			, ISNULL(cost.OriginalJobCodeID,0) AS OriginalJobCodeID
		    , ISNULL(cost.OriginalPayCodeID,0) AS OriginalPayCodeID
			, ISNULL(cost.OriginalAccountID,0) AS OriginalAccountID
		    , Volume.ChargeCodeID
		    , Volume.FiscalYearID
		    , Volume.FiscalMonthID
		    , COALESCE(cost.CostComponentID, Charge.CostComponentID) AS CostComponentID
		    , CASE WHEN Volume.TimeClassID = 1 THEN ISNULL(cost.FixedDirectUnitCost,0) ELSE 0.0 END AS FixedDirectUnitCost
			, CASE WHEN Volume.TimeClassID = 1 THEN ISNULL(cost.VariableDirectUnitCost,0) ELSE 0.0 END AS VariableDirectUnitCost
		    , CASE WHEN Volume.TimeClassID = 2 THEN ISNULL(cost.FixedDirectUnitCost,0) ELSE 0.0 END AS BudgetFixedDirectUnitCost
			, CASE WHEN Volume.TimeClassID = 2 THEN ISNULL(cost.VariableDirectUnitCost,0) ELSE 0.0 END AS BudgetVariableDirectUnitCost
		    , CASE WHEN Volume.TimeClassID = 1 THEN volume.Volume ELSE 0.0 END AS ActualMonthlyVolume
		    , CASE WHEN Volume.TimeClassID = 2 THEN volume.Volume ELSE 0.0 END AS BudgetedMonthlyVolume
		    , ISNULL(charge.RVU, 0.0) as RVU
		FROM
		     (SELECT fdcs.DepartmentID, fdcs.ChargeCodeID, fdcs.FiscalYearID, fdcs.TimeClassID, fdcs.FiscalMonthID, SUM(fdcs.Volume) AS Volume
				FROM [dss].[FactDepartmentChargeSummary] fdcs
				WHERE fdcs.IsDeleted = 0 and FiscalYearID=2017 --[BL] NEED TO UPDATE THIS JOIN TO ONLY INCL THE TARGET FISCAL YEAR
				GROUP BY fdcs.DepartmentID, fdcs.ChargeCodeID, fdcs.FiscalYearID, fdcs.TimeClassID, fdcs.FiscalMonthID
			  UNION ALL
		      SELECT cdm.DepartmentID, cdm.ChargeCodeID, cdm.FiscalYearID, cdm.TimeClassID, cdm.FiscalMonthID, SUM(cdm.Value) as Volume
		        FROM [int].[FactCDM] cdm 
		        WHERE cdm.UnitTypeID = 145 and TimeClassID = 2 and FiscalYearID=2017 --[BL] NEED TO UPDATE THIS JOIN TO ONLY INCL THE TARGET FISCAL YEAR
		        GROUP BY cdm.DepartmentID, cdm.ChargeCodeID, cdm.FiscalYearID, cdm.TimeClassID, cdm.FiscalMonthID
			  ) Volume
			  LEFT JOIN
		      (SELECT OriginalDepartmentID, CostingResultID, ChargeCodeID, FiscalYearID, TimeClassID, CostComponentID, OriginalAccountID, 0 as OriginalPayCodeID, 0 as OriginalJobCodeID, Volume, FixedDirectUnitCost, VariableDirectUnitCost FROM [dss].[FactCostingOutDetailGL]
		        UNION 
		        SELECT OriginalDepartmentID, CostingResultID, ChargeCodeID, FiscalYearID, TimeClassID, CostComponentID, ISNULL(cw.AccountID,0.0) as OriginalAccountID, OriginalPayCodeID, OriginalJobCodeID, Volume, FixedDirectUnitCost, VariableDirectUnitCost 
		        FROM [dss].[FactCostingOutDetailPayroll] p
		        INNER JOIN [fw].[DimPayCode] pc on p.OriginalPayCodeID=pc.PayCodeID
		        LEFT JOIN [clientob].[FactPayrollToAccountCrosswalk] cw on p.OriginalJobCodeID = cw.JobCodeID AND pc.PayCodeGroupID = cw.PayCodeGroupID AND cw.UnitTypeID = 34
		        ) as cost
					  ON Volume.DepartmentID = cost.OriginalDepartmentID
					  AND Volume.ChargeCodeID = cost.ChargeCodeID
					  AND Volume.FiscalYearID = cost.FiscalYearID
					  AND Volume.TimeClassID = cost.TimeClassID
			  INNER JOIN [dss].[CostingResult] cr
			  		  ON cost.CostingResultID = cr.CostingResultID
			  INNER JOIN [fw].[DimDepartment] dept
			  		  ON dept.DepartmentID = Volume.DepartmentID
			  LEFT JOIN
		     (SELECT ca.DepartmentID, ca.ChargeCodeID, ca.CostComponentID, ca.CostingConfigGuid, ca.RVU
		        FROM [dss].[ChargeAllocation] ca
		        WHERE ca.AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0
				AND CostingConfigGuid='7f3c4d40-be55-4fde-88b5-93cdf8401090'
			  ) charge
			  	      ON Volume.DepartmentID = charge.DepartmentID
					  AND Volume.ChargeCodeID = charge.ChargeCodeID
					  AND cost.CostComponentID = charge.CostComponentID
					  AND cr.CostingConfigGuid = charge.CostingConfigGuid
		WHERE cost.CostingResultID in (SELECT CostingResultID FROM (SELECT CostingConfigGuid, MAX(CostingResultID) as CostingResultID FROM [dss].[CostingResult] WHERE CostingConfigGuid='7f3c4d40-be55-4fde-88b5-93cdf8401090' and IsMarkedForDeletion = 0 AND IsActivityBasedDetail = 1 GROUP BY CostingConfigGuid) cr2)
		      AND (Volume.DepartmentID=@DepartmentID)
		
		COMMIT
				
		FETCH NEXT FROM @DepartmentCursor INTO @DepartmentID 
	END
	
	CLOSE @DepartmentCursor
	DEALLOCATE @DepartmentCursor	
 END
GO


---------------------------------------------

-- fw.procABBMRTransferFlexedPayrollSampledMonthlyToFactGLSampled
CREATE PROC [fw].[procABBMRTransferFlexedPayrollSampledMonthlyToFactGLSampled] 
	@fiscalYearID int,
	@CostingResultID int
AS
/* ************************************************************************************************************************
** Author: BL/NL
** Create Date: 2016-08-05
** Description: Runs GL flexing for MR
** Last Modified: 2016-08-05
**************************************************************************************************************************
** Change History
**************************************************************************************************************************
** CID		Date		Author	WI			Description
** 1		2017-10-09	PA		D-06466		Filter for ABB depts and IsDeleted
*************************************************************************************************************************/

DECLARE @higuid UNIQUEIDENTIFIER

EXEC procLogScript 'Sampling Flexed Payroll Sample to GL Sample: See procABBMRTransferFlexedPayrollSampledMonthlytoFactGLSampled_NMC_CUSTOM_TEMP' , @higuid output 

SELECT DISTINCT DepartmentID
INTO #ABBDepts
FROM (
	SELECT DepartmentID FROM [dss].[FactCostingOutDetailGL] WHERE CostingResultID = @CostingResultID
	UNION ALL
	SELECT DepartmentID FROM [dss].[FactCostingOutDetailPayroll] WHERE CostingResultID = @CostingResultID) depts;

SELECT
	p.[DepartmentID]
	, cw.[AccountID]
	, p.[FiscalYearID]
	, p.[FiscalMonthID]
	, p.[TimeClassID]
	, p.[IsDeleted]
	, @higuid as [HistoryItemGUID]
	, SUM(p.Hours) as [Units]
	, SUM(p.HoursYTD) as [UnitsYTD]
	, SUM(p.HoursPriorYear) as [UnitsPriorYear]
	, SUM(p.HoursPriorYTD) as [UnitsPriorYTD]
	, SUM(p.[Dollars]) as Dollars
	, SUM(p.[DollarsYTD]) as DollarsYTD
	, SUM(p.[DollarsPriorYear]) as DollarsPriorYear
	, SUM(p.[DollarsPriorYTD]) as DollarsPriorYTD
	, p.[TransactionID]
INTO #FlexPayroll
FROM [fw].[FactPayrollSampledMonthly] p
INNER JOIN [clientob].[FactPayrollToAccountCrosswalk] cw on p.JobCodeID = cw.JobCodeID AND p.PayCodeGroupID = cw.PayCodeGroupID AND cw.UnitTypeID = 34
INNER JOIN [fw].[DimDepartment] dept on p.DepartmentID = dept.DepartmentID
INNER JOIN #ABBDepts abb ON p.DepartmentID = abb.DepartmentID
WHERE TimeClassID = 4 AND FiscalYearID = @fiscalYearID 
AND cw.IsDeleted = 0
GROUP BY
	p.[DepartmentID]
	, cw.[AccountID]
	, p.[FiscalYearID]
	, p.[FiscalMonthID]
	, p.[TimeClassID]
	, p.[IsDeleted]
	, p.[TransactionID];

DELETE GL
FROM [fw].[FactGLSampled] GL
	WHERE EXISTS 
		(SELECT 1
			FROM #FlexPayroll PR
			WHERE GL.DepartmentID=PR.DepartmentID
			AND GL.AccountID=PR.AccountID
			AND GL.FiscalYearID=PR.FiscalYearID
			AND GL.FiscalMonthID=PR.FiscalMonthID
			AND GL.TimeClassID=PR.TimeClassID);

INSERT INTO [fw].[FactGLSampled]
([DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID], [IsDeleted], [HistoryItemGUID], [Units], [UnitsYTD], [UnitsPriorYear], [UnitsPriorYTD], [Dollars], [DollarsYTD], [DollarsPriorYear], [DollarsPriorYTD], [TransactionID])
SELECT [DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID], [IsDeleted], [HistoryItemGUID], [Units], [UnitsYTD], [UnitsPriorYear], [UnitsPriorYTD], [Dollars], [DollarsYTD], [DollarsPriorYear], [DollarsPriorYTD], [TransactionID]
FROM #FlexPayroll;

DROP TABLE #FlexPayroll;
GO


---------------------------------------------

-- fw.procCopyFactGLBudgetToImport
CREATE PROCEDURE fw.procCopyFactGLBudgetToImport (@HistoryItemGUID uniqueidentifier) as 
BEGIN
/************************************************************
** Author: ipetriv
** Create Date: 2018-01-15
** Description: Add procedure to calc EfficiencyFactor
** Last Modified: 2017-01-15
** GM Release: 2018.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2018-01-15	IP		B-18301		Created 
*************************************************************/

DECLARE @FiscalYearId INT = (
		SELECT setting
		FROM dbsetting
		WHERE NAME = 'Current_GL_YearID'
		)

IF OBJECT_ID('int.FactGLHistory', 'U') IS NOT NULL
	DROP TABLE INT.FactGLHistory;

SELECT RowID,
	[DepartmentID],
	[DepartmentCode],
	[AccountID],
	[AccountCode],
	[FiscalYearID],
	[FiscalYearCode],
	[TimeClassID],
	[TimeClassCode],
	[FiscalMonthID],
	[FiscalMonthCode],
	[Value],
	[IsDeleted],
	[HistoryItemGUID],
	[Version],
	[TransactionID],
	getdate() AS BCP_DTTime
INTO INT.FactGLHistory
FROM INT.FactGL
WHERE FiscalYearID = @FiscalYearId
	AND TimeClassID = 2

CREATE UNIQUE CLUSTERED INDEX IX_FactGLHistory ON [int].[FactGLHistory] (
	[FiscalMonthID] ASC,
	[IsDeleted] ASC,
	[FiscalYearID] ASC,
	[TimeClassID] ASC,
	[DepartmentID] ASC,
	[AccountID] ASC,
	[RowID] ASC
	) ON [PRIMARY]

WHILE 1 = 1
BEGIN
	DELETE TOP (10000) iGL
	FROM [int].FactGL iGL
	INNER JOIN INT.FactGLHistory iGLH ON iGL.[FiscalMonthID] = iGLH.[FiscalMonthID]
		AND iGL.[IsDeleted] = iGLH.[IsDeleted]
		AND iGL.[FiscalYearID] = iGLH.[FiscalYearID]
		AND iGL.[TimeClassID] = iGLH.[TimeClassID]
		AND iGL.[DepartmentID] = iGLH.[DepartmentID]
		AND iGL.[AccountID] = iGLH.[AccountID]
		AND iGL.[RowID] = iGLH.[RowID]

	IF @@ROWCOUNT < 10000
		BREAK;
END

INSERT INTO [int].FactGL (
	DepartmentID,
	DepartmentCode,
	AccountID,
	AccountCode,
	FiscalYearID,
	FiscalYearCode,
	TimeClassID,
	TimeClassCode,
	FiscalMonthID,
	FiscalMonthCode,
	Value,
	IsDeleted,
	HistoryItemGUID,
	TransactionID
	)
SELECT gl.DepartmentID,
	dd.DepartmentCode,
	gl.AccountID,
	da.AccountCode,
	gl.FiscalYearID,
	gl.FiscalYearID AS FiscalYearCode,
	gl.TimeClassID,
	dtm.TimeClassCode,
	gl.FiscalMonthID,
	dfm.FiscalMonthCode,
	sum(CASE 
			WHEN A.Inversion = - 1
				THEN GL.Dollars * - 1
			ELSE GL.Dollars
			END) AS Value,
	0 IsDeleted,
	@HistoryItemGUID AS HistoryItemGUID,
	0 AS TransactionID
FROM fw.FactGLSampled GL
INNER JOIN fw.DimAccount A ON A.AccountID = GL.AccountID
INNER JOIN fw.DimTimeClass dtm ON dtm.TimeClassID = gl.TimeClassID
INNER JOIN fw.DimDepartment dd ON dd.DepartmentID = gl.DepartmentID
INNER JOIN fw.DimAccount da ON da.AccountID = gl.AccountID
INNER JOIN fw.DimFiscalMonth dfm ON dfm.FiscalMonthID = gl.FiscalMonthID
WHERE gl.TimeClassID = 2 -- Data transferred will be the sampled budgeted data
	AND FiscalYearID = @FiscalYearId
	AND Dollars <> 0.0
GROUP BY gl.DepartmentID,
	dd.DepartmentCode,
	gl.AccountID,
	da.AccountCode,
	gl.FiscalYearID,
	gl.TimeClassID,
	dtm.TimeClassCode,
	gl.FiscalMonthID,
	dfm.FiscalMonthCode
END
GO


---------------------------------------------

-- fw.procCopyFactPayrollDollarsToGLMonthly
CREATE PROCEDURE [fw].[procCopyFactPayrollDollarsToGLMonthly]
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
** 1
** 2		2019-02-15	OV			D-07848 In Management Reporting, salaries and wages metrics for fixed departments are flexing
** 3		2019-02-19	KF			D-08138 MR Flexing: Flex GL values should be 0 for mapped accounts if there is no Payroll data
** 4        2019-03-19   OV        D-08253 Used temp table for @DepartmentAccountVariabilityOverrides
** 5        2019-03-26   OV        D-08253 Optimize procedure
*************************************************************/
(
  @FiscalYearID int = 0,
  @PriorYearsCount int = 0,
  @DepartmentAccountVariabilityOverrides [ob].[DepartmentAccountVariabilityOverride] READONLY 
)
AS
BEGIN

DECLARE @TimeClassID TINYINT = 4 --Flex
DECLARE @UnitTypeID TINYINT  = 34 --Dollars
DECLARE @StartFiscalYear INT = @FiscalYearID - @PriorYearsCount
DECLARE @EndFiscalYear INT = @FiscalYearID

IF @FiscalYearID = 0
BEGIN
  SELECT @StartFiscalYear = MIN(FiscalYearID) FROM (
     SELECT MIN(FiscalYearID) AS FiscalYearID FROM fw.FactPayrollSampledMonthly
	 UNION ALL
	 SELECT MIN(FiscalYearID) AS FiscalYearID FROM fw.FactGLSampled) S

  SELECT @EndFiscalYear = MAX(FiscalYearID) FROM (
     SELECT MAX(FiscalYearID) AS FiscalYearID FROM fw.FactPayrollSampledMonthly
	 UNION ALL
	 SELECT MAX(FiscalYearID) AS FiscalYearID FROM fw.FactGLSampled) S
END

DECLARE @MappingMode INT
SELECT TOP 1 @MappingMode = CASE [PropertyXML].value('(/Properties//PayRollToGLLinkDollarsConfiguration/node())[1]', 'nvarchar(max)')
  WHEN 'EachJobCode' THEN 1
  WHEN 'EachPayCodeGroup' THEN 2
  ELSE 0 END -- BothUnique or BothOverride
FROM SystemCenterStep WHERE GlobalID = 'PayrolltoGLLinkSelection'

IF OBJECT_ID('tempdb..#department') IS NOT NULL  DROP TABLE #department
IF OBJECT_ID('tempdb..#tempCrosswalk') IS NOT NULL  DROP TABLE #tempCrosswalk
IF OBJECT_ID('tempdb..#DepAcc_P_GL') IS NOT NULL  DROP TABLE #DepAcc_P_GL
IF OBJECT_ID('tempdb..#Source') IS NOT NULL  drop table #Source
IF OBJECT_ID('tempdb..#FactGL_1') IS NOT NULL  drop table #FactGL_1
IF OBJECT_ID('tempdb..#FactGL_2 ') IS NOT NULL  drop table #FactGL_2 
IF OBJECT_ID('tempdb..#Payroll_JC_PCG') IS NOT NULL  drop table #Payroll_JC_PCG
IF OBJECT_ID('tempdb..#payroll') IS NOT NULL  drop table #payroll


IF OBJECT_ID('tempdb..#DepartmentAccountVariabilityOverride') IS NOT NULL DROP TABLE #DepartmentAccountVariabilityOverride
CREATE TABLE #DepartmentAccountVariabilityOverride (AccountID int, DepartmentID int, Variability decimal(19,8))

INSERT INTO #DepartmentAccountVariabilityOverride (AccountID,  DepartmentID, Variability)
select AccountID,  DepartmentID, Variability FROM @DepartmentAccountVariabilityOverrides
----
SELECT departmentID,AccountID
into #DepAcc_P_GL
FROM (
select departmentID, AccountId
from fw.FactGLSampled 
union
select DepartmentID, accountID
from fw.FactPayrollSampledMonthly
cross join clientob.FactPayrollToAccountCrosswalk c
) t
 
-----
select d.DepartmentID,AccountID, isvariable 
into  #department
FROM #DepAcc_P_GL DepAcc_P_GL
inner join fw.DimDepartment d on DepAcc_P_GL.departmentID = d.departmentID
where d.IsMRPlan = 1

-----
SELECT aa.AccountID, cc.UnitTypeID, aa.Variability, FY.FiscalYearID, FM.FiscalMonthID,
CASE WHEN @MappingMode IN(0,1) then cc.JobCodeId else -10001 END AS JobCodeID,
CASE WHEN @MappingMode IN(0,2) then CC.payCodeGroupID else -10001 END AS PayCodeGroupID
into #tempCrosswalk
from clientob.FactPayrollToAccountCrosswalk cc
inner join fw.DimAccount aa on cc.AccountID = aa.AccountID
        CROSS JOIN fw.DimFiscalYear FY
        CROSS JOIN fw.DimFiscalMonth FM
where CC.UnitTypeID = @UnitTypeID and FY.FiscalYearID BETWEEN @StartFiscalYear AND @EndFiscalYear and FM.FiscalMonthID != 0

-----
select SUM(p.Dollars) as Dollars ,p.FiscalYearID, p.FiscalMonthID,
CASE WHEN @MappingMode IN(0,1) then JobCodeId else -10001 END AS JobCodeID,
CASE WHEN @MappingMode IN(0,2) then payCodeGroupID else -10001 END AS PayCodeGroupID,
DepartmentID
INTO #Payroll_JC_PCG
FROM fw.FactPayrollSampledMonthly P
WHERE P.TimeClassID =  @TimeClassID
	 AND P.IsDeleted = 0 
GROUP BY p.FiscalYearID, p.FiscalMonthID, p.JobCodeID, p.PayCodeGroupID, p.DepartmentID

-----
SELECT FactGL.FiscalYearID, FactGL.FiscalMonthId, FactGL.AccountID, FactGL.DepartmentID, FactGL.Dollars as Dollars 
INTO #FactGL_1
FROM fw.FactGLSampled FactGL 
WHERE FactGL.TimeclassID = 20 AND FactGL.IsDeleted = 0

-----
select FactGl.DepartmentID, Cw.AccountID, cw.FiscalYearID, cw.FiscalMonthID, FactGL.Dollars,CW.Variability * D.IsVariable as Koef_var
INTO #FactGL_2
from (SELECT distinct AccountId,FiscalYearID,FiscalMonthID,Variability FROM #tempCrosswalk) cw
INNER JOIN #FactGL_1 FactGL on 
		     FactGL.FiscalYearID = CW.FiscalYearID 
		     AND FactGL.FiscalMonthID = CW.FiscalMonthID
			 AND FactGL.AccountID = CW.AccountID
 INNER JOIN fw.DimDepartment d on FactGL.departmentID = d.departmentID

-----
SELECT DD.DepartmentID, X.AccountID, X.FiscalYearID, X.FiscalMonthID, X.Dollars, X.Variability * DD.IsVariable as Koef_var
INTO #payroll
FROM (
select  Cw.AccountID, cw.FiscalYearID, cw.FiscalMonthID, CW.Variability, SUM(ROUND(p.Dollars,6)) as Dollars, P.DepartmentID
from (SELECT distinct AccountId,JobCodeID,PayCodeGroupID,FiscalYearID,FiscalMonthID,Variability FROM #tempCrosswalk) cw
inner join #Payroll_JC_PCG P ON
			P.FiscalYearID = CW.FiscalYearID
			AND P.FiscalMonthID = CW.FiscalMonthID
			AND CW.JobCodeID = P.JobCodeID
	        AND CW.PayCodeGroupID = P.PayCodeGroupID
GROUP BY Cw.AccountID, cw.FiscalYearID, cw.FiscalMonthID, cw.Variability, P.DepartmentID
) X
INNER JOIN #department dd on DD.AccountID = X.AccountID and X.DepartmentID = Dd.DepartmentID

-----
SELECT ISNULL(GL.DepartmentID,p.DepartmentID) as DepartmentID,
ISNULL(GL.AccountId,p.AccountId) as AccountId,
ISNULL(GL.FiscalYearId,p.FiscalYearId) as FiscalYearId,
ISNULL(GL.FiscalMonthId,p.FiscalMonthId) as FiscalMonthId,
ISNULL(ISNULL(DAV.Variability,P.Koef_var) * P.Dollars, 0) + isnull((1-ISNULL(DAV.Variability,Gl.Koef_var)) *GL.Dollars,0) as Dollars
INTO #Source
FROM #FactGL_2 GL
FULL JOIN #payroll p on GL.AccountId = p.AccountId and GL.DepartmentID = p.DepartmentID and GL.FiscalYearId = p.FiscalYearId and GL.FiscalMonthId = p.FiscalMonthId
LEFT JOIN #DepartmentAccountVariabilityOverride DAV ON
		     ISNULL(GL.DepartmentID,p.DepartmentID) = DAV.DepartmentID
		     AND ISNULL(GL.AccountID,p.AccountId) = DAV.AccountID 
----
MERGE fw.FactGLSampled AS TARGET
USING #Source  AS SOURCE ON
    TARGET.DepartmentID = SOURCE.DepartmentID
    AND TARGET.AccountID = SOURCE.AccountID
    AND TARGET.FiscalYearID = SOURCE.FiscalYearID
    AND TARGET.FiscalMonthID = SOURCE.FiscalMonthID
    AND TARGET.TimeClassID = @TimeClassID
    AND TARGET.IsDeleted = 0
WHEN MATCHED AND TARGET.Dollars != SOURCE.Dollars THEN 
  UPDATE SET TARGET.Dollars = SOURCE.Dollars
WHEN NOT MATCHED BY TARGET THEN
  INSERT (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Dollars)
  VALUES (SOURCE.DepartmentID, SOURCE.AccountID, SOURCE.FiscalYearID, SOURCE.FiscalMonthID, @TimeClassID, SOURCE.Dollars);
  
END
GO


---------------------------------------------

-- fw.procCopyFactPayrollHoursToStatisticsMonthly
CREATE PROCEDURE [fw].[procCopyFactPayrollHoursToStatisticsMonthly]
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
** 1
** 2		2019-02-15	OV			D-07848 In Management Reporting, salaries and wages metrics for fixed departments are flexing
** 3		2019-02-19	KF			D-08138 MR Flexing: Flex GL values should be 0 for mapped accounts if there is no Payroll data
** 4      2019-03-19   OV        D-08253 - used temp table for @DepartmentAccountVariabilityOverrides
** 5      2019-03-26   OV        D-08253 - optimize proc
*************************************************************/
(
  @FiscalYearID int = 0,
  @PriorYearsCount int = 0,
  @DepartmentAccountVariabilityOverrides [ob].[DepartmentAccountVariabilityOverride] READONLY 
)
AS
BEGIN
DECLARE @TimeClassID TINYINT = 4 --Flex
DECLARE @UnitTypeID TINYINT  = 51 --Hours
DECLARE @StartFiscalYear INT = @FiscalYearID - @PriorYearsCount
DECLARE @EndFiscalYear INT = @FiscalYearID

IF @FiscalYearID = 0
BEGIN
  SELECT @StartFiscalYear = MIN(FiscalYearID) FROM (
     SELECT MIN(FiscalYearID) AS FiscalYearID FROM fw.FactPayrollSampledMonthly
	 UNION ALL
	 SELECT MIN(FiscalYearID) AS FiscalYearID FROM fw.FactGLSampled) S

  SELECT @EndFiscalYear = MAX(FiscalYearID) FROM (
     SELECT MAX(FiscalYearID) AS FiscalYearID FROM fw.FactPayrollSampledMonthly
	 UNION ALL
	 SELECT MAX(FiscalYearID) AS FiscalYearID FROM fw.FactGLSampled) S
END

DECLARE @MappingMode INT
SELECT TOP 1 @MappingMode = CASE [PropertyXML].value('(/Properties//PayRollToGLLinkHoursConfiguration/node())[1]', 'nvarchar(max)')
  WHEN 'EachJobCode' THEN 1
  WHEN 'EachPayCodeGroup' THEN 2
  ELSE 0 END -- BothUnique or BothOverride
FROM SystemCenterStep WHERE GlobalID = 'PayrolltoGLLinkSelection'

IF OBJECT_ID('tempdb..#department') IS NOT NULL  DROP TABLE #department
IF OBJECT_ID('tempdb..#tempCrosswalk') IS NOT NULL  DROP TABLE #tempCrosswalk
IF OBJECT_ID('tempdb..#DepAcc_P_Stat') IS NOT NULL  DROP TABLE #DepAcc_P_Stat
IF OBJECT_ID('tempdb..#Source') IS NOT NULL  drop table #Source
IF OBJECT_ID('tempdb..#Stat_1') IS NOT NULL  drop table #Stat_1
IF OBJECT_ID('tempdb..#Stat_2 ') IS NOT NULL  drop table #Stat_2 
IF OBJECT_ID('tempdb..#Payroll_JC_PCG') IS NOT NULL  drop table #Payroll_JC_PCG
IF OBJECT_ID('tempdb..#payroll') IS NOT NULL  drop table #payroll

IF OBJECT_ID('tempdb..#DepartmentAccountVariabilityOverride') IS NOT NULL DROP TABLE #DepartmentAccountVariabilityOverride
CREATE TABLE #DepartmentAccountVariabilityOverride (AccountID int, DepartmentID int, Variability decimal(19,8))

INSERT INTO #DepartmentAccountVariabilityOverride (AccountID,  DepartmentID, Variability)
select AccountID,  DepartmentID, Variability FROM @DepartmentAccountVariabilityOverrides
----
SELECT departmentID,AccountID
into #DepAcc_P_Stat
FROM (
select departmentID, AccountId
from fw.FactStatisticSampledMonthly
union
select DepartmentID, accountID
from fw.FactPayrollSampledMonthly
cross join clientob.FactPayrollToAccountCrosswalk c
) t

-----
select d.DepartmentID, DepAcc_P_Stat.AccountID, d.isvariable 
into  #department
FROM #DepAcc_P_Stat DepAcc_P_Stat
inner join fw.DimDepartment d on DepAcc_P_Stat.departmentID = d.departmentID
where d.IsMRPlan = 1

-----
SELECT aa.AccountID, UnitTypeID, aa.Variability, FY.FiscalYearID, FM.FiscalMonthID,
CASE WHEN @MappingMode IN(0,1) then cc.JobCodeId else -10001 END AS JobCodeID,
CASE WHEN @MappingMode IN(0,2) then CC.payCodeGroupID else -10001 END AS PayCodeGroupID
into #tempCrosswalk
from clientob.FactPayrollToAccountCrosswalk cc
inner join fw.DimAccount aa on cc.AccountID = aa.AccountID
        CROSS JOIN fw.DimFiscalYear FY
        CROSS JOIN fw.DimFiscalMonth FM
where CC.UnitTypeID = @UnitTypeID and FY.FiscalYearID BETWEEN @StartFiscalYear AND @EndFiscalYear and FM.FiscalMonthID != 0

-----
select SUM(p.Hours) as Hours, p.FiscalYearID, p.FiscalMonthID,
CASE WHEN @MappingMode IN(0,1) then p.JobCodeId else -10001 END AS JobCodeID,
CASE WHEN @MappingMode IN(0,2) then p.payCodeGroupID else -10001 END AS PayCodeGroupID,
p.DepartmentID
INTO #Payroll_JC_PCG
FROM fw.FactPayrollSampledMonthly P
WHERE P.TimeClassID = @TimeClassID
	 AND P.IsDeleted = 0 
GROUP BY FiscalYearID,FiscalMonthID,JobCodeID,PayCodeGroupID, DepartmentID
-----
SELECT Stat.FiscalYearID, Stat.FiscalMonthId, Stat.AccountID, Stat.DepartmentID, Stat.Amount as Hours 
INTO #Stat_1
FROM fw.FactStatisticSampledMonthly Stat 
WHERE Stat.TimeclassID = 20 AND Stat.IsDeleted = 0

-----
select Stat.DepartmentID, Cw.AccountID, cw.FiscalYearID, cw.FiscalMonthID, Hours, CW.Variability * D.IsVariable as Koef_var
INTO #Stat_2
from (SELECT distinct AccountId,FiscalYearID,FiscalMonthID,Variability FROM #tempCrosswalk) cw
INNER JOIN #Stat_1 Stat on 
		     Stat.FiscalYearID = CW.FiscalYearID 
		     AND Stat.FiscalMonthID = CW.FiscalMonthID
			 AND Stat.AccountID = CW.AccountID
 INNER JOIN fw.DimDepartment d on Stat.departmentID = d.departmentID
 -----
SELECT DD.DepartmentID, X.AccountID, X.FiscalYearID, X.FiscalMonthID, X.Hours, X.Variability * DD.IsVariable as Koef_var
INTO #payroll
FROM (
select  Cw.AccountID, cw.FiscalYearID, cw.FiscalMonthID, CW.Variability, SUM(ROUND(P.Hours,6)) as Hours, P.DepartmentID
from (SELECT distinct AccountId,JobCodeID,PayCodeGroupID,FiscalYearID,FiscalMonthID,Variability FROM #tempCrosswalk) cw
inner join #Payroll_JC_PCG P ON
			P.FiscalYearID = CW.FiscalYearID
			AND P.FiscalMonthID = CW.FiscalMonthID
			AND CW.JobCodeID = P.JobCodeID
	        AND CW.PayCodeGroupID = P.PayCodeGroupID
GROUP BY Cw.AccountID, cw.FiscalYearID, cw.FiscalMonthID, CW.Variability, P.DepartmentID
) X
INNER JOIN #department dd on DD.AccountID = X.AccountID and dd.DepartmentID = X.DepartmentID

-----
SELECT ISNULL(Stat.DepartmentID,p.DepartmentID) as DepartmentID,
ISNULL(Stat.AccountId,p.AccountId) as AccountId,
ISNULL(Stat.FiscalYearId,p.FiscalYearId) as FiscalYearId,
ISNULL(Stat.FiscalMonthId,p.FiscalMonthId) as FiscalMonthId,
ISNULL(ISNULL(DAV.Variability,p.Koef_var) * P.Hours, 0) + isnull((1-ISNULL(DAV.Variability,Stat.Koef_var)) *Stat.Hours,0) as Hours
INTO #Source
FROM #Stat_2 Stat
FULL JOIN #payroll p on Stat.AccountId = p.AccountId and Stat.DepartmentID = p.DepartmentID and Stat.FiscalYearId = p.FiscalYearId and Stat.FiscalMonthId = p.FiscalMonthId
LEFT JOIN #DepartmentAccountVariabilityOverride DAV ON
		     ISNULL(Stat.DepartmentID,p.DepartmentID) = DAV.DepartmentID
		     AND ISNULL(Stat.AccountID,p.AccountId) = DAV.AccountID 

----
MERGE fw.FactStatisticSampledMonthly AS TARGET
USING #Source  AS SOURCE ON
    TARGET.DepartmentID = SOURCE.DepartmentID
    AND TARGET.AccountID = SOURCE.AccountID
    AND TARGET.FiscalYearID = SOURCE.FiscalYearID
    AND TARGET.FiscalMonthID = SOURCE.FiscalMonthID
    AND TARGET.TimeClassID = @TimeClassID
    AND TARGET.IsDeleted = 0
WHEN MATCHED AND TARGET.Amount != SOURCE.Hours THEN 
  UPDATE SET TARGET.Amount = SOURCE.Hours
WHEN NOT MATCHED BY TARGET THEN
  INSERT (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount)
  VALUES (SOURCE.DepartmentID, SOURCE.AccountID, SOURCE.FiscalYearID, SOURCE.FiscalMonthID, @TimeClassID, SOURCE.Hours);

  
END
GO


---------------------------------------------

-- fw.procCopyFactStaffingBudgetToImport
CREATE PROCEDURE fw.procCopyFactStaffingBudgetToImport (@HistoryItemGUID uniqueidentifier)
AS
BEGIN
/************************************************************
** Author: ipetriv
** Create Date: 2018-01-15
** Description: Add procedure to calc EfficiencyFactor
** Last Modified: 2017-01-15
** GM Release: 2018.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2018-01-15	IP		B-18301		Created 
*************************************************************/
	DECLARE @FiscalYearId INT = (
			SELECT setting
			FROM dbsetting
			WHERE NAME = 'Current_GL_YearID'
			)

	IF OBJECT_ID('int.FactStaffingHistory', 'U') IS NOT NULL
		DROP TABLE INT.FactStaffingHistory;

	SELECT RowID,
		DepartmentID,
		DepartmentCode,
		JobCodeID,
		JobCode,
		EmployeeID,
		Employeecode,
		PayCodeID,
		PayCode,
		FiscalYearID,
		FiscalYearCode,
		TimeClassID,
		TimeClassCode,
		UnitTypeID,
		UnitType,
		FiscalMonthID,
		FiscalMonthCode,
		Value,
		IsDeleted,
		HistoryItemGUID,
		Version,
		TransactionID,
		getdate() AS BCP_DTTime
	INTO INT.FactStaffingHistory
	FROM INT.FactStaffing
	WHERE FiscalYearID = @FiscalYearId
		AND TimeClassID = 2

	CREATE UNIQUE CLUSTERED INDEX IX_FactStaffingHistory ON [int].[FactStaffingHistory] (
		[FiscalMonthID] ASC,
		[IsDeleted] ASC,
		[FiscalYearID] ASC,
		[TimeClassID] ASC,
		[DepartmentID] ASC,
		[JobCodeID] ASC,
		[RowID] ASC
		) ON [PRIMARY]

	WHILE 1 = 1
	BEGIN
		DELETE TOP (10000) iST
		FROM [int].FactStaffing iST
		INNER JOIN INT.FactStaffingHistory iSTH ON iST.[FiscalMonthID] = iSTH.[FiscalMonthID]
			AND iST.[IsDeleted] = iSTH.[IsDeleted]
			AND iST.[FiscalYearID] = iSTH.[FiscalYearID]
			AND iST.[TimeClassID] = iSTH.[TimeClassID]
			AND iST.[DepartmentID] = iSTH.[DepartmentID]
			AND iST.[JobCodeID] = iSTH.[JobCodeID]
			AND iST.[RowID] = iSTH.[RowID]

		IF @@ROWCOUNT < 10000
			BREAK;
	END

	INSERT INTO [int].FactStaffing (
		DepartmentID,
		DepartmentCode,
		JobCodeID,
		JobCode,
		EmployeeID,
		Employeecode,
		PayCodeID,
		PayCode,
		FiscalYearID,
		FiscalYearCode,
		TimeClassID,
		TimeClassCode,
		UnitTypeID,
		UnitType,
		FiscalMonthID,
		FiscalMonthCode,
		Value,
		IsDeleted,
		HistoryItemGUID,
		TransactionID
		)
	SELECT PR.DepartmentID,
		dd.DepartmentCode,
		pr.JobCodeID,
		djc.JobCode,
		pr.EmployeeID,
		de.Code AS Employeecode,
		pr.PayCodeID,
		dpc.PayCode,
		pr.FiscalYearID,
		FiscalYearID AS FiscalYearCode,
		pr.TimeClassID,
		dtm.TimeClassCode,
		UnitTypeID,
		UnitType,
		pr.FiscalMonthID,
		dfm.FiscalMonthCode,
		sum(Value),
		0 AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID,
		0 AS TransactionID
	FROM (
		SELECT DepartmentID,
			JobCodeID,
			EmployeeID,
			PayCodeID,
			FiscalYearID,
			TimeClassID,
			CASE 
				WHEN UnitType = 'Dollars'
					THEN 34
				WHEN UnitType = 'Hours'
					THEN 51
				ELSE 0
				END AS UnitTypeID,
			UnitType,
			FiscalMonthID,
			Value
		FROM [fw].[FactPayrollSampledMonthlyDetailed]
		UNPIVOT(Value FOR UnitType IN (
					Dollars,
					Hours
					)) AS unpvt
		WHERE Value <> 0
			AND TimeClassID = 2 -- Data transferred will be the sampled budgeted data
			AND FiscalYearID = @FiscalYearID
		) PR
	INNER JOIN fw.DimTimeClass dtm ON dtm.TimeClassID = PR.TimeClassID
	INNER JOIN fw.DimDepartment dd ON dd.DepartmentID = PR.DepartmentID
	INNER JOIN fw.DimJobCode djc ON djc.JobCodeID = PR.JobCodeID
	INNER JOIN fw.DimPayCode dpc ON dpc.PayCodeID = PR.PayCodeID
	INNER JOIN fw.DimEmployee de ON de.EmployeeID = PR.EmployeeID
	INNER JOIN fw.DimFiscalMonth dfm ON dfm.FiscalMonthID = PR.FiscalMonthID
	GROUP BY PR.DepartmentID,
		dd.DepartmentCode,
		pr.JobCodeID,
		djc.JobCode,
		pr.EmployeeID,
		de.code,
		pr.PayCodeID,
		dpc.PayCode,
		pr.FiscalYearID,
		pr.TimeClassID,
		dtm.TimeClassCode,
		UnitTypeID,
		UnitType,
		pr.FiscalMonthID,
		dfm.FiscalMonthCode
END
GO


---------------------------------------------

-- fw.procCopyFactStatisticBudgetToImport
/************************************************************
** Author: ipetriv
** Create Date: 2018-01-15
** Description: Add procedure to calc EfficiencyFactor
** Last Modified: 2017-01-15
** GM Release: 2018.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2018-01-15	IP		B-18301		Created 
** 2		2018-08-23	OV		D-07498		Removed inversion logic
*************************************************************/
CREATE PROCEDURE [fw].[procCopyFactStatisticBudgetToImport] (@HistoryItemGUID uniqueidentifier) as 
BEGIN
DECLARE @FiscalYearId INT = (
		SELECT setting
		FROM dbsetting
		WHERE NAME = 'Current_GL_YearID'
		)

IF OBJECT_ID('int.FactStatisticHistory', 'U') IS NOT NULL
	DROP TABLE INT.FactStatisticHistory;

SELECT RowID,
	[DepartmentID],
	[DepartmentCode],
	[AccountID],
	[AccountCode],
	[FiscalYearID],
	[FiscalYearCode],
	[TimeClassID],
	[TimeClassCode],
	[FiscalMonthID],
	[FiscalMonthCode],
	[Value],
	[IsDeleted],
	[HistoryItemGUID],
	[Version],
	[TransactionID],
	getdate() AS BCP_DTTime
INTO INT.FactStatisticHistory
FROM INT.FactStatistic
WHERE FiscalYearID = @FiscalYearId
	AND TimeClassID = 2

CREATE UNIQUE CLUSTERED INDEX IX_FactStatisticHistory ON [int].[FactStatisticHistory] (
	[FiscalMonthID] ASC,
	[IsDeleted] ASC,
	[FiscalYearID] ASC,
	[TimeClassID] ASC,
	[DepartmentID] ASC,
	[AccountID] ASC,
	[RowID] ASC
	) ON [PRIMARY]

WHILE 1 = 1
BEGIN
	DELETE TOP (10000) iST
	FROM [int].FactStatistic iST
	INNER JOIN INT.FactStatisticHistory iSTH ON iST.[FiscalMonthID] = iSTH.[FiscalMonthID]
		AND iST.[IsDeleted] = iSTH.[IsDeleted]
		AND iST.[FiscalYearID] = iSTH.[FiscalYearID]
		AND iST.[TimeClassID] = iSTH.[TimeClassID]
		AND iST.[DepartmentID] = iSTH.[DepartmentID]
		AND iST.[AccountID] = iSTH.[AccountID]
		AND iST.[RowID] = iSTH.[RowID]

	IF @@ROWCOUNT < 10000
		BREAK;
END

INSERT INTO [int].FactStatistic (
	DepartmentID,
	DepartmentCode,
	AccountID,
	AccountCode,
	FiscalYearID,
	FiscalYearCode,
	TimeClassID,
	TimeClassCode,
	FiscalMonthID,
	FiscalMonthCode,
	Value,
	IsDeleted,
	HistoryItemGUID,
	TransactionID
	)
SELECT ST.DepartmentID,
	dd.DepartmentCode,
	ST.AccountID,
	da.AccountCode,
	ST.FiscalYearID,
	ST.FiscalYearID AS FiscalYearCode,
	ST.TimeClassID,
	dtm.TimeClassCode,
	ST.FiscalMonthID,
	dfm.FiscalMonthCode,
	sum(ST.Amount) AS Value,
	0 IsDeleted,
	@HistoryItemGUID  AS HistoryItemGUID,
	0 AS TransactionID
FROM fw.FactStatisticSampledMonthly ST
INNER JOIN fw.DimAccount A ON A.AccountID = ST.AccountID
INNER JOIN fw.DimTimeClass dtm ON dtm.TimeClassID = ST.TimeClassID
INNER JOIN fw.DimDepartment dd ON dd.DepartmentID = ST.DepartmentID
INNER JOIN fw.DimAccount da ON da.AccountID = ST.AccountID
INNER JOIN fw.DimFiscalMonth dfm ON dfm.FiscalMonthID = ST.FiscalMonthID
WHERE ST.TimeClassID = 2 -- Data transferred will be the sampled budgeted data
	AND FiscalYearID = @FiscalYearId
	AND Amount <> 0.0
GROUP BY ST.DepartmentID,
	dd.DepartmentCode,
	ST.AccountID,
	da.AccountCode,
	ST.FiscalYearID,
	ST.TimeClassID,
	dtm.TimeClassCode,
	ST.FiscalMonthID,
	dfm.FiscalMonthCode
END
GO


---------------------------------------------

-- fw.procCopySystemGeneratedStatistics
CREATE   PROC fw.procCopySystemGeneratedStatistics
  @departmentIds nvarchar(MAX) = NULL
AS
BEGIN
  SET NOCOUNT ON

  DROP TABLE IF EXISTS #departments

  SELECT val AS DepartmentId
  INTO #departments
  FROM ConvertCSValuesToTable(@departmentIds, ',')

  DECLARE
  @startRowId bigint,
  @maxRowId bigint,
  @endRowId bigint

  IF (@departmentIds IS NULL)
  BEGIN
    TRUNCATE TABLE fw.FactSystemGeneratedStatistics

    SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId)
    FROM fw.FactChargeBasedStatistics

    WHILE (@startRowId <= @maxRowId)
    BEGIN
      SELECT @endRowId = MAX(d.RowId)
      FROM (SELECT TOP 1000000 RowId
              FROM fw.FactChargeBasedStatistics
              WHERE RowId >= @startRowId
              ORDER BY RowID) as d

      INSERT INTO fw.FactSystemGeneratedStatistics (AccountID, DepartmentID, DateID, Value)
      SELECT s.AccountID, s.DepartmentID, s.DateID, s.Value
      FROM fw.FactChargeBasedStatistics s
      WHERE s.RowId >= @startRowId
          AND s.RowId <= @endRowId

      SELECT @startRowId = MIN(d.RowId)
      FROM fw.FactChargeBasedStatistics d
      WHERE RowId > @endRowId
    END
  END
  ELSE
  BEGIN
    DELETE
    FROM fw.FactSystemGeneratedStatistics
    WHERE DepartmentID IN (SELECT DepartmentId FROM #departments)

    INSERT INTO fw.FactSystemGeneratedStatistics (AccountID, DepartmentID, DateID, Value)
    SELECT s.AccountID, s.DepartmentID, s.DateID, s.Value
    FROM fw.FactChargeBasedStatistics s
      JOIN #departments d
        ON s.DepartmentID = d.DepartmentID
  END

END
GO


---------------------------------------------

-- fw.procCopySystemGeneratedStatisticsMonthly
CREATE   PROC fw.procCopySystemGeneratedStatisticsMonthly
  @fiscalYearId smallint = 0
AS
BEGIN
  SET NOCOUNT ON

  IF (@fiscalYearID = 0)
  BEGIN
    TRUNCATE TABLE fw.FactSystemGeneratedStatisticsMonthly

    INSERT INTO fw.FactSystemGeneratedStatisticsMonthly (AccountID, DepartmentID, FiscalYearID, FiscalMonthID, Value)
    SELECT s.AccountID, s.DepartmentID, s.FiscalYearID, s.FiscalMonthID, s.Value
    FROM fw.FactChargeBasedStatisticsMonthly s
  END
  ELSE
  BEGIN
    WHILE EXISTS(SELECT NULL FROM fw.FactSystemGeneratedStatisticsMonthly (nolock) WHERE FiscalYearID = @fiscalYearID)
    BEGIN
      DELETE TOP (1000000) fw.FactSystemGeneratedStatisticsMonthly
      WHERE FiscalYearID = @fiscalYearID
    END

    INSERT INTO fw.FactSystemGeneratedStatisticsMonthly (AccountID, DepartmentID, FiscalYearID, FiscalMonthID, Value)
    SELECT s.AccountID, s.DepartmentID, s.FiscalYearID, s.FiscalMonthID, s.Value
    FROM fw.FactChargeBasedStatisticsMonthly s
    WHERE s.FiscalYearID = @fiscalYearId
  END
END
GO


---------------------------------------------

-- fw.procCreateCapandOBMissingRoles
create proc fw.procCreateCapandOBMissingRoles as

	--Check for Capital Management Permission Set
	if (select COUNT(*) from S3PermissionSet where Name='Capital Management')=1
	begin
		--Check for access - Read allow in Capital Management Permission Set
		if(select COUNT(*) from S3Permission where PermissionSetID=(select PermissionSetID from S3PermissionSet where Name='Capital Management') and RoleID = (Select RoleID from UserRole where Name='Access - Read Allow'))=0
		begin
			insert into S3Permission (PermissionSetID,RoleID,Weight,ReadValue)
			select 
				(select PermissionSetID from S3PermissionSet where Name='Capital Management'),
				RoleID,
				0 as weight,
				1 as ReadValue
			from 
				UserRole
			where 
				Name='Access - Read Allow'
		end
		
		--Check for access - Write allow in Capital Management Permission Set
		if(select COUNT(*) from S3Permission where PermissionSetID=(select PermissionSetID from S3PermissionSet where Name='Capital Management') and RoleID = (Select RoleID from UserRole where Name='Access - Write Allow'))=0
		begin
			insert into S3Permission (PermissionSetID,RoleID,Weight,ReadValue,WriteValue)
			select 
				(select PermissionSetID from S3PermissionSet where Name='Capital Management'),
				RoleID,
				0 as weight,
				1 as ReadValue,
				1 as WriteValue
			from 
				UserRole
			where 
				Name='Access - Write Allow'
		end

	end

	--Check for Operating Budgeting Permission Set
	if (select COUNT(*) from S3PermissionSet where Name='Operating Budgeting')=1
	begin
		--Check for access - Read allow in Capital Management Permission Set
		if(select COUNT(*) from S3Permission where PermissionSetID=(select PermissionSetID from S3PermissionSet where Name='Operating Budgeting') and RoleID = (Select RoleID from UserRole where Name='Access - Read Allow'))=0
		begin
			insert into S3Permission (PermissionSetID,RoleID,Weight,ReadValue)
			select 
				(select PermissionSetID from S3PermissionSet where Name='Operating Budgeting'),
				RoleID,
				0 as weight,
				1 as ReadValue
			from 
				UserRole
			where 
				Name='Access - Read Allow'
		end
		
		--Check for access - Write allow in Capital Management Permission Set
		if(select COUNT(*) from S3Permission where PermissionSetID=(select PermissionSetID from S3PermissionSet where Name='Operating Budgeting') and RoleID = (Select RoleID from UserRole where Name='Access - Write Allow'))=0
		begin
			insert into S3Permission (PermissionSetID,RoleID,Weight,ReadValue,WriteValue)
			select 
				(select PermissionSetID from S3PermissionSet where Name='Operating Budgeting'),
				RoleID,
				0 as weight,
				1 as ReadValue,
				1 as WriteValue
			from 
				UserRole
			where 
				Name='Access - Write Allow'
		end

	end
GO


---------------------------------------------

-- fw.procCreateUserProfile
Create proc fw.procCreateUserProfile
	@username nvarchar(64)
	,@NameLast nvarchar(64)
	,@NameFirst nvarchar(64)
	,@EmailAddress nvarchar(450)

as

	insert into UserProfile(UserName,NameFirst,NameLast,EmailAddress)
	values(@username,@NameFirst,@NameLast,@EmailAddress)
GO


---------------------------------------------

-- fw.procDeleteDimensionData
/*****************************************************************
****** Author: unknown                                            
****** Create Date: Unknown                                       
****** Description: Deletes all FW dimensions that are specified by the client, used only for GM releases - NEVER RUN ON CLIENT DATABASES
****** Last Modified: 2022-03-22                                  
****** GM Release: 2022.22                                        
****** ***********************************************************
****** Change History                                             
****** ***********************************************************
****** CID  Date        Author      WI            Description     
****** 1    2013-10-02  akk         64597         Adding new dimensions
****** 2    2014-02-20  akk         D-01398       Adding delete from scorefillin
****** 3    2014-06-13  akk         D-01874       Adding payor dimension
****** 4    2016-03-22  akk                       Deleting additional service lines
****** 5    2017-09-07  gjf         D-06351       Clean up security
****** 6    2018-06-19  jbm                       Changing DimAccount Delete
****** 7    2020-05-13  yxr         B-26923       Adding DayType dimension
****** 8    2022-03-22  ljc         JAZZ-37520    Adding post delete insert of Standard Codes into DayType dimension and definition reformat
*****************************************************************/
                                                                  
CREATE 
     
  PROCEDURE [fw].[procDeleteDimensionData]
    AS 
 BEGIN 
       --------- SET NOCOUNT ON added to prevent extra result sets from
       --------- interfering with SELECT statements.              
             SET NOCOUNT ON;                                      
                                                                  
         DECLARE @nextid int;                                     
          SELECT @nextid = 0;                                     
                                                                  
           WHILE EXISTS ( SELECT TOP 1 1 FROM [fw].[DimAccount] WHERE [AccountID] != 0 )
           BEGIN 
                 DELETE TOP (1000) 
                   FROM [fw].[DimAccount] 
                  WHERE [AccountID] != 0;
             END;                                                 
                                                                  
            DBCC CHECKIDENT ('[fw].[DimAccount]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimDepartment] 
           WHERE [DepartmentID] != 0;                             
                                                                  
            DBCC CHECKIDENT ('[fw].[DimDepartment]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimEmployee] 
           WHERE [EmployeeID] != 0;                               
                                                                  
            DBCC CHECKIDENT ('[fw].[DimEmployee]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimDepartmentRollup6] 
           WHERE [DepartmentRollup6ID] != 0;                      
                                                                  
            DBCC CHECKIDENT ('[fw].[DimDepartmentRollup6]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimDepartmentRollup5] 
           WHERE [DepartmentRollup5ID] != 0;                      
                                                                  
            DBCC CHECKIDENT ('[fw].[DimDepartmentRollup5]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimDepartmentRollup4] 
           WHERE [DepartmentRollup4ID] != 0;                      
                                                                  
            DBCC CHECKIDENT ('[fw].[DimDepartmentRollup4]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimDepartmentRollup3] 
           WHERE [DepartmentRollup3ID] != 0;                      
                                                                  
            DBCC CHECKIDENT ('[fw].[DimDepartmentRollup3]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimDepartmentRollup2] 
           WHERE [DepartmentRollup2ID] != 0;                      
                                                                  
            DBCC CHECKIDENT ('[fw].[DimDepartmentRollup2]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimDepartmentRollup1] 
           WHERE [DepartmentRollup1ID] != 0;                      
                                                                  
            DBCC CHECKIDENT ('[fw].[DimDepartmentRollup1]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimEntity] 
           WHERE [EntityID] != 0;                                 
                                                                  
            DBCC CHECKIDENT ('[fw].[DimEntity]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimSystem] 
           WHERE [SystemID] != 0;                                 
                                                                  
            DBCC CHECKIDENT ('[fw].[DimSystem]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimJobCode] 
           WHERE [JobCodeID] != 0;                                
                                                                  
            DBCC CHECKIDENT ('[fw].[DimJobCode]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimPayCode] 
           WHERE [PayCodeID] != 0;                                
                                                                  
            DBCC CHECKIDENT ('[fw].[DimPayCode]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimChargeCode] 
           WHERE [ChargeCodeID] != 0;                             
                                                                  
            DBCC CHECKIDENT ('[fw].[DimChargeCode]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimPatientType] 
           WHERE [PatientTypeID] > 4;                             
                                                                  
            DBCC CHECKIDENT ('[fw].[DimPatientType]', RESEED, 4);   
                                                                  
       --------- BEGIN CID 7                                      
          DELETE 
            FROM [fw].[DimDayType] 
           WHERE [DayTypeID] > 1;                                 
                                                                  
            DBCC CHECKIDENT ('[fw].[DimDayType]', RESEED, 1);     
       --------- END CID 7                                        
                                                                  
       --------- BEGIN CID 8                                      
          INSERT INTO [fw].[DimDayType] ([DayTypeCode], [PrecedentOrder])
          SELECT --*
        DISTINCT [Rollup], 
                 CASE 
                 WHEN [Rollup] = 'Observation' THEN 50 
                 ELSE DENSE_RANK() OVER (ORDER BY [Rollup] ASC) 
                  END AS [PrecedentOrder]
            FROM [dss].[DimUBRevenueCode]
           WHERE [CostDriver] = 'LOS';                            
       --------- END CID 8                                        
                                                                  
                                                                  
       --------- BEGIN CID 1                                      
          DELETE 
            FROM [fw].[DimModelingServiceLine] 
           WHERE [ModelingServiceLineID] != 0;                    
                                                                  
            DBCC CHECKIDENT ('[fw].[DimModelingServiceLine]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimPatientReimbursementGroup] 
           WHERE [PatientReimbursementGroupID] != 0;              
                                                                  
            DBCC CHECKIDENT ('[fw].[DimPatientReimbursementGroup]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimServiceLine] 
           WHERE [ServiceLineID] != 0;                            
                                                                  
            DBCC CHECKIDENT ('[fw].[DimServiceLine]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimServiceLineRollup] 
           WHERE [ServiceLineRollupID] != 0;                      
                                                                  
            DBCC CHECKIDENT ('[fw].[DimServiceLineRollup]', RESEED, @nextid);
                                                                  
       --------- BEGIN CID 4                                      
          DELETE 
            FROM [dbo].[RuleSet]
           WHERE [Category] IN 
                 ( SELECT [RuleSetCategory] 
                     FROM [dss].[ServiceLineDefinition] 
                    WHERE [DimensionGUID] != '074b4b22-9824-40f5-aa2a-a7b32631e8a2' );
                                                                  
          DELETE 
            FROM [fw].[DimServiceLine2] 
           WHERE [ServiceLine2ID] != 0;                           
                                                                  
            DBCC CHECKIDENT ('[fw].[DimServiceLine2]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimServiceLine3] 
           WHERE [ServiceLine3ID] != 0;                           
                                                                  
            DBCC CHECKIDENT ('[fw].[DimServiceLine3]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimServiceLine4] 
           WHERE [ServiceLine4ID] != 0;                           
                                                                  
            DBCC CHECKIDENT ('[fw].[DimServiceLine4]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimServiceLine5] 
           WHERE [ServiceLine5ID] != 0;                           
                                                                  
            DBCC CHECKIDENT ('[fw].[DimServiceLine5]', RESEED, @nextid);
                                                                  
          DELETE 
            FROM [fw].[DimServiceLine6] 
           WHERE [ServiceLine6ID] != 0;                           
                                                                  
            DBCC CHECKIDENT ('[fw].[DimServiceLine6]', RESEED, @nextid);
       --------- END CID 4                                        
                                                                  
          DELETE 
            FROM [fw].[DimProvider] 
           WHERE [ProviderID] != 0;                               
                                                                  
            DBCC CHECKIDENT ('[fw].[DimProvider]', RESEED, @nextid);
       --------- END CID 1                                        
                                                                  
       --------- BEGIN CID 3                                      
          DELETE 
            FROM [fw].[DimPayor] 
           WHERE [PayorID] != 0;                                  
                                                                  
            DBCC CHECKIDENT ('[fw].[DimPayor]', RESEED, @nextid); 
       --------- END CID 3                                        
                                                                  
       --------- BEGIN CID 2                                      
        TRUNCATE TABLE [dbo].[ScoreFillin];                       
                                                                  
            EXEC [dbo].[procScoreFillinTableRebuildAll];          
            EXEC [dbo].[procScoreFillinTableRefreshAll];          
       --------- END CID 2                                        
                                                                  
            EXEC [fw].[procInsertDimensionDefaults];              
                                                                  
          DELETE [l] 
            FROM [dbo].[S3Loot] AS [l] 
           WHERE [l].[LootID] LIKE 'DEPT|%' 
             AND NOT EXISTS
                 ( SELECT 1 
                     FROM [fw].[DimDepartment] AS [d] 
                    WHERE [l].[LootID] = 'DEPT|' + CAST([d].[DepartmentID] AS nvarchar(16))
                   );                                             
                                                                  
          DELETE [lg] 
            FROM [dbo].[S3Loot] AS [lg] 
           WHERE [lg].[LootID] LIKE 'DEPT|%' 
             AND NOT EXISTS
                 ( SELECT 1 
                     FROM [fw].[DimDepartment] AS [d] 
                    WHERE [lg].[LootID] = 'DEPT|' + CAST([d].[DepartmentID] AS nvarchar(16))
                   );                                             
                                                                  
          DELETE [l] 
            FROM [dbo].[S3Loot] AS [l] 
           WHERE [l].[LootID] LIKE 'MRDEPT|%' 
             AND NOT EXISTS
                 ( SELECT 1 
                     FROM [fw].[DimDepartment] AS [d] 
                    WHERE [l].[LootID] = 'MRDEPT|' + CAST([d].[DepartmentID] AS nvarchar(16))
                   );                                             
                                                                  
          DELETE [lg] 
            FROM [dbo].[S3Loot] AS [lg] 
           WHERE [lg].[LootID] LIKE 'MRDEPT|%' 
             AND NOT EXISTS
                 ( SELECT 1 
                     FROM [fw].[DimDepartment] AS [d] 
                    WHERE [lg].[LootID] = 'MRDEPT|' + CAST([d].[DepartmentID] AS nvarchar(16))
                   );                                             
   END;                                                           
                                                                  
RETURN;
GO


---------------------------------------------

-- fw.procDeleteFactData
CREATE PROCEDURE [fw].[procDeleteFactData]
AS

/************************************************************
** Author: akowalski
** Create Date: 2013-11-07
** Description: Deletes FW and CLIENT schema tables that are populated by the client, used only for GM releases - NEVER RUN ON CLIENT DATABASES
** Last Modified: 2013-11-07
** GM Release: 2013-11-19
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2015-06-18	akk				Converting proc to cursor
**
*************************************************************/
BEGIN

	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	DECLARE @SCHEMA nvarchar(256)
	DECLARE @FactTableName nvarchar(256)
	DECLARE @SQL nvarchar(1024)
	DECLARE @SQL2 nvarchar(1024)
	DECLARE FactTableCursor CURSOR FOR 
		select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t 
		where (t.schema_id in(select schema_id from sys.schemas where name in('fw', 'client')) and t.name like 'fact%' and t.name not like '%map'
		and t.name<>'FactWorkingHoursPerMonth') 
		order by t.name
	open FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		set @SQL = 'truncate table ' + @SCHEMA + '.' + @FactTableName
		set @SQL2='DBCC CHECKIDENT (''' + + @SCHEMA + '.' + @FactTableName + ''', RESEED, 1)'
	    --print @SQL

	    EXECUTE sp_executesql @SQL 
		if exists (	select 1 from sys.columns c
			inner join sys.tables t on t.object_id=c.object_ID
			inner join sys.schemas s on t.schema_id=s.schema_id
			where t.name=@FactTableName and s.name=@SCHEMA and is_identity=1)
		begin
			EXECUTE sp_executesql @SQL2
		end
	    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor
	

END

RETURN
GO


---------------------------------------------

-- fw.procDepartmentChargeCodePrimaryStatisticMappingCache
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2023-03-20	HV		JAZZ-52052	Create and fill in cache table for Primary Statistics data source for Daily and Pay Period
*************************************************************/
CREATE PROCEDURE fw.procDepartmentChargeCodePrimaryStatisticMappingCache
AS

IF OBJECT_ID('tempdb..#drivers') IS NOT NULL DROP TABLE #drivers

CREATE TABLE #drivers (OriginalDepartmentID INT NOT NULL, DriverDepartmentID INT NOT NULL, AccountID INT NULL, IsStaffing BIT NOT NULL)

INSERT INTO #drivers (OriginalDepartmentID, DriverDepartmentID, AccountID, IsStaffing)
SELECT C.DepartmentID AS OriginalDepartmentID, COALESCE(DC.DriverDepartmentID, C.DepartmentID) AS DriverDepartmentID, C.AccountID, C.Staffing AS IsStaffing
FROM client.FactDepartmentPrimaryStatisticConfiguration C
LEFT JOIN client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache DC ON DC.FactDepartmentPrimaryStatisticConfigurationID = C.RowID
WHERE C.IsDeleted = 0

TRUNCATE TABLE fw.DepartmentChargeCodePrimaryStatisticMappingCache

INSERT INTO fw.DepartmentChargeCodePrimaryStatisticMappingCache (DepartmentID, OriginalDepartmentID, FiscalYearID, AccountID, ChargeCodeID, PatientTypeRollupID, Weight, IsStaffing)
SELECT
    D.DriverDepartmentID AS DepartmentID,
    D.OriginalDepartmentID,
    map.FiscalYearID,
    map.AccountID,
    map.ChargeCodeID,
    map.PatientTypeRollupID,
    map.Weight,
    D.IsStaffing
FROM #drivers D
INNER JOIN fw.DepartmentChargeCodeStatisticMappingCache map ON map.DepartmentID = D.DriverDepartmentID AND map.AccountID = D.AccountID

IF OBJECT_ID('tempdb..#drivers') IS NOT NULL DROP TABLE #drivers
GO


---------------------------------------------

-- fw.procDepartmentChargeCodeStatisticMappingCacheRefresh
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1        2020-12-08  KF      JAZZ-10947	My Performance | Supplies UOS Detail
*************************************************************/
CREATE PROCEDURE [fw].[procDepartmentChargeCodeStatisticMappingCacheRefresh]
AS

TRUNCATE TABLE fw.DepartmentChargeCodeStatisticMappingCache

INSERT INTO fw.DepartmentChargeCodeStatisticMappingCache (FiscalYearID, DepartmentID, ChargeCodeID, PatientTypeRollupID, AccountID, Weight)
SELECT FiscalYearID, DepartmentID, ChargeCodeID, PatientTypeRollupID, AccountID, Weight
FROM fw.viewDepartmentChargeCodeStatisticMapping
WHERE AccountID != 0 AND Weight != 0
GO


---------------------------------------------

-- fw.procDepartmentChargeCodeStatisticMappingSetDefault
/*
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2016-09-14	GF		Initial implementation
** 2		2018-05-08	KF		B-19364 MRPR - Set Global Weights for Charge Codes - System Center Page
** 3      2018-02-28   OV     D-06846 modify proc to not insert data for RollupID = 0
************************************************************
*/


CREATE proc [fw].[procDepartmentChargeCodeStatisticMappingSetDefault]
as
	set nocount on
	
	insert into fw.DepartmentChargeCodeStatisticMapping (FiscalYearID, DepartmentRollupLevelMemberID, ChargeCodeID, PatientTYpeRollupID, AccountID, Weight, IsReviewed, DepartmentRollupLevelMemberColumnName)
	select distinct 
		pblid.FiscalYearID,
		pblid.DepartmentID, 
		pblid.ChargeCodeID, 
		pt.PatientTypeRollupID, 
		0 as AccountID, 
		0 as Weight,
		0 as IsReviewed,
		'DepartmentID'
   from 
		dss.FactPatientBillingLineItemDetail pblid with (readuncommitted)
		inner join clientdss.FactPatientEncounterSummary es with (readuncommitted) on es.EncounterID = pblid.EncounterID
		inner join [fw].[DimPatientType] PT with (readuncommitted) on es.PatientTypeID=PT.PatientTypeID
		LEFT JOIN fw.DepartmentChargeCodeStatisticMapping ex on  ex.FiscalYearID = pblid.FiscalYearID
                                                             and ex.DepartmentRollupLevelMemberID = pblid.DepartmentID
                                                             and ex.DepartmentRollupLevelMemberColumnName = 'DepartmentID'
                                                             and ex.ChargeCodeID = pblid.ChargeCodeID
                                                             and ex.PatientTypeRollupID = pt.PatientTypeRollupID
	WHERE ex.FiscalYearID is null
    and pt.PatientTypeRollupID != 0
GO


---------------------------------------------

-- fw.procDepartmentChargeCodeStatisticMappingStaffingCache
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2023-02-02	KF		JAZZ-48413	Charge Based Statistics Modals Performance Improvement- Bug Fixing
*************************************************************/
CREATE PROCEDURE fw.procDepartmentChargeCodeStatisticMappingStaffingCache
AS

IF OBJECT_ID('tempdb..#drivers') IS NOT NULL DROP TABLE #drivers

CREATE TABLE #drivers (OriginalDepartmentID INT NOT NULL, DriverDepartmentID INT NOT NULL, AccountID INT NULL)

INSERT INTO #drivers (OriginalDepartmentID, DriverDepartmentID, AccountID)
SELECT C.DepartmentID AS OriginalDepartmentID, COALESCE(DC.DriverDepartmentID, C.DepartmentID) AS DriverDepartmentID, C.AccountID
FROM client.FactDepartmentPrimaryStatisticConfiguration C
LEFT JOIN client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache DC ON DC.FactDepartmentPrimaryStatisticConfigurationID = C.RowID
WHERE C.IsDeleted = 0 AND C.Staffing = 1

TRUNCATE TABLE fw.DepartmentChargeCodeStatisticMappingStaffingCache

INSERT INTO fw.DepartmentChargeCodeStatisticMappingStaffingCache (DepartmentID, OriginalDepartmentID, FiscalYearID, AccountID, ChargeCodeID, PatientTypeRollupID, Weight)
SELECT
    D.DriverDepartmentID AS DepartmentID,
    D.OriginalDepartmentID,
    map.FiscalYearID,
    map.AccountID,
    map.ChargeCodeID,
    map.PatientTypeRollupID,
    map.Weight
FROM #drivers D
INNER JOIN fw.DepartmentChargeCodeStatisticMappingCache map ON map.DepartmentID = D.DriverDepartmentID AND map.AccountID = D.AccountID

IF OBJECT_ID('tempdb..#drivers') IS NOT NULL DROP TABLE #drivers
GO


---------------------------------------------

-- fw.procDepartmentPrimaryStatisticConfigurationDriverDepartmentCacheRefresh
create proc fw.procDepartmentPrimaryStatisticConfigurationDriverDepartmentCacheRefresh
as
	if (not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment)) begin
		return
	end

	declare @sql nvarchar(max)

	set @sql = '
	truncate table [client].[FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache];

	insert into [client].[FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache] (DriverDepartmentGUID, FactDepartmentPrimaryStatisticConfigurationID, DriverDepartmentID)
	select 
		dd.DriverDepartmentGUID,
		dd.FactDepartmentPrimaryStatisticConfigurationID,
		sd.DepartmentID
	from 
		client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd
		inner join fw.DimDepartment sd on dd.Value = ''DEPT|KEY|af5b308b-7574-4769-b4e9-dcdeb617b1fc|'' + cast(sd.DepartmentID as nvarchar(8)) + ''|DEPTDepartmentID|'' + cast(sd.DepartmentID as nvarchar(8));'
	
	if (exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.Value not like 'DEPT|KEY|%')) begin
		declare @driverGUID uniqueidentifier
		declare @configID int
		declare @hpath nvarchar(max)
		declare @where nvarchar(max)
		declare crsHPaths cursor fast_forward for
			select 
				dd.DriverDepartmentGUID,
				dd.FactDepartmentPrimaryStatisticConfigurationID,
				dd.Value
			from 
				client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd
			where
				dd.Value not like 'DEPT|KEY|%'
		open crsHPaths
		fetch next from crsHPaths into @driverGUID, @configID, @hpath
		while (@@FETCH_STATUS = 0) begin
			exec dbo.procScoreHierarchyPathGetQuery @hpath, 1, @where OUTPUT
			set @sql = @sql + '

		insert into [client].[FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache] (DriverDepartmentGUID, FactDepartmentPrimaryStatisticConfigurationID, DriverDepartmentID)
		select ''' + CAST(@driverGUID as nvarchar(36)) + ''', ' + cast(@configID as nvarchar(8)) + ', DepartmentID from fw.viewDimDepartment where ' + @where + ';'
		
			fetch next from crsHPaths into @driverGUID, @configID, @hpath
		end
		close crsHPaths
		deallocate crsHPaths
	end

	exec(@sql)
GO


---------------------------------------------

-- fw.procDimDateAssignFiscalYear
CREATE proc [fw].[procDimDateAssignFiscalYear]
as
/************************************************************
** Author: Unknown
** Create Date: Unknown
** Description: Assigns Fiscal Year to the Date Dimension
** Last Modified: 2015-11-25
** GM Release: Unknown
**************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
** 	1 		2015-11-25	JG					Changing join to join on ID instead of Code
** 	2 		2016-10-17	MH			D-04891	Updated FiscalQuarter
*************************************************************/ 

--Disable triggers on fw.DimDate or else this will be very slow

begin
	declare @yemonth int = (select dbo.GetDBSetting('GENERAL_FISCALYEARENDMONTH'))
	print @yemonth

	update fw.dimdate
		set FiscalYear = 
		    CASE 
				WHEN calendarmonth <= @yemonth THEN  calendaryear  
				else cast(calendaryear as int) + 1 
			END 
from fw.DimDate
end

update d
set d.FiscalMonth = fm.SortOrder, d.FiscalQuarter = concat('Quarter ', fm.QuarterID) 
from fw.DimDate d
inner join fw.DimFiscalMonth fm on d.CalendarMonth = fm.FiscalMonthID
where DateID <> 0

--exec [dbo].[procChangeDBSetting] @settingname = 'GENERAL_FISCALYEARENDMONTH', @value = 6
GO


---------------------------------------------

-- fw.procDimDatePopulate
--Author: ekretzer
--Branch: DSS
--Forward

create procedure fw.procDimDatePopulate
	@StartDate datetime
as
begin
	set nocount on
	
	-- Determine if the year has 365 or 366 days
    declare @numDays smallint = 365;      
	declare @p_leap_date SMALLDATETIME = CONVERT(VARCHAR(4), YEAR(@StartDate)) + '0228'
    declare @p_check_day TINYINT = DATEPART(d, DATEADD(d, 1, @p_leap_date))                           
    if (@p_check_day = 29)
    	set @numDays = 366;

	declare @i int = 0;
    declare @CurrentDate datetime;
			
	while (@i < @numDays)
	begin
        set @CurrentDate = DATEADD(DAY, @i, @StartDate);
        set @CurrentDate = DATEADD(DAY, DATEDIFF(Day, 0, @CurrentDate), 0); --round off to day
        insert into fw.DimDate (
        	CalendarDateTime, CalendarYear, CalendarMonth, CalendarMonthName, DayNumberOfWeek, DayNameOfWeek, DayNumberOfMonth, DayNumberOfYear, WeekNumberOfYear, IsWeekDay, CalendarQuarter)
		values (@CurrentDate, YEAR(@CurrentDate), MONTH(@CurrentDate), DATENAME(month, @CurrentDate ), DATEPART(weekday, @CurrentDate), DATENAME(weekday, @CurrentDate)
		        ,DAY(@CurrentDate), DATEPART(dayofyear, @CurrentDate), DATEPART(week, @CurrentDate), 
				case when DATEPART(weekday, @CurrentDate) in (1,7) then 0 else 1 end, 
				DATENAME(quarter, @CurrentDate))
        set @i = @i + 1;                                
	end
	print 'Added ' + cast(@numDays as varchar(3)) + ' days for ' + cast(year(@StartDate) as varchar(4))
end

RETURN
GO


---------------------------------------------

-- fw.procDimFiscalMonthUpdateDaysInMonth
CREATE PROCEDURE [fw].[procDimFiscalMonthUpdateDaysInMonth]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
	declare @currentYear int = year(getdate())
	update fw.DimFiscalMonth
	set DaysInMonth = dbo.GetDaysInMonth(cast(cast(@currentYear as varchar) + '-' + cast(fiscalmonthid as varchar) + '-1' as DateTime))
	where FiscalMonthID <> 0

	update fw.dimfiscalmonth
	set
		ytddaysinmonth = 
			coalesce(fw.[GetYTDDaysInMonth](fiscalmonthid), 0)
	where FiscalMonthID <> 0
END
GO


---------------------------------------------

-- fw.procDimPayPeriodUpdateFiscalYear
CREATE PROCEDURE [fw].[procDimPayPeriodUpdateFiscalYear]
AS

	update
		fw.dimpayperiod
	set
		fiscalyearidstart = [dbo].[GetFiscalYearForDate](dateadd(day,(1)-[perioddays],[periodendcalendardate])),
		fiscalyearidsecond = [dbo].[GetFiscalYearForDate]([periodendcalendardate])
GO


---------------------------------------------

-- fw.procDimTimePopulate
--Author: ekretzer
--Branch: DSS
--Forward

create procedure fw.procDimTimePopulate
as
begin
	-- We assume that the 0 record is 0:00 & not 0 - Not Specified
	truncate table fw.DimTime
	DBCC CHECKIDENT ('fw.DimTime', reseed, 0)

	declare @Hour tinyint = 0
	declare @Minute tinyint = 0

	while @Hour < 24
	begin
		set @Minute = 0
		while @Minute < 60
		begin
			insert into fw.DimTime([Hour], [Minute], MemberGUID) values (@Hour, @Minute, newid())
			set @Minute = @Minute + 1
		end
		set @Hour = @Hour + 1
	end --@Hour

end

RETURN
GO


---------------------------------------------

-- fw.procEMFFillInCreateAutoProc
CREATE proc [fw].[procEMFFillInCreateAutoProc] 
	@procschema sysname,
	@procobject sysname,
	@phdimensionguid uniqueidentifier,
	@plantypeguid uniqueidentifier,
	@attributename nvarchar(100) = 'AutomaticPHSection'
   --@planguid uniqueidentifier = '00000000-0000-0000-0000-000000000000'
as
/*

select 
	AutomaticPHSection 
from 
	zzviewlist_masteraccount

*/
declare @phdimname nvarchar(100)
declare @fidimname nvarchar(100)
declare @phl1name nvarchar(100)

select
	@phdimname = replace(ph.Name, ' ', ''),
	@fidimname = replace(fi.Name, ' ', ''),
	@phl1name = replace(phl1.Name, ' ','')
from
	SecureList ph
	inner join SecureList fi on ph.FillInDimensionGUID = fi.ListGUID
	inner join SecureListLevel phl1 on ph.ListGUID = phl1.ListGUID and phl1.LevelIndex = 0
where
	ph.ListGUID = @phdimensionguid
	
declare @sql nvarchar(max)

set @sql = '

if exists ( select 1 from viewSysProcedures where schemaname = ''' + @procschema + ''' and objectname = ''' + @procobject + ''' ) begin
	drop proc [' + @procschema + '].[' + @procobject + ']
end
'

exec (@sql)

set @sql = '

create proc [' + @procschema + '].[' + @procobject + ']
	@planguid uniqueidentifier = ''00000000-0000-0000-0000-000000000000''
as

declare @iguid uniqueidentifier
set @iguid = NEWID()

insert into EMFFillInSetManyStaging ( InstanceGUID, ModelGUID, PHDimensionGUID, ParentPHMemberGUID, FillInGUID, SortOrder)
select 
	@iguid, 
	p.PlanGUID as ModelGUID,
	''' + cast(@phdimensionguid as varchar(36)) + ''' as PHDimensionGUID, --' + @phdimname + '
	ph.'+ @phdimname +'GUID as ParentPHMemberGUID, 
	fi.'+ @fidimname +'GUID as FillInGuid,
	ROW_NUMBER() over (partition by p.planguid order by fi.'+ @fidimname +' asc) as SortOrder
from 
	[zzviewlist_'+ @fidimname +'] fi
	inner join zzviewlist_'+ @phdimname +' ph on fi.'+ @attributename +' = ph.'+ @phl1name +' and ph.'+ @phdimname +' is null
	cross join xplan p
where 
	p.plantypeguid = ''' + CAST(@plantypeguid as varchar(36)) +  '''
	and (p.planguid = @planguid or @planguid = dbo.ZeroGUID())

exec procEMFFillInSetManyNoClear @iguid

--select * from EMFFillInSetManyStaging where InstanceGUID = @iguid
delete from EMFFillInSetManyStaging where InstanceGUID = @iguid
'

exec (@sql)
GO


---------------------------------------------

-- fw.procFactDailyMergeDuplicates
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
** 1		2022-07-25	KF			JAZZ-39738 Daily flexing - Payroll Hours and Dollars
*************************************************************/
CREATE proc [fw].[procFactDailyMergeDuplicates]
	@factTableName nvarchar(100),
	@keyNameCSV nvarchar(450),
	@measureNameCSV nvarchar(450),
	@fiscalYearID smallint = 0,
	@priorYearsCount smallint = 0,
	@timeClassID tinyint = 0,
	@onePayPeriodOnlyDate datetime = null,
	@isDebugOnly bit = 0,
	@departmentIDs nvarchar(max) = null
with recompile
as
	set nocount on

	IF OBJECT_ID('tempdb..#DailyCalcPeriodsScope') IS NOT NULL DROP TABLE #DailyCalcPeriodsScope
    CREATE TABLE #DailyCalcPeriodsScope (PayPeriodID int primary key)

    INSERT INTO #DailyCalcPeriodsScope (PayPeriodID) 
    SELECT PayPeriodID
    FROM fw.DimPayPeriod
    WHERE 
		(@onePayPeriodOnlyDate IS NOT NULL and @onePayPeriodOnlyDate BETWEEN PeriodStartCalendarDate and PeriodEndCalendarDate)
		or
		(@onePayPeriodOnlyDate IS NULL and ((FiscalYearIDSecond BETWEEN @fiscalYearID - @priorYearsCount AND @fiscalYearID) or @fiscalYearID = 0))

	declare @sql nvarchar(max)

	declare @from nvarchar(max) = '
	FROM ' + @factTableName + ' data
	INNER JOIN #DailyCalcPeriodsScope pp ON pp.PayPeriodID = data.PayPeriodID
	INNER JOIN
	(
	    SELECT fd.DepartmentID, fd.' + replace(@keyNameCSV, ',', ', fd.') + ', fd.PayPeriodID, fd.DateID, fd.TimeClassID
		FROM ' + @factTableName + ' fd
		GROUP BY fd.DepartmentID, fd.' + replace(@keyNameCSV, ',', ', fd.') + ', fd.PayPeriodID, fd.DateID, fd.TimeClassID
		HAVING COUNT(*) > 1
	) dr ON dr.DepartmentID = data.DepartmentID and ' + (select dbo.straggr('dr.' + csv.val + ' = data.' + csv.val, ' and ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' and dr.PayPeriodID = data.PayPeriodID and dr.DateID = data.DateID and dr.TimeClassID = data.TimeClassID
	WHERE (1 = 1)' + (case when @timeClassID > 0 then ' and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end)

	declare @fromForUpdate nvarchar(max) = REPLACE(@from, '#DailyCalcPeriodsScope', '#inputPayPeriods');

	declare @delete nvarchar(max) = '
		WHILE (EXISTS (SELECT TOP 1 1 FROM ' + @factTableName + ' WHERE IsDeleted = 1))
		BEGIN
		    DELETE TOP(10000000) data FROM ' + @factTableName + ' data WHERE data.IsDeleted = 1
		END;
	'


	--merge duplicate rows
	set @sql = @delete +'

		IF OBJECT_ID(''tempdb..#inputPayPeriods'') IS NOT NULL DROP TABLE #inputPayPeriods

        SELECT data.PayPeriodID, COUNT(1) AS RecordsCount, 0 AS BatchID INTO #inputPayPeriods ' + @from + '
		GROUP BY data.PayPeriodID
        
	-- Split data into batches
	DECLARE @BatchSize INT = 20000000

    WHILE EXISTS (SELECT TOP 1 1 FROM #inputPayPeriods WHERE BatchID = 0)
    BEGIN
        ;WITH PayPeriodInfo AS 
        (
            SELECT IPP.PayPeriodID, ROW_NUMBER() OVER (ORDER BY IPP.PayPeriodID) AS RowNumber, SUM(RecordsCount) OVER (ORDER BY IPP.PayPeriodID) AS Total, M.MaxBatchID+1 AS BatchID
            FROM #inputPayPeriods IPP
		    CROSS JOIN (SELECT MAX(BatchID) AS MaxBatchID FROM #inputPayPeriods) M        
            WHERE IPP.BatchID = 0
        )
        UPDATE IPP
        SET IPP.BatchID = MI.BatchID
        FROM #inputPayPeriods IPP
        INNER JOIN PayPeriodInfo MI ON MI.PayPeriodID = IPP.PayPeriodID
        WHERE MI.Total <= @BatchSize OR MI.RowNumber = 1
    END

	DECLARE @BatchID INT, @MaxBatchID INT
    SELECT @MaxBatchID = MAX(BatchID) FROM #inputPayPeriods

	-- Loop thru batches and insert data
    SET @BatchID = 1
    WHILE @BatchID <= @MaxBatchID
    BEGIN
	    UPDATE data
		SET data.IsDeleted = 1 ' + @fromForUpdate + ' and pp.BatchID = @BatchID	
	
		INSERT INTO ' + @factTableName + ' (data.DepartmentID, ' + @keyNameCSV + ', PayPeriodID, DateID, TimeClassID, ' + @measureNameCSV + ')
		SELECT data.DepartmentID, ' + replace(@keyNameCSV, ',', ', data.') + ', data.PayPeriodID, data.DateID, data.TimeClassID, sum(' + replace(@measureNameCSV, ',', '), sum(') + ')
		FROM ' + @factTableName + ' data
		INNER JOIN #inputPayPeriods pp ON pp.PayPeriodID = data.PayPeriodID
		WHERE data.IsDeleted = 1 and pp.BatchID = @BatchID
		GROUP BY data.DepartmentID, ' + replace(@keyNameCSV, ',', ', data.') + ', data.PayPeriodID, data.DateID, data.TimeClassID;
	    
        SET @BatchID = @BatchID + 1
    END
	' + @delete; 

	if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end

	IF OBJECT_ID('tempdb..#DailyCalcPeriodsScope') IS NOT NULL DROP TABLE #DailyCalcPeriodsScope
	IF OBJECT_ID('tempdb..#inputPayPeriods') IS NOT NULL DROP TABLE #inputPayPeriods
GO


---------------------------------------------

-- fw.procFactGLSampledBaselineTargetUpdate
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
** 1		2017-07-05	IP			D-06023	Changing columns size to support values over 1 trillion
** 2		2018-05-16	IP			D-07006	Rolling Average method for metric target calculation doesn't include months with 0 values
** 3		2018-05-24	KF			D-07006	Rolling Average method for metric target calculation doesn't include months with 0 values
** 4		2018-06-01	IP 			D-07006	Rolling Average method for metric target calculation doesn't include months with 0 values (one year part)
** 5		2018-06-05	IP 			TK-58643 added filetr for current year only and non-zero records in output
** 6		2024-06-05	ishah		JAZZ-61244 [TrLog][High] Bug - Run Management Reporting Monthly Process (MR Sampling, all years run): Task failed on Inserting GL Sampled.
*************************************************************/
----- #FactGLStaging should be created with specified columns(RowID bigint identity(1,1), DepartmentID int, AccountID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Units decimal(21,6), Dollars decimal(21,6), FTEs decimal(21,6),isDeleted bit default 0, isSystemGenerated bit default 0) before calling the proc
CREATE PROCEDURE [fw].[procFactGLSampledBaselineTargetUpdate] 
	@targetType INT = NULL, 
	@numberOfMonths INT = NULL, 
	@fiscalYearID INT = 0
	
	WITH RECOMPILE
AS

IF (@targetType IS NULL)
	SET @targetType = (
			SELECT Value
			FROM mr.SystemSetting
			WHERE NAME = 'Target Basis'
			)

IF (@numberOfMonths IS NULL)
	SET @numberOfMonths = (
			SELECT Value
			FROM mr.SystemSetting
			WHERE NAME = 'Number Of Rolling Average Months'
			)

CREATE TABLE #temp (DepartmentID INT, AccountID INT, FiscalYearID SMALLINT, FiscalMonthID TINYINT, Dollars DECIMAL(21, 6), Units DECIMAL(21, 6))
DECLARE 
	@declareParameters nvarchar(max), 
	@sql nvarchar(max), 
	@sqlJoin nvarchar(max), 
	@sqlWhere nvarchar(max),
	@sqlFromForBatches nvarchar(max), 
	@batchSize INT, 
	@BatchID INT, 
	@MaxBatchID INT, 
	@sqlParam nvarchar(max),
	@timeClassId int = 1

declare @maxCalculatingFiscalYear int = (select max(FiscalYearID) from #FactGLStaging)

-- Split by batches
EXEC mr.procGetIntBatchSize
	@DefaultBatchSize = 30000000,
	@ResultBatchSize = @batchSize OUTPUT
	
IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments
CREATE TABLE #inputDepartments (DepartmentID INT, RecordsCount INT, BatchID INT)

delete from #FactGLStaging where TimeClassID = 20 and (FiscalYearID = @FiscalYearID or @FiscalYearID = 0)

IF (@targetType = 1)
BEGIN --Prior Year Actual
	IF @fiscalYearID <> 0
	BEGIN
		set @declareParameters = '@fiscalYearID INT = ' + cast(@fiscalYearID - 1 as NVARCHAR(4)) + ', @timeClassId INT = ' + cast(@timeClassId as nvarchar(max))	
		set @sqlJoin = '
				(
					SELECT d.DepartmentID, d.AccountID, d.FiscalYearID + 1 as FiscalYearID, d.FiscalMonthID
					FROM fw.FactGLSampled d
					WHERE d.TimeClassID = @timeClassId AND d.FiscalYearID = @fiscalYearID
				) X
			'
			
		INSERT INTO #inputDepartments
		EXEC dbo.procGetInputDataByBatches
	  		@batchSize = @batchSize,
			@columnName = 'DepartmentID',
			@tableAlias = 'X',
			@fromClause = @sqlJoin,
			@whereClause = '',
			@declareParameters = @declareParameters,
			@isDebug = 0
				
		SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

		SET @BatchID = 1
		WHILE @BatchID <= @MaxBatchID
		BEGIN
			INSERT INTO #temp
			SELECT d.DepartmentID, d.AccountID, d.FiscalYearID + 1, d.FiscalMonthID, d.Dollars, d.Units
			FROM fw.FactGLSampled d
			INNER JOIN #inputDepartments ID on ID.DepartmentID = d.DepartmentID
				AND d.TimeClassID = @timeClassId AND d.FiscalYearID = @fiscalYearID - 1 AND ID.BatchID = @BatchID

			SET @BatchID = @BatchID + 1	
		END
	END
	ELSE
	BEGIN
		set @declareParameters = '@timeClassId INT = ' + cast(@timeClassId as nvarchar(max))
		set @sqlJoin = '
				(
					SELECT d.DepartmentID, d.AccountID, d.FiscalYearID + 1 as FiscalYearID, d.FiscalMonthID
					FROM #FactGLStaging d
					WHERE d.TimeClassID = @timeClassId
				) X
			'
			
		INSERT INTO #inputDepartments
		EXEC dbo.procGetInputDataByBatches
	  		@batchSize = @batchSize,
			@columnName = 'DepartmentID',
			@tableAlias = 'X',
			@fromClause = @sqlJoin,
			@whereClause = '',
			@declareParameters = @declareParameters,
			@isDebug = 0
			
			
		SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments
		SET @BatchID = 1
		WHILE @BatchID <= @MaxBatchID
		BEGIN	
			INSERT INTO #temp
			SELECT d.DepartmentID, d.AccountID, d.FiscalYearID + 1, d.FiscalMonthID, d.Dollars, d.Units
			FROM #FactGLStaging d
			INNER JOIN #inputDepartments ID on ID.DepartmentID = d.DepartmentID
			WHERE d.TimeClassID = @timeClassId AND ID.BatchID = @BatchID

			SET @BatchID = @BatchID + 1
		END
	END	
END
ELSE IF (@targetType = 10)
BEGIN --Rolling Average
	IF OBJECT_ID('tempdb..#AllCombinations') IS NOT NULL DROP TABLE #AllCombinations
	CREATE TABLE #AllCombinations (
		DepartmentID INT,
		AccountID INT,
		FiscalYearID INT,
		SortOrder INT,
		Units DECIMAL(21, 6),
		Dollars DECIMAL(21, 6)
	);

	IF OBJECT_ID('tempdb..#FinalDataset') IS NOT NULL DROP TABLE #FinalDataset
	CREATE TABLE #FinalDataset (
		DepartmentID INT,
		AccountID INT,
		FiscalYearID INT,
		FiscalMonthID INT,
		Dollars DECIMAL(21, 6),
		Units DECIMAL(21, 6)
	);

	IF @fiscalYearID = 0
	BEGIN
		IF OBJECT_ID('tempdb..#FiscalYearMonth') IS NOT NULL DROP TABLE #FiscalYearMonth
		CREATE TABLE #FiscalYearMonth (
			FiscalYearID INT,
			FiscalMonthID INT,
			SortOrder INT,
			ChronologicalOrder INT
		);
		
		INSERT INTO #FiscalYearMonth (FiscalYearID, FiscalMonthID, SortOrder, ChronologicalOrder)
		SELECT fy.FiscalYearID, fm.FiscalMonthID, fm.SortOrder, fy.FiscalYearID * 12 + fm.SortOrder AS ChronologicalOrder
		FROM fw.DimFiscalYear fy
		CROSS JOIN fw.DimFiscalMonth fm
		WHERE fy.FiscalYearID <> 0 AND fm.FiscalMonthID <> 0
		
		IF OBJECT_ID('tempdb..#PrecomputedValues') IS NOT NULL DROP TABLE #PrecomputedValues
		CREATE TABLE #PrecomputedValues (
			DepartmentID INT,
			AccountID INT,
			FiscalYearID INT,
			FiscalMonthID INT,
			SortOrder INT,
			PrecomputedValue INT,
			Units DECIMAL(21, 6),
			Dollars DECIMAL(21, 6),
			TimeClassID INT,
			IsSystemGenerated BIT
		);
		
		SET @sqlFromForBatches = '
		(
			SELECT
				p.DepartmentID as DepartmentID,
				p.AccountID,
				p.FiscalYearID,
				p.FiscalMonthID,
				m.SortOrder,
				(p.FiscalYearID * 12 + m.SortOrder) AS PrecomputedValue,
				p.Units,
				p.Dollars,
				p.TimeClassID,
				ISNULL(p.IsSystemGenerated, 0) AS IsSystemGenerated
			FROM #FactGLStaging p
			INNER JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
			WHERE p.TimeClassID = 1 AND ISNULL(p.IsSystemGenerated, 0) = 0
		) X
		'
				
		INSERT INTO #inputDepartments
		EXEC dbo.procGetInputDataByBatches
			@batchSize = @batchSize,
			@columnName = 'DepartmentID',
			@tableAlias = 'X',
			@fromClause = @sqlFromForBatches,
			@whereClause = '',
			@isDebug = 0
												
		SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments
		SET @BatchID = 1
		WHILE @BatchID <= @MaxBatchID
		BEGIN
			INSERT INTO #PrecomputedValues
			SELECT
				p.DepartmentID,
				p.AccountID,
				p.FiscalYearID,
				p.FiscalMonthID,
				m.SortOrder,
				(p.FiscalYearID * 12 + m.SortOrder) AS PrecomputedValue,
				p.Units,
				p.Dollars,
				p.TimeClassID,
				ISNULL(p.IsSystemGenerated, 0) AS IsSystemGenerated
			FROM #FactGLStaging p
			INNER JOIN #inputDepartments ID ON ID.DepartmentID = p.DepartmentID
			INNER JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
			WHERE p.TimeClassID = 1 AND ISNULL(p.IsSystemGenerated, 0) = 0 AND ID.BatchID = @BatchID 
			
			SET @BatchID = @BatchID + 1
		END
						
		IF OBJECT_ID('tempdb..#ChronologicalDifferences') IS NOT NULL DROP TABLE #ChronologicalDifferences
		CREATE TABLE #ChronologicalDifferences (
			DepartmentID INT,
			AccountID INT,
			FiscalYearID INT,
			SortOrder INT,
			ChronologicalDifference INT
		);
		
		DECLARE @MinYear INT = (SELECT MIN(FiscalYearID) FROM #PrecomputedValues)
		DECLARE @MaxYear INT = (SELECT MAX(FiscalYearID) FROM #PrecomputedValues)
		
		WHILE @MinYear <= @MaxYear
		BEGIN	
			SET @sqlFromForBatches = '
				(
					SELECT
						pv.DepartmentID as DepartmentID,
						pv.AccountID,
						fy.FiscalYearID,
						fy.SortOrder,
						(fy.ChronologicalOrder - pv.PrecomputedValue) AS ChronologicalDifference
					FROM #PrecomputedValues pv
					INNER JOIN #FiscalYearMonth fy ON (fy.ChronologicalOrder - pv.PrecomputedValue) BETWEEN 1 AND ' + CAST(@numberOfMonths AS NVARCHAR(4)) + '
					WHERE pv.FiscalYearID = ' + cast(@MinYear as nvarchar(100)) + '
				) X
			'
			
			TRUNCATE TABLE #inputDepartments		
			INSERT INTO #inputDepartments
			EXEC dbo.procGetInputDataByBatches
				@batchSize = @batchSize,
				@columnName = 'DepartmentID',
				@tableAlias = 'X',
				@fromClause = @sqlFromForBatches,
				@whereClause = '',
				@isDebug = 0
				
			SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments
			SET @BatchID = 1
			WHILE @BatchID <= @MaxBatchID
			BEGIN
				INSERT INTO #ChronologicalDifferences
				SELECT
					pv.DepartmentID,
					pv.AccountID,
					fy.FiscalYearID,
					fy.SortOrder,
					(fy.ChronologicalOrder - pv.PrecomputedValue) AS ChronologicalDifference
				FROM #PrecomputedValues pv
				INNER JOIN #inputDepartments ID ON ID.DepartmentID = pv.DepartmentID
				INNER JOIN #FiscalYearMonth fy ON (fy.ChronologicalOrder - pv.PrecomputedValue) BETWEEN 1 AND @numberOfMonths 
				WHERE ID.BatchID = @BatchID AND pv.FiscalYearID = @MinYear
						
				SET @BatchID = @BatchID + 1
			END	
		
			
			SET @MinYear = @MinYear + 1
		END
											
		SET @sqlFromForBatches = '
		(
			SELECT
				CombinedResults.DepartmentID as DepartmentID,
				AccountID,
				FiscalYearID,
				SortOrder
			FROM (
				SELECT
					PV.DepartmentID as DepartmentID,
					AccountID,
					FiscalYearID,
					SortOrder,
					Units,
					Dollars,
					NULL AS ChronologicalDifference
				FROM #PrecomputedValues PV
				WHERE PV.FiscalMonthID <> 0
					
				UNION ALL

				SELECT
					CD.DepartmentID as DepartmentID,
					AccountID,
					FiscalYearID,
					SortOrder,
					0 AS Units,
					0 AS Dollars,
					ChronologicalDifference
				FROM #ChronologicalDifferences CD
			) AS CombinedResults
			GROUP BY CombinedResults.DepartmentID, AccountID, FiscalYearID, SortOrder
		) X
		'
			
		TRUNCATE TABLE #inputDepartments
		INSERT INTO #inputDepartments
		EXEC dbo.procGetInputDataByBatches
			@batchSize = @batchSize,
			@columnName = 'DepartmentID',
			@tableAlias = 'X',
			@fromClause = @sqlFromForBatches,
			@whereClause = '',
			@isDebug = 0
												
		SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments
		SET @BatchID = 1
		WHILE @BatchID <= @MaxBatchID
		BEGIN
			INSERT INTO #AllCombinations
			SELECT
				CombinedResults.DepartmentID,
				AccountID,
				FiscalYearID,
				SortOrder,
				SUM(CASE WHEN ChronologicalDifference IS NULL THEN Units ELSE 0 END) AS Units,
				SUM(CASE WHEN ChronologicalDifference IS NULL THEN Dollars ELSE 0 END) AS Dollars
			FROM (
				SELECT
					PV.DepartmentID,
					AccountID,
					FiscalYearID,
					SortOrder,
					Units,
					Dollars,
					NULL AS ChronologicalDifference
				FROM #PrecomputedValues PV
				WHERE PV.FiscalMonthID <> 0
					
				UNION ALL

				SELECT
					CD.DepartmentID,
					AccountID,
					FiscalYearID,
					SortOrder,
					0 AS Units,
					0 AS Dollars,
					ChronologicalDifference
				FROM #ChronologicalDifferences CD
			) AS CombinedResults
			INNER JOIN #inputDepartments ID ON ID.DepartmentID = CombinedResults.DepartmentID
			WHERE ID.BatchID = @BatchID 
			GROUP BY CombinedResults.DepartmentID, AccountID, FiscalYearID, SortOrder
			
			SET @BatchID = @BatchID + 1
		END
						
		SET @sql = '
			SELECT DepartmentID, AccountID, FiscalYearID, SortOrder, Dollars, Units
			FROM #AllCombinations
		'			
		SET @sqlWhere = 'WHERE (Dollars is not null or Units is not null)'	
	END
	ELSE -- FiscalYearID != 0
	BEGIN
		SET @sqlFromForBatches = '
		(
			SELECT
				p.DepartmentID as DepartmentID,
				AccountID,
				FiscalYearID,
				m.SortOrder as SortOrder,
				Units,
				Dollars
			FROM #FactGLStaging p
			JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
			WHERE m.FiscalMonthID <> 0 AND ISNULL(p.IsSystemGenerated, 0) = 0 AND TimeClassID = 1 AND FiscalYearID = ' + cast(@fiscalYearID AS NVARCHAR(4)) + '

			UNION ALL

			SELECT
				p.DepartmentID as DepartmentID,
				AccountID,
				FiscalYearID,
				m.SortOrder as SortOrder,
				Units,
				Dollars
			FROM fw.FactGLSampled p
			JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
			WHERE m.FiscalMonthID <> 0 AND ISNULL(p.IsSystemGenerated, 0) = 0 AND TimeClassID = 1 AND FiscalYearID = ' + cast(@fiscalYearID - 1 AS NVARCHAR(4)) + '

			UNION ALL

			SELECT
				p.DepartmentID as DepartmentID,
				AccountID,
				FiscalYearID,
				m.SortOrder as SortOrder,
				0 AS Units,
				0 AS Dollars
			FROM #FactGLStaging p
			CROSS APPLY fw.DimFiscalMonth m
			WHERE m.FiscalMonthID <> 0 AND p.TimeClassID = 1

			UNION ALL

			SELECT
				p.DepartmentID as DepartmentID,
				p.AccountID as AccountID,
				fy.FiscalYearID as FiscalYearID,
				m.SortOrder as SortOrder, 
				0 AS Units,
				0 AS Dollars
			FROM fw.FactGLSampled p
			CROSS APPLY fw.DimFiscalMonth m
			CROSS JOIN (
				SELECT FiscalYearID
				FROM fw.DimFiscalYear dm
				WHERE dm.FiscalYearID IN ('+cast(@fiscalYearID-1 as nvarchar(4))+','+cast(@fiscalYearID as nvarchar(4))+')
			) fy
			WHERE m.FiscalMonthID <> 0 AND p.TimeClassID = 1 AND ISNULL(p.IsSystemGenerated, 0) = 0 AND p.FiscalYearID = ' + cast(@fiscalYearID - 1 AS NVARCHAR(4)) + '
		) X
		'
					
		INSERT INTO #inputDepartments
		EXEC dbo.procGetInputDataByBatches
			@batchSize = @batchSize,
			@columnName = 'DepartmentID',
			@tableAlias = 'X',
			@fromClause = @sqlFromForBatches,
			@whereClause = '',
			@isDebug = 0
									
		SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments
		SET @BatchID = 1
		WHILE @BatchID <= @MaxBatchID
		BEGIN	
			INSERT INTO #AllCombinations
			SELECT
				p.DepartmentID,
				AccountID,
				FiscalYearID,
				m.SortOrder,
				Units,
				Dollars
			FROM #FactGLStaging p
			INNER JOIN #inputDepartments ID on ID.DepartmentID = p.DepartmentID
			JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
			WHERE m.FiscalMonthID <> 0 AND ISNULL(p.IsSystemGenerated, 0) = 0 AND TimeClassID = 1 AND FiscalYearID = @fiscalYearID AND ID.BatchID = @BatchID

			UNION ALL

			SELECT
				p.DepartmentID,
				AccountID,
				FiscalYearID,
				m.SortOrder,
				Units,
				Dollars
			FROM fw.FactGLSampled p
			INNER JOIN #inputDepartments ID on ID.DepartmentID = p.DepartmentID
			JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
			WHERE m.FiscalMonthID <> 0 AND ISNULL(p.IsSystemGenerated, 0) = 0 AND TimeClassID = 1 AND FiscalYearID = @fiscalYearID - 1 AND ID.BatchID = @BatchID

			UNION ALL

			SELECT
				p.DepartmentID,
				AccountID,
				FiscalYearID,
				m.SortOrder,
				0 AS Units,
				0 AS Dollars
			FROM #FactGLStaging p
			INNER JOIN #inputDepartments ID on ID.DepartmentID = p.DepartmentID
			CROSS APPLY fw.DimFiscalMonth m
			WHERE m.FiscalMonthID <> 0 AND p.TimeClassID = 1 AND ID.BatchID = @BatchID

			UNION ALL

			SELECT
				p.DepartmentID,
				p.AccountID,
				fy.FiscalYearID,
				m.SortOrder,
				0 AS Units,
				0 AS Dollars
			FROM fw.FactGLSampled p
			INNER JOIN #inputDepartments ID on ID.DepartmentID = p.DepartmentID
			CROSS APPLY fw.DimFiscalMonth m
			CROSS JOIN (
				SELECT FiscalYearID
				FROM fw.DimFiscalYear dm
				WHERE dm.FiscalYearID IN (@fiscalYearID - 1, @fiscalYearID)
			) fy
			WHERE m.FiscalMonthID <> 0 AND p.TimeClassID = 1 AND ISNULL(p.IsSystemGenerated, 0) = 0 AND p.FiscalYearID = @fiscalYearID - 1 AND ID.BatchID = @BatchID

			SET @BatchID = @BatchID + 1
		END
			
		SET @sql = '
			SELECT DepartmentID, AccountID, FiscalYearID, SortOrder, SUM(Dollars) AS Dollars, SUM(Units) AS Units
			FROM #AllCombinations
			GROUP BY DepartmentID, AccountID, FiscalYearID, SortOrder
		'		
		SET @sqlWhere = 'WHERE (Dollars is not null or Units is not null) and FiscalYearID = ' + cast(@fiscalYearID AS NVARCHAR(4)) + ' '		
	END

	SET @sqlJoin = '
		SELECT
			FullScope.DepartmentID as DepartmentID,
			FullScope.AccountID as AccountID,
			FullScope.FiscalYearID as FiscalYearID,
			m.FiscalMonthID as FiscalMonthID,
			ISNULL(
				(SUM(Dollars) OVER (PARTITION BY FullScope.DepartmentID, AccountID ORDER BY FiscalYearID * 12 + m.SortOrder ROWS BETWEEN ' + CAST(@numberOfMonths AS NVARCHAR(4)) + ' PRECEDING AND 1 PRECEDING)) / ' + CAST(@numberOfMonths AS NVARCHAR(4)) + ', 0
			) AS Dollars,
			ISNULL(
				(SUM(Units) OVER (PARTITION BY FullScope.DepartmentID, AccountID ORDER BY FiscalYearID * 12 + m.SortOrder ROWS BETWEEN ' + CAST(@numberOfMonths AS NVARCHAR(4)) + ' PRECEDING AND 1 PRECEDING)) / ' + CAST(@numberOfMonths AS NVARCHAR(4)) + ', 0
			) AS Units
		FROM (
			' + @sql + '
		) AS FullScope
		JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder
		'
			
		SET @sqlFromForBatches = '
			( ' + @sqlJoin + '
			) X
		'
			
		SET @sql = '
		INSERT INTO #FinalDataset
			' + @sqlJoin + '
			' + 'INNER JOIN #inputDepartments IP ON IP.DepartmentID = FullScope.DepartmentID' + ' 
			WHERE IP.BatchID = @BatchID	
		'
				
		TRUNCATE TABLE #inputDepartments
		INSERT INTO #inputDepartments
		EXEC dbo.procGetInputDataByBatches
			@batchSize = @batchSize,
			@columnName = 'DepartmentID',
			@tableAlias ='X',
			@fromClause = @sqlFromForBatches,
			@whereClause = '',
			@isDebug = 0
						
		SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

		SET @SqlParam = '@BatchID INT'
		-- Loop thru batches and insert data
		SET @BatchID = 1
		WHILE @BatchID <= @MaxBatchID
		BEGIN
			EXEC sp_executesql @sql, @SqlParam, @BatchID = @BatchID;
			SET @BatchID = @BatchID + 1
		END
				
		SET @sqlFromForBatches = '
			(
				SELECT
					DepartmentID,
					AccountID,
					FiscalYearID,
					FiscalMonthID,
					ISNULL(Dollars, 0.0) AS Dollars,
					ISNULL(Units, 0.0) AS Units
				FROM #FinalDataset	
				' + @sqlWhere + ' 
			) X
		'
		
		SET @sql = '
			INSERT INTO #temp (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Dollars, Units)
			SELECT
				FDS.DepartmentID,
				AccountID,
				FiscalYearID,
				FiscalMonthID,
				ISNULL(Dollars, 0.0) AS Dollars,
				ISNULL(Units, 0.0) AS Units
			FROM #FinalDataset FDS	
			' + 'INNER JOIN #inputDepartments IP ON IP.DepartmentID = FDS.DepartmentID' + ' 
			'  + @sqlWhere + ' and IP.BatchID = @BatchID	
		'
					
		TRUNCATE TABLE #inputDepartments
		INSERT INTO #inputDepartments
		EXEC dbo.procGetInputDataByBatches
			@batchSize = @batchSize,
			@columnName = 'DepartmentID',
			@tableAlias ='X',
			@fromClause = @sqlFromForBatches,
			@whereClause = '',
			@isDebug = 0
					
		SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

		SET @SqlParam = '@BatchID INT'
		-- Loop thru batches and insert data
		SET @BatchID = 1
		WHILE @BatchID <= @MaxBatchID
		BEGIN
			EXEC sp_executesql @sql, @SqlParam, @BatchID = @BatchID;
			SET @BatchID = @BatchID + 1
		END	
END
ELSE
BEGIN --Budget	
	SET @sqlWhere = 'TimeClassID = 2 and (FiscalYearID = ' + cast(@fiscalYearID AS NVARCHAR(4)) + ' or ' + cast(@fiscalYearID AS NVARCHAR(4)) + ' = 0) '

	TRUNCATE TABLE #inputDepartments

	INSERT INTO #inputDepartments
	EXEC dbo.procGetInputDataByBatches
	  	@batchSize = @batchSize,
		@columnName = 'DepartmentID',
		@tableAlias = 'X',
		@fromClause = '#FactGLStaging X',
		@whereClause = @sqlWhere,
		@isDebug = 0
				
	SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments
	
	SET @BatchID = 1
	WHILE @BatchID <= @MaxBatchID
	BEGIN
		INSERT INTO #temp
		SELECT GL.DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Dollars, Units
		FROM #FactGLStaging GL
		INNER JOIN #inputDepartments IP ON IP.DepartmentID = GL.DepartmentID 
		WHERE TimeClassID = 2
			and (FiscalYearID = @FiscalYearID or @FiscalYearID = 0) and IP.BatchID = @BatchID

		SET @BatchID = @BatchID + 1
	END
END

SET @sqlWhere = '(FiscalYearID =' + cast(@fiscalYearID AS NVARCHAR(4)) + ' or ' + cast(@fiscalYearID AS NVARCHAR(4)) + ' = 0) and not (Dollars = 0 and Units = 0)'

TRUNCATE TABLE #inputDepartments
INSERT INTO #inputDepartments
EXEC dbo.procGetInputDataByBatches
	@batchSize = @batchSize,
	@columnName = 'DepartmentID',
	@tableAlias = 'X',
	@fromClause = '#temp X',
	@whereClause = @sqlWhere,
	@isDebug = 0

SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments
SET @BatchID = 1
WHILE @BatchID <= @MaxBatchID
BEGIN
	INSERT INTO #FactGLStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Dollars, Units)
	SELECT source.DepartmentID, source.AccountID, source.FiscalYearID, source.FiscalMonthID, 20 as TimeClassID, source.Dollars, source.Units 
	FROM #temp source
	INNER JOIN #inputDepartments ID on ID.DepartmentID = source.DepartmentID
	WHERE (FiscalYearID = @fiscalYearID or @fiscalYearID = 0) and not (Dollars = 0 and Units = 0) AND ID.BatchID = @BatchID

	SET @BatchID = @BatchID + 1
END

IF OBJECT_ID('tempdb..#FiscalYearMonth') IS NOT NULL DROP TABLE #FiscalYearMonth
IF OBJECT_ID('tempdb..#AllCombinations') IS NOT NULL DROP TABLE #AllCombinations
IF OBJECT_ID('tempdb..#FinalDataset') IS NOT NULL DROP TABLE #FinalDataset
DROP TABLE #temp
GO


---------------------------------------------

-- fw.procFactMonthlyMergeDuplicates
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
** 1		2017-02-20	gforeman	D-05545	Created
*************************************************************/
CREATE PROC [fw].[procFactMonthlyMergeDuplicates] 
	@factTableName nvarchar(100),
	@keyNameCSV nvarchar(450),
	@measureNameCSV nvarchar(450),
	@fiscalYearID smallint = 0,
	@timeClassID tinyint = 0,
	@isDebugOnly bit = 0
with recompile
as
	set nocount on

	declare @sql nvarchar(max)

	--merge duplicate rows
	set @sql = '
		while (exists (select top 1 1 from ' + @factTableName + ' where IsDeleted = 1)) begin delete top(10000) data from ' + @factTableName + ' data where data.IsDeleted = 1 end;
		update data set data.IsDeleted = 1 from ' + @factTableName + ' data where ' + (case when @fiscalYearID > 0 then 'data.FiscalYearID between  ' + cast((@fiscalYearID-1) as nvarchar(4)) + ' and ' + cast(@fiscalYearID as nvarchar(4)) + ' and ' else '' end) + (case when @timeClassID > 0 then 'data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) + ' and ' else '' end) + ' exists(select 1 from (select DepartmentID, ' + @keyNameCSV + ', FiscalYearID, FiscalMonthID, TimeClassID from ' + @factTableName + ' where (1 = 1)' + (case when @fiscalYearID > 0 then ' and FiscalYearID between ' + cast((@fiscalYearID-1) as nvarchar(4)) + ' and ' + cast(@fiscalYearID as nvarchar(4)) else '' end) + (case when @timeClassID > 0 then ' and TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + ' group by DepartmentID, ' + @keyNameCSV + ', FiscalYearID, FiscalMonthID, TimeClassID having count(*) > 1) dr where dr.DepartmentID = data.DepartmentID and ' + (select dbo.straggr('dr.' + csv.val + ' = data.' + csv.val, ' and ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' and dr.FiscalYearID = data.FiscalYearID and dr.FiscalMonthID = data.FiscalMonthID and dr.TimeClassID = data.TimeClassID);
		insert into ' + @factTableName + ' (DepartmentID, ' + @keyNameCSV + ', FiscalYearID, FiscalMonthID, TimeClassID, ' + @measureNameCSV + ') select DepartmentID, ' + @keyNameCSV + ', FiscalYearID, FiscalMonthID, TimeClassID, sum(' + replace(@measureNameCSV, ',', '), sum(') + ') from ' + @factTableName + ' where IsDeleted = 1 group by DepartmentID, ' + @keyNameCSV + ', FiscalYearID, FiscalMonthID, TimeClassID;
		while (exists (select top 1 1 from ' + @factTableName + ' where IsDeleted = 1)) begin delete top(10000) data from ' + @factTableName + ' data where data.IsDeleted = 1 end;
	'
	if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end
GO


---------------------------------------------

-- fw.procFactMonthlyYTDPriorYearUpdate
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
** 1
** 2		2018-07-17	KF			B-20261 MR - Provider flexing - flexing
*************************************************************/
CREATE PROC [fw].[procFactMonthlyYTDPriorYearUpdate] 
	@factTableName nvarchar(100),
	@keyNameCSV nvarchar(450),
	@measureNameCSV nvarchar(450),
	@fiscalYearID smallint = 0,
	@timeClassID tinyint = 0,
	@isDebugOnly bit = 0
with recompile
as
set nocount on

	declare @sql nvarchar(max)

	--insert missing records
	set @sql = '
		declare @minYear int = ' + cast(@fiscalYearID as nvarchar(4)) + '
		declare @maxYear int = ' + cast(@fiscalYearID as nvarchar(4)) + '
		if (@minYear = 0 or @maxYear = 0) begin
			select @minYear = min(data.FiscalYearID) from ' + @factTableName + ' data ' + (case when @timeClassID > 0 then 'where data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + '
			select @maxYear = max(data.FiscalYearID) from ' + @factTableName + ' data ' + (case when @timeClassID > 0 then 'where data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + '
		end

		--records for ytd
	    insert into ' + @factTableName + '
	    (
            ' + @keyNameCSV + ',
            DepartmentID,
            FiscalYearID,
            FiscalMonthID,
            TimeClassID,
			IsSystemGenerated
	    )
		SELECT DISTINCT data.' + replace(@keyNameCSV, ',', ',data.') + ',data.DepartmentID,data.FiscalYearID,m.FiscalMonthID,data.TimeClassID,1
		FROM
	        ' + @factTableName + ' data
			inner join fw.DimFiscalMonth mm on mm.FiscalMonthID = data.FiscalMonthID 
			inner join fw.DimFiscalMonth m on m.SortOrder > mm.SortOrder
		where
	        data.FiscalYearID between @minYear and @maxYear
			' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + '
			and not exists (  --no existing reporting record for this tuple-month
				select   1 
				from
					' + @factTableName + ' datax
				where 
					(1 = 1)
					' + (select dbo.straggr('AND datax.' + csv.val + ' = data.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
					AND datax.DepartmentID = data.DepartmentID
					AND datax.FiscalYearID = data.FiscalYearID
					AND datax.FiscalMonthID = m.FiscalMonthID
					AND datax.TimeClassID = data.TimeClassID
			)
		option (recompile)

		--records for prior year, prior ytd
		DECLARE @currentYear INT, @maxYearForPriorYear INT
		SELECT @currentYear = Setting FROM dbo.DBSetting WHERE Name = ''Current_GL_YearID''
		SELECT @maxYearForPriorYear = CASE WHEN @maxYear > @currentYear THEN @currentYear ELSE @maxYear END
				
	    insert into ' + @factTableName + '
	    (
            ' + @keyNameCSV + ',
            DepartmentID,
            FiscalYearID,
            FiscalMonthID,
            TimeClassID,
			IsSystemGenerated
	    )
		SELECT DISTINCT data.' + replace(@keyNameCSV, ',', ',data.') + ',data.DepartmentID,data.FiscalYearID+1,m.FiscalMonthID,data.TimeClassID,1
		FROM
	        ' + @factTableName + ' data
			inner join fw.DimFiscalMonth mm on mm.FiscalMonthID = data.FiscalMonthID 
			inner join fw.DimFiscalMonth m on m.SortOrder >= mm.SortOrder
		where
	        data.FiscalYearID between @minYear-1 and @maxYearForPriorYear
			' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + '
			and not exists (  --no existing reporting record for this tuple-month
				select   1 
				from
					' + @factTableName + ' datax
				where 
					(1 = 1)
					' + (select dbo.straggr('AND datax.' + csv.val + ' = data.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
					AND datax.DepartmentID = data.DepartmentID
					AND datax.FiscalYearID-1 = data.FiscalYearID
					AND datax.FiscalMonthID = m.FiscalMonthID
					AND datax.TimeClassID = data.TimeClassID
			)
		option (recompile)
	'
	if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end

	--populate YTD and prior year measures
	set @sql = '
		select
		    data.DepartmentID,
		    data.' + replace(@keyNameCSV, ',', ', data.') + ',
		    data.FiscalYearID,
		    data.FiscalMonthID,
		    data.TimeClassID,
			' + (select dbo.straggr('SUM(data.' + csv.val + ') OVER (PARTITION BY data.DepartmentID,' + @keyNameCSV + ',TimeClassID,FiscalYearID ORDER BY fm.SortOrder) AS ' + csv.val + 'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		    ' + @measureNameCSV + '
		into #calculatedMeasures
		from
		    ' + @factTableName + ' data
		    inner join fw.DimFiscalMonth fm on fm.FiscalMonthID=data.FiscalMonthID
		where
			(1 = 1)
			' + (case when @fiscalYearID > 0 then 'and data.FiscalYearID between ' + cast(@fiscalYearID as nvarchar(4)) + '-1 and ' + cast(@fiscalYearID as nvarchar(4)) else '' end) + '
			' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + '
		option (recompile)

		CREATE UNIQUE CLUSTERED INDEX IX_calculatedMeasures ON #calculatedMeasures ( ' + @keyNameCSV + ', DepartmentID, FiscalYearID, FiscalMonthID, TimeClassID ) WITH ( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

		update M 
		set 
			' + (select dbo.straggr('m.' + csv.val + 'YTD = cm.' + csv.val + 'YTD', ',', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		from 
		    ' + @factTableName + ' m
		    INNER JOIN #calculatedMeasures cm ON
		                M.DepartmentID = cm.DepartmentID 
						' + (select dbo.straggr('AND M.' + csv.val + ' = cm.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
		                AND M.FiscalMonthID = cm.FiscalMonthID 
		                AND M.TimeClassID = cm.TimeClassID
		                and m.FiscalYearID = cm.FiscalYearID
		where
			' + (select dbo.straggr('m.' + csv.val + 'YTD <> cm.' + csv.val + 'YTD', ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		option (recompile)

		update M 
		set 
			' + (select dbo.straggr('m.' + csv.val + 'PriorYear = cm_py.' + csv.val, ',', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ',
			' + (select dbo.straggr('m.' + csv.val + 'PriorYTD = cm_py.' + csv.val + 'YTD', ',', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		from 
	        ' + @factTableName + ' m
	        INNER JOIN #calculatedMeasures cm_py ON
		                M.DepartmentID = cm_py.DepartmentID 
						' + (select dbo.straggr('AND M.' + csv.val + ' = cm_py.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
	                    AND M.FiscalMonthID = cm_py.FiscalMonthID 
	                    AND M.TimeClassID = cm_py.TimeClassID
	                    and m.FiscalYearID = cm_py.FiscalYearID+1
		where
			' + (select dbo.straggr('m.' + csv.val + 'PriorYear <> cm_py.' + csv.val, ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' or
			' + (select dbo.straggr('m.' + csv.val + 'PriorYTD <> cm_py.' + csv.val + 'YTD', ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		option (recompile)

		drop table #calculatedMeasures
	'
	if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end

	--delete zero records, possible only if YTD aggregates to zero due to negative values
	set @sql = '
		delete data
		from
	        ' + @factTableName + ' data
		where
			' + (select dbo.straggr('data.' + csv.val + ' = 0 and data.' + csv.val + 'YTD = 0 and data.' + csv.val + 'PriorYear = 0 and data.' + csv.val + 'PriorYTD = 0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
	'
	if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end
GO


---------------------------------------------

-- fw.procFactMonthlyYTDPriorYearUpdateStaging
/*************************************************************
** Change History
**************************************************************
** CID	Date        Author    	WI			Description
** 1	2017-06-15	IP		B-15086 Modify SP to use unique temp table
** 2	2017-07-13	IP		TK-45395 	fixed isSystemGenerated for generated records
** 3	2018-07-25	KF		B-20342		MR - Update provider sampling to be in the appropriate format
** 4	2018-08-22	KF		D-07561		MR Sampling: Provider FTEsYTD values are calculated incorrectly
** 5	2024-06-04	ishah	JAZZ-61244	MR - Add batches to procFactMonthlyYTDPriorYearUpdateStaging
*************************************************************/
CREATE PROCEDURE [fw].[procFactMonthlyYTDPriorYearUpdateStaging]
	@factTableName nvarchar(100),
	@stagingTableName nvarchar(100),
	@keyNameCSV nvarchar(450),
	@measureNameCSV nvarchar(450),
	@fiscalYearID smallint = 0,
	@timeClassID tinyint = 0,
	@isDebugOnly bit = 0
AS
	declare @sql nvarchar(max), @sqlJoin nvarchar(max), @sqlClauseForBatches nvarchar(max), @sqlWhere nvarchar(max), @sqlGroupBy nvarchar(max), @sqlParam nvarchar(max), @batchSize INT, @BatchID INT, @MaxBatchID INT
	declare @MaxYearForCalculation int= (select max(FiscalYearID) from int.FactStaffing), @maxFiscalYear int
	
	set @sql = N'SELECT @Output = max(FiscalYearID)  FROM '+@stagingTableName+''

	exec sp_executesql @sql, N'@Output INT OUTPUT', @Output=@maxFiscalYear OUTPUT;
	
	--insert missing records
	set @sql = '
	alter table '+@stagingTableName+'
	add SortOrder tinyint
	'
	if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end

	declare @isFTEsColumnPresent BIT
	IF EXISTS (SELECT val from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') WHERE val = 'FTEs')
	  SET @isFTEsColumnPresent = 1
	ELSE
	  SET @isFTEsColumnPresent = 0
	 		
	EXEC mr.procGetIntBatchSize
		@DefaultBatchSize = 30000000,
		@ResultBatchSize = @batchSize OUTPUT	

	SET @sqlClauseForBatches = @stagingTableName + ' X'

	set @sql = '
	  UPDATE tp
	  SET tp.SortOrder = fm.SortOrder
	  FROM '+@stagingTableName+' tp
	  INNER JOIN fw.DimFiscalMonth fm ON tp.FiscalMonthID = fm.FiscalMonthID
	  INNER JOIN #inputDepartments IP ON IP.DepartmentID = tp.DepartmentID
	  WHERE IP.BatchID = @BatchID
	'
	
	IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments
	CREATE TABLE #inputDepartments (DepartmentID INT, RecordsCount INT, BatchID INT)	
	
	INSERT INTO #inputDepartments
	EXEC dbo.procGetInputDataByBatches
	  	@batchSize = @batchSize,
		@columnName = 'DepartmentID',
		@tableAlias ='X',
		@fromClause = @sqlClauseForBatches,
		@whereClause = '',
		@isDebug = 0

	SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

	SET @SqlParam = '@BatchID INT'
	-- Loop thru batches and insert data
	SET @BatchID = 1
	WHILE @BatchID <= @MaxBatchID
	BEGIN
		EXEC sp_executesql @sql, @SqlParam, @BatchID = @BatchID;
		SET @BatchID = @BatchID + 1
	END	
				
	IF OBJECT_ID('tempdb..#dimMonth') IS NOT NULL DROP TABLE #dimMonth
	CREATE TABLE #dimMonth (FiscalMonthID tinyInt INDEX IX1 CLUSTERED, SortOrder tinyint)
	
	insert into #dimMonth (FiscalMonthID, SortOrder)
	select FiscalMonthID, SortOrder from fw.DimFiscalMonth where FiscalMonthID <> 0
	
	--- forming #MinSoTemp table and split by batches
	IF OBJECT_ID('tempdb..#MinSoTemp') IS NOT NULL DROP TABLE #MinSoTemp
	CREATE TABLE #MinSoTemp (DepartmentID int, FiscalYearID int, TimeClassID int, MinSortOrder int)	

	set @sql = '
		alter table #MinSoTemp
		add '+ replace(@keyNameCSV, ',', ' INT, ') +' int
	'
	
	if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end

	set @sqlClauseForBatches = '
		(
			'+(select case when @fiscalYearID > 0 THEN '
		SELECT '+replace(@keyNameCSV, ',', ',X.')+',
					X.DepartmentID,
					X.FiscalYearID,
					X.TimeClassID,
					min(mm.SortOrder) as MinSortOrder
				FROM ' + @factTableName + ' X 
				INNER JOIN #dimMonth mm
					ON mm.FiscalMonthID = x.FiscalMonthID
				WHERE FiscalYearID ='+cast(@fiscalYearID-1 as varchar(4))+'
				group by '+replace(@keyNameCSV, ',', ',X.')+',
					X.DepartmentID,
					X.FiscalYearID,
					X.TimeClassID
			UNION
				SELECT '+replace(@keyNameCSV, ',', ',X.')+',
					X.DepartmentID,
					X.FiscalYearID,
					X.TimeClassID,
					min(X.SortOrder) as MinSortOrder
				FROM '+@stagingTableName+' X 
				WHERE FiscalYearID ='+cast(@fiscalYearID as varchar(4))+'
				group by '+replace(@keyNameCSV, ',', ',X.')+',
					X.DepartmentID,
					X.FiscalYearID,
					X.TimeClassID

				' else '
				SELECT '+replace(@keyNameCSV, ',', ',X.')+',
					X.DepartmentID,
					X.FiscalYearID,
					X.TimeClassID,
					min(X.SortOrder) as MinSortOrder
				FROM '+@stagingTableName+' X 
				group by '+replace(@keyNameCSV, ',', ',X.')+',
					X.DepartmentID,
					X.FiscalYearID,
					X.TimeClassID
				' end )+'
		) X	
	'
	
	SET @sql = '
		INSERT INTO #MinSoTemp ('+ replace(@keyNameCSV, ',', ',') +', DepartmentID, FiscalYearID, TimeClassID, MinSortOrder)
			'+(select case when @fiscalYearID > 0 THEN '
			SELECT '+replace(@keyNameCSV, ',', ',X.')+',
						X.DepartmentID,
						X.FiscalYearID,
						X.TimeClassID,
						min(mm.SortOrder) as MinSortOrder
					FROM ' + @factTableName + ' X 
					INNER JOIN #dimMonth mm
						ON mm.FiscalMonthID = x.FiscalMonthID
					' + 'INNER JOIN #inputDepartments IP ON IP.DepartmentID = X.DepartmentID' + '
					WHERE IP.BatchID = @BatchID AND FiscalYearID ='+cast(@fiscalYearID-1 as varchar(4))+'
					group by '+replace(@keyNameCSV, ',', ',X.')+',
						X.DepartmentID,
						X.FiscalYearID,
						X.TimeClassID
				UNION
					SELECT '+replace(@keyNameCSV, ',', ',X.')+',
						X.DepartmentID,
						X.FiscalYearID,
						X.TimeClassID,
						min(X.SortOrder) as MinSortOrder
					FROM '+@stagingTableName+' X 
					' + 'INNER JOIN #inputDepartments IP ON IP.DepartmentID = X.DepartmentID' + '
					WHERE IP.BatchID = @BatchID AND FiscalYearID ='+cast(@fiscalYearID as varchar(4))+'
					group by '+replace(@keyNameCSV, ',', ',X.')+',
						X.DepartmentID,
						X.FiscalYearID,
						X.TimeClassID

					' else '
					SELECT '+replace(@keyNameCSV, ',', ',X.')+',
						X.DepartmentID,
						X.FiscalYearID,
						X.TimeClassID,
						min(X.SortOrder) as MinSortOrder
					FROM '+@stagingTableName+' X
					' + 'INNER JOIN #inputDepartments IP ON IP.DepartmentID = X.DepartmentID' + '
					WHERE IP.BatchID = @BatchID
					group by '+replace(@keyNameCSV, ',', ',X.')+',
						X.DepartmentID,
						X.FiscalYearID,
						X.TimeClassID
					' end )+'
		
	'	
	
	TRUNCATE TABLE #inputDepartments
	INSERT INTO #inputDepartments
	EXEC dbo.procGetInputDataByBatches
	  	@batchSize = @batchSize,
		@columnName = 'DepartmentID',
		@tableAlias ='X',
		@fromClause = @sqlClauseForBatches,
		@whereClause = '',
		@isDebug = 0

	SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

	SET @SqlParam = '@BatchID INT'
	-- Loop thru batches and insert data
	SET @BatchID = 1
	WHILE @BatchID <= @MaxBatchID
	BEGIN
		EXEC sp_executesql @sql, @SqlParam, @BatchID = @BatchID;
		SET @BatchID = @BatchID + 1
	END
		
	--- forming #MinPresentTemp table and split by batches
	IF OBJECT_ID('tempdb..#MinPresentTemp') IS NOT NULL DROP TABLE #MinPresentTemp
	CREATE TABLE #MinPresentTemp (DepartmentID int, FiscalYearID int, TimeClassID int, MinSortOrder int)	

	set @sql = '
		alter table #MinPresentTemp
		add '+ replace(@keyNameCSV, ',', ' INT, ') +' int
	'
	
	if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end
	
	set @sqlJoin = '
		SELECT '+replace(@keyNameCSV, ',', ',X.')+',
					X.DepartmentID,
					X.FiscalYearID,
					X.TimeClassID,
					min(X.MinSortOrder) as MinSortOrder
				FROM (SELECT '+replace(@keyNameCSV, ',', ',')+',
						DepartmentID,
						FiscalYearID,
						TimeClassID,
						MinSortOrder
					 FROM #MinSoTemp
					 UNION ALL
					 SELECT '+replace(@keyNameCSV, ',', ',')+',
						DepartmentID,
						FiscalYearID+1 as FiscalYearID,
						TimeClassID,
						MinSortOrder
					 FROM #MinSoTemp 
		) X
	'
	
	set @sqlWhere = 'where FiscalYearID <= ' + cast(@maxFiscalYear as nvarchar(max))
	set @sqlGroupBy = '
		GROUP BY '+replace(@keyNameCSV, ',', ',')+',
			X.DepartmentID,
			X.FiscalYearID,
			X.TimeClassID
	'
	
	SET @sqlClauseForBatches = '
		( ' + @sqlJoin + '
			' + @sqlWhere + ' 
			' + @sqlGroupBy + '
		) X
	'
		
	SET @sql = '
		INSERT INTO #MinPresentTemp ('+ replace(@keyNameCSV, ',', ',') +', DepartmentID, FiscalYearID, TimeClassID, MinSortOrder)
			' + @sqlJoin + '
			' + 'INNER JOIN #inputDepartments IP ON IP.DepartmentID = X.DepartmentID' + ' 
			'  + @sqlWhere + ' and IP.BatchID = @BatchID	
			' + @sqlGroupBy + '
	'
	
	TRUNCATE TABLE #inputDepartments
	INSERT INTO #inputDepartments
	EXEC dbo.procGetInputDataByBatches
	  	@batchSize = @batchSize,
		@columnName = 'DepartmentID',
		@tableAlias ='X',
		@fromClause = @sqlClauseForBatches,
		@whereClause = '',
		@isDebug = 0

	SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

	SET @SqlParam = '@BatchID INT'
	-- Loop thru batches and insert data
	SET @BatchID = 1
	WHILE @BatchID <= @MaxBatchID
	BEGIN
		EXEC sp_executesql @sql, @SqlParam, @BatchID = @BatchID;
		SET @BatchID = @BatchID + 1
	END
		
	--- forming #MissingListTemp table and split by batches
	IF OBJECT_ID('tempdb..#MissingListTemp') IS NOT NULL DROP TABLE #MissingListTemp
	CREATE TABLE #MissingListTemp (DepartmentID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, SortOrder int)	

	set @sql = '
		alter table #MissingListTemp
		add '+ replace(@keyNameCSV, ',', ' INT, ') +' int
	'
		
	if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end
	
	set @sqlJoin = '
		SELECT '+replace(@keyNameCSV, ',', ',')+',
			DepartmentID,
			FiscalYearID,
			mm.FiscalMonthID,
			TimeClassID,
			unpvt.SortOrder
		FROM (
			SELECT '+replace(@keyNameCSV, ',', ',')+',
				DepartmentID,
				FiscalYearID,
				TimeClassID,
				[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],
				MinSortOrder
			FROM (
			SELECT 
				isnull(TP.DepartmentID,MP.DepartmentID) as DepartmentID,
				' + (select dbo.straggr('isnull (TP.' + csv.val + ',MP.' + csv.val +') as ' + csv.val+',', ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
				isnull(TP.FiscalYearID,MP.FiscalYearID) as FiscalYearID,
				TP.FiscalMonthID as FiscalMonthID,
				isnull(TP.TimeClassID,MP.TimeClassID) as TimeClassID,
				0 as '+replace(@measureNameCSV, ',', ', 0 as ')+',
				0 as isDeleted,
				1 as isSystemGenerated,
				MP.MinSortOrder,
				TP.SortOrder
			FROM '+@stagingTableName+' TP
			FULL join #MinPresentTemp MP ON
				TP.DepartmentID = mp.DepartmentID
				' + (select dbo.straggr('AND TP.' + csv.val + ' = MP.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
				and TP.TimeClassID = mp.TimeClassID
				and TP.FiscalYearID = mp.FiscalYearID
			where (TP.SortOrder >= mp.MinSortOrder) or TP.SortOrder is null) ss /* there can be a subquery here*/
			PIVOT /* formation of the pivot table*/
				(count(FiscalMonthID) /*is an aggregate function that forms the contents of a pivot table*/
				FOR sortorder IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12]))  Pvt  /*alias for the pivot table*/
		) X
		UNPIVOT (isPresent /*the header of the column that will contain the values
				from the columns of the source table listed below*/
		FOR SortOrder IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) Unpvt
		INNER JOIN #dimMonth mm
					ON mm.SortOrder = Unpvt.SortOrder
	'
	
	set @sqlWhere = 'WHERE isPresent = 0 and Unpvt.SortOrder >= MinSortOrder'
	
	SET @sqlClauseForBatches = '
		( ' + @sqlJoin + '
			' + @sqlWhere + '
		) X
	'
		
	SET @sql = '
		INSERT INTO #MissingListTemp ('+ replace(@keyNameCSV, ',', ',') +', DepartmentID, FiscalYearID, FiscalMonthID, TimeClassID, SortOrder)
			SELECT '+replace(@keyNameCSV, ',', ',')+',
			DepartmentID,
			FiscalYearID,
			mm.FiscalMonthID,
			TimeClassID,
			unpvt.SortOrder
		FROM (
			SELECT '+replace(@keyNameCSV, ',', ',')+',
				DepartmentID,
				FiscalYearID,
				TimeClassID,
				[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],
				MinSortOrder
			FROM (
			SELECT 
				isnull(TP.DepartmentID,MP.DepartmentID) as DepartmentID,
				' + (select dbo.straggr('isnull (TP.' + csv.val + ',MP.' + csv.val +') as ' + csv.val+',', ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
				isnull(TP.FiscalYearID,MP.FiscalYearID) as FiscalYearID,
				TP.FiscalMonthID as FiscalMonthID,
				isnull(TP.TimeClassID,MP.TimeClassID) as TimeClassID,
				0 as '+replace(@measureNameCSV, ',', ', 0 as ')+',
				0 as isDeleted,
				1 as isSystemGenerated,
				MP.MinSortOrder,
				TP.SortOrder
			FROM '+@stagingTableName+' TP
			FULL join #MinPresentTemp MP ON
				TP.DepartmentID = mp.DepartmentID
				' + (select dbo.straggr('AND TP.' + csv.val + ' = MP.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
				and TP.TimeClassID = mp.TimeClassID
				and TP.FiscalYearID = mp.FiscalYearID
			INNER JOIN #inputDepartments IP ON IP.DepartmentID = MP.DepartmentID
			where IP.BatchID = @BatchID and (TP.SortOrder >= mp.MinSortOrder) or TP.SortOrder is null) ss /* there can be a subquery here*/
			PIVOT /* formation of the pivot table*/
				(count(FiscalMonthID) /*is an aggregate function that forms the contents of a pivot table*/
				FOR sortorder IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12]))  Pvt  /*alias for the pivot table*/
		) X
		UNPIVOT (isPresent /*the header of the column that will contain the values
				from the columns of the source table listed below*/
		FOR SortOrder IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) Unpvt
		INNER JOIN #dimMonth mm
					ON mm.SortOrder = Unpvt.SortOrder
			'  + @sqlWhere + '	
	'
	
	TRUNCATE TABLE #inputDepartments
	INSERT INTO #inputDepartments
	EXEC dbo.procGetInputDataByBatches
	  	@batchSize = @batchSize,
		@columnName = 'DepartmentID',
		@tableAlias ='X',
		@fromClause = @sqlClauseForBatches,
		@whereClause = '',
		@isDebug = 0

	SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

	SET @SqlParam = '@BatchID INT'
	-- Loop thru batches and insert data
	SET @BatchID = 1
	WHILE @BatchID <= @MaxBatchID
	BEGIN
		EXEC sp_executesql @sql, @SqlParam, @BatchID = @BatchID;
		SET @BatchID = @BatchID + 1
	END
		
	--- forming #calculatedMeasuresTemp table and split by batches
	IF OBJECT_ID('tempdb..#calculatedMeasuresTemp') IS NOT NULL DROP TABLE #calculatedMeasuresTemp
	CREATE TABLE #calculatedMeasuresTemp (DepartmentID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, isSystemGenerated int)	

	set @sql = '
		alter table #calculatedMeasuresTemp
		add '+ replace(@keyNameCSV, ',', ' INT, ') +' int
	'
	
	if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end

	set @sql = '
		alter table #calculatedMeasuresTemp
		add ' + replace(@measureNameCSV, ',', 'YTD decimal (25, 6),') + 'YTD decimal (25, 6)' + '
	'
	
	if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end

	set @sql = '
		alter table #calculatedMeasuresTemp
		add ' + replace(@measureNameCSV, ',', ' decimal (25, 6),') + ' decimal (25, 6)' + '
	'
	
	if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end
	
	set @sqlJoin = '
		select
		    uoag.DepartmentID,
		    uoag.' + replace(@keyNameCSV, ',', ', uoag.') + ',
		    uoag.FiscalYearID,
		    uoag.FiscalMonthID,
		    uoag.TimeClassID,
			' + (select dbo.straggr('SUM(uoag.' + csv.val + ') OVER (PARTITION BY uoag.DepartmentID,' + @keyNameCSV + ',TimeClassID,FiscalYearID ORDER BY fm.SortOrder) AS ' + csv.val + 'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		    ' + @measureNameCSV + ',
			uoag.isSystemGenerated
		from
			(
					SELECT 
			ML.DepartmentID,
			ML.' + replace(@keyNameCSV, ',', ', ML.') + ',
			ML.FiscalYearID,
			ML.FiscalMonthID,
			ML.TimeClassID,
			0 as '+replace(@measureNameCSV, ',', ', 0 as ')+',
			1 as isSystemGenerated
		FROM #MissingListTemp ML ' + case when @fiscalYearID > 0 then ' where ML.FiscalYearID = ' + cast(@fiscalYearID as nvarchar(4)) else '' end +'
		UNION 
		SELECT data.DepartmentID,
			data.' + replace(@keyNameCSV, ',', ', data.') + ',
			data.FiscalYearID,
		    data.FiscalMonthID,
		    data.TimeClassID,
			' + @measureNameCSV + ',
			data.isSystemGenerated
		    from '+@stagingTableName+' data
		where
			(1 = 1)
			' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + '
' + case when @fiscalYearID > 0 then '
		UNION 
		SELECT data.DepartmentID,
			data.' + replace(@keyNameCSV, ',', ', data.') + ',
			data.FiscalYearID,
		    data.FiscalMonthID,
		    data.TimeClassID,
			' + @measureNameCSV + ',
			1 as isSystemGenerated
		    from ' + @factTableName + ' data
		where data.FiscalYearID = ' + cast(@fiscalYearID-1 as nvarchar(4)) + case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end
	else '' end + '

		) uoag -- union ald and generated
		inner join #dimMonth fm on fm.FiscalMonthID=uoag.FiscalMonthID
	'

	SET @sqlClauseForBatches = '
		( ' + @sqlJoin + '
		) X
	'

	SET @sql = '
		INSERT INTO #calculatedMeasuresTemp (DepartmentID,  '+ replace(@keyNameCSV, ',', ',') +', FiscalYearID, FiscalMonthID, TimeClassID, ' + replace(@measureNameCSV, ',', 'YTD,') + 'YTD' + ',  ' + replace(@measureNameCSV, ',', ',') + ', isSystemGenerated)
			' + @sqlJoin + '
			' + 'INNER JOIN #inputDepartments IP ON IP.DepartmentID = uoag.DepartmentID' + ' 
			WHERE IP.BatchID = @BatchID	
	'

	TRUNCATE TABLE #inputDepartments
	INSERT INTO #inputDepartments
	EXEC dbo.procGetInputDataByBatches
	  	@batchSize = @batchSize,
		@columnName = 'DepartmentID',
		@tableAlias ='X',
		@fromClause = @sqlClauseForBatches,
		@whereClause = '',
		@isDebug = 0

	SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

	SET @SqlParam = '@BatchID INT'
	-- Loop thru batches and insert data
	SET @BatchID = 1
	WHILE @BatchID <= @MaxBatchID
	BEGIN
		EXEC sp_executesql @sql, @SqlParam, @BatchID = @BatchID;
		SET @BatchID = @BatchID + 1
	END
		
	-- insert into stagingTableName and spolit by bathes
	set @sqlJoin = '
		SELECT 
			cm.DepartmentID,
			cm.' + replace(@keyNameCSV, ',', ',cm.') + ',
			cm.FiscalYearID,
		    cm.FiscalMonthID,
		    cm.TimeClassID,
		' + (select dbo.straggr('isnull(cm.' + csv.val+',0) as '+ csv.val+',', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) +'
		' + (select dbo.straggr(case when csv.val = 'FTEs' then 'cast(0 as decimal(19, 4))' else 'isnull(cm.' + csv.val+'YTD,0) ' end + 'as '+csv.val+'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		' + (select dbo.straggr('isnull(cm_py.' + csv.val + ',0) as '+ csv.val+'PriorYear,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		' + (select dbo.straggr(case when csv.val = 'FTEs' then 'cast(0 as decimal(19, 4))' else 'isnull(cm_py.' + csv.val + 'YTD,0) ' end + 'as ' + csv.val + 'PriorYTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		isnull(cm.isSystemGenerated,0) as isSystemGenerated
		from #calculatedMeasuresTemp cm
		LEFT JOIN #calculatedMeasuresTemp cm_py ON
		                cm.DepartmentID = cm_py.DepartmentID 
						' + (select dbo.straggr('AND cm.' + csv.val + ' = cm_py.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
	                    AND cm.FiscalMonthID = cm_py.FiscalMonthID 
	                    AND cm.TimeClassID = cm_py.TimeClassID
	                    and cm.FiscalYearID = cm_py.FiscalYearID+1
		' + case when @fiscalYearID > 0 then ' WHERE cm.FiscalYearId = '+cast(@fiscalYearID as varchar(4)) else '' end+'
	'
	
	set @sqlWhere = '
		WHERE (
		' + (select dbo.straggr(csv.val+'<>0 ', ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) +'
		or ' + (select dbo.straggr(csv.val+'YTD<>0', ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		or ' + (select dbo.straggr(csv.val+'PriorYear<>0', ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		or ' + (select dbo.straggr(csv.val+'PriorYTD<>0', ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		)
	'
	
	SET @sqlClauseForBatches = '
	( 
		SELECT 
			PreSelect.*' + case when @isFTEsColumnPresent = 1 then '' else
			',
			FTEs=cast(0 as decimal(19, 4)),
			FTEsYTD=cast(0 as decimal(19, 4)),
			FTEsPriorYear=cast(0 as decimal(19, 4)),
			FTEsPriorYTD=cast(0 as decimal(19, 4))'end +
		'
		FROM
		 (
			' + @sqlJoin + '
		 ) PreSelect
			' + @sqlWhere + '
	) X
	'
	
	set @sql = '
		CREATE TABLE fw.'+replace(@stagingTableName,'#','')+'WithCalcs 
			(
				DepartmentID int, 
				'+ replace(@keyNameCSV, ',', ' INT, ') +' int, 
				FiscalYearID int, 
				FiscalMonthID int, 
				TimeClassID int, 
				'+ replace(@measureNameCSV, ',', ' decimal(25,6), ') +' decimal(25,6),
				' + (select dbo.straggr(case when csv.val = 'FTEs' then csv.val + 'YTD decimal(19,4),' else csv.val +  'YTD decimal(25,6),' end, '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
				'+ replace(@measureNameCSV, ',', 'PriorYear decimal(25,6), ') +'PriorYear decimal(25,6),
				' + (select dbo.straggr(case when csv.val = 'FTEs' then csv.val + 'PriorYTD decimal(19,4),' else csv.val +  'PriorYTD decimal(25,6),' end, '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
				isSystemGenerated int'
				+ case when @isFTEsColumnPresent = 1 then '' else
				',
				FTEs decimal(19,4),
				FTEsYTD decimal(19,4),
				FTEsPriorYear decimal(19,4),
				FTEsPriorYTD decimal(19,4)'end +
		'
			)				
	'
	
	if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end
	
	SET @sql = '
	INSERT INTO fw.'+replace(@stagingTableName,'#','')+'WithCalcs
	SELECT 
			PreSelect.*' + case when @isFTEsColumnPresent = 1 then '' else
			',
			FTEs=cast(0 as decimal(19, 4)),
			FTEsYTD=cast(0 as decimal(19, 4)),
			FTEsPriorYear=cast(0 as decimal(19, 4)),
			FTEsPriorYTD=cast(0 as decimal(19, 4))'end+
	'
	FROM
		 (
			' + @sqlJoin + '
		 ) PreSelect
	INNER JOIN #inputDepartments IP ON IP.DepartmentID = PreSelect.DepartmentID
	' + @sqlWhere + ' and IP.BatchID = @BatchID	
	'
	
	TRUNCATE TABLE #inputDepartments
	INSERT INTO #inputDepartments
	EXEC dbo.procGetInputDataByBatches
	  	@batchSize = @batchSize,
		@columnName = 'DepartmentID',
		@tableAlias ='X',
		@fromClause = @sqlClauseForBatches,
		@whereClause = '',
		@isDebug = 0

	SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

	SET @SqlParam = '@BatchID INT'
	-- Loop thru batches and insert data
	SET @BatchID = 1
	WHILE @BatchID <= @MaxBatchID
	BEGIN
		EXEC sp_executesql @sql, @SqlParam, @BatchID = @BatchID;
		SET @BatchID = @BatchID + 1
	END
		
	set @sql = 'drop table '+@stagingTableName+' '
	
	if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end
	
	IF OBJECT_ID('tempdb..#dimMonth') IS NOT NULL DROP TABLE #dimMonth
	IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments
	IF OBJECT_ID('tempdb..#MinSoTemp') IS NOT NULL DROP TABLE #MinSoTemp
	IF OBJECT_ID('tempdb..#MinPresentTemp') IS NOT NULL DROP TABLE #MinPresentTemp
	IF OBJECT_ID('tempdb..#MissingListTemp') IS NOT NULL DROP TABLE #MissingListTemp
	IF OBJECT_ID('tempdb..#calculatedMeasuresTemp') IS NOT NULL DROP TABLE #calculatedMeasuresTemp
GO


---------------------------------------------

-- fw.procFactPayPeriodMergeDuplicates
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
** 1		2017-10-56	gforeman	D-05545	Created
*************************************************************/
create proc [fw].[procFactPayPeriodMergeDuplicates] 
	@factTableName nvarchar(100),
	@keyNameCSV nvarchar(450),
	@measureNameCSV nvarchar(450),
	@fiscalYearID smallint = 0,
	@timeClassID tinyint = 0,
	@isDebugOnly bit = 0,
	@departmentIDs nvarchar(max) = null
with recompile
as
	set nocount on

	declare @sql nvarchar(max)

	--merge duplicate rows
	set @sql = '
		while (exists (select top 1 1 from ' + @factTableName + ' where IsDeleted = 1)) begin delete top(10000) data from ' + @factTableName + ' data where data.IsDeleted = 1 end;
		update data set data.IsDeleted = 1 from ' + @factTableName + ' data inner join fw.DimPayPeriod pp on pp.PayPeriodID = data.PayPeriodID where ' + (case when @fiscalYearID > 0 then 'pp.FiscalYearIDSecond between ' + cast((@fiscalYearID-1) as nvarchar(4)) + ' and ' + cast(@fiscalYearID as nvarchar(4)) + ' and ' else '' end) + (case when @timeClassID > 0 then 'data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) + ' and ' else '' end) + ' exists(select 1 from (select fd.DepartmentID, fd.' + replace(@keyNameCSV, ',', ', fd.') + ', fd.PayPeriodID, fd.TimeClassID from ' + @factTableName + ' fd inner join fw.DimPayPeriod p on p.PayPeriodID = fd.PayPeriodID where (1 = 1)' + (case when @fiscalYearID > 0 then ' and p.FiscalYearIDSecond between ' + cast((@fiscalYearID-1) as nvarchar(4)) + ' and ' + cast(@fiscalYearID as nvarchar(4)) else '' end) + (case when @timeClassID > 0 then ' and fd.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + ' group by fd.DepartmentID, fd.' + replace(@keyNameCSV, ',', ', fd.') + ', fd.PayPeriodID, fd.TimeClassID having count(*) > 1) dr where dr.DepartmentID = data.DepartmentID and ' + (select dbo.straggr('dr.' + csv.val + ' = data.' + csv.val, ' and ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' and dr.PayPeriodID = data.PayPeriodID and dr.TimeClassID = data.TimeClassID);
		insert into ' + @factTableName + ' (DepartmentID, ' + @keyNameCSV + ', PayPeriodID, TimeClassID, ' + @measureNameCSV + ') select DepartmentID, ' + @keyNameCSV + ', PayPeriodID, TimeClassID, sum(' + replace(@measureNameCSV, ',', '), sum(') + ') from ' + @factTableName + ' where IsDeleted = 1 group by DepartmentID, ' + @keyNameCSV + ', PayPeriodID, TimeClassID;
		while (exists (select top 1 1 from ' + @factTableName + ' where IsDeleted = 1)) begin delete top(10000) data from ' + @factTableName + ' data where data.IsDeleted = 1 end;
	'
	if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end
GO


---------------------------------------------

-- fw.procFactPayPeriodYTDPriorYearUpdate
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
** 1		2014-09-09	gforeman	B-02162	Added merge rows step
** 2		2014-09-09	gforeman	B-02162	Run prior year when year specified
** 3		2014-09-18	gforeman	B-02682	Additional speedups to insert missing step
** 4		2015-09-14	mschmitz	B-08303 Added PayCycleID to partition and indexing
** 5		2015-10-13	nleroy		D-03496	FTEsYTD fix
** 6		2015-10-20	mschmitz	B-08303 Fixed bug found related to B-08303 change
** 7        2016-03-23  mholov      D-04105 Added rolling delete on fact Table
** 8		2016-07-28	akozlov		D-04262 Added IsSystemGenerated flag setting for inserted records
** 9		2016-09-48	gforeman	D-04759 Optimize YTD calc
** 10		2016-09-26	akozlov		D-04899 Reverted optimization
** 11		2016-09-26	akozlov		D-04899 Fixed performance bug
** 12		2016-10-10	gforeman	D-05000 Add IsSystemGenerated reset
** 13		2016-12-27	akozlov		D-05183 Removed IsSystemGenerated reset
** 14		2017-01-23	gforeman	D-05419 Misc perf improvements, add department parameter
** 15		2017-02-17	gforeman	B-14308 Temp table tuning
** 16		2017-02-20	gforeman	D-05545 Move duplicate record handling from YTD into sampling
** 17		2018-11-07	KF			D-06432		PR - YTD Labor Expense PR Metrics Do Not Match Payroll
** 18		2022-03-01	KF			JAZZ-13874 Stored procedure fw.procFactPayPeriodYTDPriorYearUpdate is timing out
** 19		2024-01-29	KF			JAZZ-66821	Run PR Process Task: Some procs don't support non-consecutive pay period id (expect consecutive pay period id). It causes wrong YTD values & wrong Rolling Average Baseline Target values
*************************************************************/
CREATE proc [fw].[procFactPayPeriodYTDPriorYearUpdate] 
	@factTableName nvarchar(100),
	@keyNameCSV nvarchar(450),
	@measureNameCSV nvarchar(450),
	@fiscalYearID smallint = 0,
	@timeClassID tinyint = 0,
	@isDebugOnly bit = 0,
	@departmentIDs nvarchar(max) = null
with recompile
as
	set nocount on

	declare @sql nvarchar(max)

	--insert missing records
	set @sql = '
		declare @minYear int = ' + cast(@fiscalYearID as nvarchar(4)) + '
		declare @maxYear int = ' + cast(@fiscalYearID as nvarchar(4)) + '
		if (@minYear <= 0 or @maxYear <= 0) begin
			select @minYear = min(pp.FiscalYearIDSecond) from ' + @factTableName + ' data INNER JOIN fw.DimPayPeriod pp ON data.PayPeriodID = pp.PayPeriodID ' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + (case when @departmentIDs is not null then ' and data.DepartmentID in(select val from ConvertCSValuesToTable(''' + @departmentIDs + ''', '',''))' else '' end) + '
			select @maxYear = max(pp.FiscalYearIDSecond) from ' + @factTableName + ' data INNER JOIN fw.DimPayPeriod pp ON data.PayPeriodID = pp.PayPeriodID ' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + (case when @departmentIDs is not null then ' and data.DepartmentID in(select val from ConvertCSValuesToTable(''' + @departmentIDs + ''', '',''))' else '' end) + '
		end

		--records for ytd
	    insert into ' + @factTableName + '
	    (
            DepartmentID,
            ' + @keyNameCSV + ',
            PayPeriodID,
            TimeClassID,
			IsSystemGenerated
	    )
		SELECT DISTINCT data.DepartmentID,data.' + replace(@keyNameCSV, ',', ',data.') + ',p.PayPeriodID,data.TimeClassID,1
		FROM
			' + @factTableName + ' data
			' + (case when @departmentIDs is not null then 'inner join (select val as DepartmentID from ConvertCSValuesToTable(''' + @departmentIDs + ''', '','')) dept on dept.DepartmentID = data.DepartmentID' else '' end) + '
			inner join fw.DimPayPeriod pp ON data.PayPeriodID = pp.PayPeriodID
			inner join fw.DimPayCycle pc on pc.PayCycleID = pp.PayCycleID
			inner join pi.viewNextAfterCurrentPayPeriod npp on npp.PayCycleID = pc.PayCycleID
			inner join fw.DimPayPeriod p on p.FiscalYearIDSecond = pp.FiscalYearIDSecond and p.PayCycleID = pp.PayCycleID and p.PeriodNumber > pp.PeriodNumber and p.FiscalYearIDSecond <= npp.FiscalYearIDSecond
			left join dbo.ColumnStoreIndex csi ON 1=0 -- tricky fix for JAZZ-13874
		where
			pp.FiscalYearIDSecond between @minYear and @maxYear
			' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + '
			and not exists (  --existing record for this tuple-payperiod
		        select   1 
		        from
		            ' + @factTableName + ' datax
		        where 
	                datax.DepartmentID = data.DepartmentID
					' + (select dbo.straggr('AND datax.' + csv.val + ' = data.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
					AND datax.PayPeriodID = p.PayPeriodID
	                AND datax.TimeClassID = data.TimeClassID
		    )
		option (recompile)

		--records for prior year, prior ytd
	    insert into ' + @factTableName + '
	    (
            DepartmentID,
            ' + @keyNameCSV + ',
            PayPeriodID,
            TimeClassID,
			IsSystemGenerated
	    )
		SELECT DISTINCT data.DepartmentID,data.' + replace(@keyNameCSV, ',', ',data.') + ',p.PayPeriodID,data.TimeClassID,1
		FROM
			' + @factTableName + ' data
			' + (case when @departmentIDs is not null then 'inner join (select val as DepartmentID from ConvertCSValuesToTable(''' + @departmentIDs + ''', '','')) dept on dept.DepartmentID = data.DepartmentID' else '' end) + '
			inner join fw.DimPayPeriod pp ON data.PayPeriodID = pp.PayPeriodID
			inner join fw.DimPayCycle pc on pc.PayCycleID = pp.PayCycleID
			inner join pi.viewNextAfterCurrentPayPeriod npp on npp.PayCycleID = pc.PayCycleID
			inner join fw.DimPayPeriod p on p.FiscalYearIDSecond = pp.FiscalYearIDSecond+1 and p.PayCycleID = pp.PayCycleID and p.PeriodNumber >= pp.PeriodNumber and p.FiscalYearIDSecond <= npp.FiscalYearIDSecond
			left join dbo.ColumnStoreIndex csi ON 1=0 -- tricky fix for JAZZ-13874
		where
			pp.FiscalYearIDSecond between @minYear-1 and @maxYear-1
			' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + '
			and not exists (  --existing record for this tuple-payperiod
		        select   1 
		        from
		            ' + @factTableName + ' datax
		        where 
	                datax.DepartmentID = data.DepartmentID
					' + (select dbo.straggr('AND datax.' + csv.val + ' = data.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
					AND datax.PayPeriodID = p.PayPeriodID
	                AND datax.TimeClassID = data.TimeClassID
		    )
		option (recompile)
	'
	if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end

	--populate YTD and prior year measures
	set @sql = '
		select
		    data.DepartmentID,
		    data.' + replace(@keyNameCSV, ',', ',data.') + ',
			pp.PayCycleID,
			pp.FiscalYearIDSecond,
			pp.PeriodNumber,
		    data.TimeClassID,
			' + (select dbo.straggr('SUM(data.' + csv.val + ') OVER (PARTITION BY data.DepartmentID,' + @keyNameCSV + ',TimeClassID,pp.PayCycleID,FiscalYearIDSecond ORDER BY pp.PayCycleID, pp.FiscalYearIDSecond, pp.PeriodNumber) AS ' + csv.val + 'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		    ' + @measureNameCSV + '
		into #calculatedMeasures
		from
		    ' + @factTableName + ' data
			' + (case when @departmentIDs is not null then 'inner join (select val as DepartmentID from ConvertCSValuesToTable(''' + @departmentIDs + ''', '','')) dept on dept.DepartmentID = data.DepartmentID' else '' end) + '
		    inner join fw.DimPayPeriod pp on pp.PayPeriodID=data.PayPeriodID
		where
			(1 = 1)
			' + (case when @fiscalYearID > 0 then 'and pp.FiscalYearIDSecond between ' + cast(@fiscalYearID as nvarchar(4)) + '-1 and ' + cast(@fiscalYearID as nvarchar(4)) else '' end) + '
			' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + '
		option (recompile)

		CREATE UNIQUE CLUSTERED INDEX IX_calculatedMeasures ON #calculatedMeasures ( DepartmentID, ' + @keyNameCSV + ', PayCycleID, FiscalYearIDSecond, PeriodNumber, TimeClassID ) WITH ( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

		update M 
		set 
			' + (select dbo.straggr('m.' + csv.val + 'YTD = cm.' + csv.val + 'YTD', ',', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		from 
		    ' + @factTableName + ' m
			inner join fw.DimPayPeriod pp on pp.PayPeriodID=m.PayPeriodID
		    INNER JOIN #calculatedMeasures cm ON
		                M.DepartmentID = cm.DepartmentID 
						' + (select dbo.straggr('AND M.' + csv.val + ' = cm.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
						AND pp.PayCycleID = cm.PayCycleID
						AND pp.FiscalYearIDSecond = cm.FiscalYearIDSecond
						AND pp.PeriodNumber = cm.PeriodNumber
		                AND M.TimeClassID = cm.TimeClassID
		where
			' + (select dbo.straggr('m.' + csv.val + 'YTD <> cm.' + csv.val + 'YTD', ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		option (recompile)

		update M 
		set 
			' + (select dbo.straggr('m.' + csv.val + 'PriorYear = cm_py.' + csv.val, ',', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ',
			' + (select dbo.straggr('m.' + csv.val + 'PriorYTD = cm_py.' + csv.val + 'YTD', ',', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		from 
	        ' + @factTableName + ' m
			inner join fw.DimPayPeriod pp on pp.PayPeriodID=m.PayPeriodID
	        INNER JOIN #calculatedMeasures cm_py ON
		                M.DepartmentID = cm_py.DepartmentID 
						' + (select dbo.straggr('AND M.' + csv.val + ' = cm_py.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
						AND pp.PayCycleID = cm_py.PayCycleID
						AND pp.FiscalYearIDSecond = cm_py.FiscalYearIDSecond+1
						AND pp.PeriodNumber = cm_py.PeriodNumber
		                AND M.TimeClassID = cm_py.TimeClassID
		where
			' + (select dbo.straggr('m.' + csv.val + 'PriorYear <> cm_py.' + csv.val, ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' or
			' + (select dbo.straggr('m.' + csv.val + 'PriorYTD <> cm_py.' + csv.val + 'YTD', ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		option (recompile)

		drop table #calculatedMeasures
	'
	if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end

	--delete zero records, possible only if YTD aggregates to zero due to negative values
	set @sql = '
		delete data
		from
	        ' + @factTableName + ' data
		where
			' + (select dbo.straggr('data.' + csv.val + ' = 0 and data.' + csv.val + 'YTD = 0 and data.' + csv.val + 'PriorYear = 0 and data.' + csv.val + 'PriorYTD = 0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
	'
	if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end
GO


---------------------------------------------

-- fw.procFactPayPeriodYTDPriorYearUpdate_AG
/***************************************************************
** CID		Date		Author		WI			Description
** 1		2017-06-09	ipetriv		TK-44047	fixing one-year integraion test for fw_procPayrollSampledDailyDetailedInsert
** 2		2017-06-15	IP			B-15086		Modify SP to use unique temp table
** 3		2019-08-21	vfay		D-08311		PR Sampling Proc : removed filtering out 0 Value Rows
** 4		2023-10-18	KF			JAZZ-62485	Technical - Update procs to support 7 days pay periods for Pay Period and Daily
** 5		2024-01-29	KF			JAZZ-66821	Run PR Process Task: Some procs don't support non-consecutive pay period id (expect consecutive pay period id). It causes wrong YTD values & wrong Rolling Average Baseline Target values
** 6		2024-02-08	KF			JAZZ-67258	Current year runs of the Run PR Process Task have been failing.
** 7		2024-02-12	HV			JAZZ-15888	[fw].[procPayrollSampledPayPeriodInsert]: YTD records are not sampled properly for TimeClassID=20 when run proc for all years and Target Basis=Rolling Average
**************************************************************/
CREATE PROC [fw].[procFactPayPeriodYTDPriorYearUpdate_AG] 
	@factTableName nvarchar(100),
	@stagingTableName varchar(100),
	@keyNameCSV nvarchar(450),
	@measureNameCSV nvarchar(450),
	@fiscalYearID smallint = 0,
	@timeClassID tinyint = 0,
	@isDebugOnly bit = 0
as
set nocount on

	declare @sql nvarchar(max)
	declare @MaxYearForCalculation int= (select max(FiscalYearID) from int.FactStaffing)
	declare @PeriodsList nvarchar(max) = ''
	select @PeriodsList = @PeriodsList+',['+cast(PeriodNumber as varchar(3))+']' FROM (select distinct PeriodNumber from fw.DimPayPeriod where PeriodNumber <> 0) PN
	set @PeriodsList = SUBSTRING(@PeriodsList,2,LEN(@PeriodsList)-1)

	/*insert missing records*/
	set @sql = '
	alter table '+@stagingTableName+'
	add PeriodNumber int

	alter table '+@stagingTableName+'
	add FiscalYearID int
	
	ALTER TABLE '+@stagingTableName+'
	ADD PayCycleID int
	'
	if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end
	
	set @sql = '
	UPDATE tp
	SET tp.PeriodNumber = fm.PeriodNumber,
	tp.FiscalYearID = fm.FiscalYearIDSecond,
	tp.PayCycleID = d.PayCycleID
	FROM '+@stagingTableName+' tp
	INNER JOIN fw.DimPayPeriod fm
		ON tp.PayPeriodID = fm.PayPeriodID
	INNER JOIN fw.DimDepartment d
		ON tp.DepartmentID = d.DepartmentID

	CREATE TABLE #dimPayPeriod (PayPeriodID INT,FiscalYearID int, PeriodNumber TINYINT, PayCycleID int, UNIQUE CLUSTERED (PeriodNumber,FiscalYearID,PayCycleID))

	INSERT INTO #dimPayPeriod
	SELECT dpp.PayPeriodID, dpp.FiscalYearIDSecond, dpp.PeriodNumber, dpp.PayCycleID
	FROM fw.DimPayPeriod dpp
	inner join pi.viewNextAfterCurrentPayPeriod npp on dpp.PayCycleID = npp.PayCycleID and dpp.FiscalYearIDSecond <= npp.FiscalYearIDSecond
	WHERE PayPeriodID <> 0;

	;WITH MinSO as ('+(select case when @fiscalYearID > 0 THEN '
			SELECT '+replace(@keyNameCSV, ',', ',X.')+',
					X.DepartmentID,
					mm.FiscalYearID,
					X.TimeClassID,
					min(mm.PeriodNumber) as MinPeriodNumber
				FROM ' + @factTableName + ' X 
				INNER JOIN #dimPayPeriod mm
					ON mm.PayPeriodID = x.PayPeriodID
				WHERE FiscalYearID ='+cast(@fiscalYearID-1 as varchar(4))+'
				group by '+replace(@keyNameCSV, ',', ',X.')+',
					X.DepartmentID,
					mm.FiscalYearID,
					X.TimeClassID
			UNION
				SELECT '+replace(@keyNameCSV, ',', ',X.')+',
					X.DepartmentID,
					X.FiscalYearID,
					X.TimeClassID,
					min(X.PeriodNumber) as MinPeriodNumber
				FROM '+@stagingTableName+' X 
				WHERE FiscalYearID ='+cast(@fiscalYearID as varchar(4))+'
				group by '+replace(@keyNameCSV, ',', ',X.')+',
					X.DepartmentID,
					X.FiscalYearID,
					X.TimeClassID

				' else '
				SELECT '+replace(@keyNameCSV, ',', ',X.')+',
					X.DepartmentID,
					X.FiscalYearID,
					X.TimeClassID,
					min(X.PeriodNumber) as MinPeriodNumber
				FROM '+@stagingTableName+' X 
				group by '+replace(@keyNameCSV, ',', ',X.')+',
					X.DepartmentID,
					X.FiscalYearID,
					X.TimeClassID
				' end )+')
	,MinPresent as (

		SELECT '+replace(@keyNameCSV, ',', ',X.')+',
					X.DepartmentID,
					X.FiscalYearID,
					X.TimeClassID,
					dd.PayCycleID,
					min(X.MinPeriodNumber) as MinPeriodNumber
				FROM (SELECT '+replace(@keyNameCSV, ',', ',')+',
						DepartmentID,
						FiscalYearID,
						TimeClassID,
						MinPeriodNumber
					 FROM MinSO 
					 UNION ALL
					 SELECT '+replace(@keyNameCSV, ',', ',')+',
						DepartmentID,
						FiscalYearID+1 as FiscalYearID,
						TimeClassID,
						MinPeriodNumber
					 FROM MinSO 
					 ) X
					 inner join fw.DimDepartment dd on dd.DepartmentID = x.DepartmentID
					 where FiscalYearID <= (SELECT max(FiscalYearID)  FROM '+@stagingTableName+')
					 GROUP BY '+replace(@keyNameCSV, ',', ',')+',
							X.DepartmentID,
							X.FiscalYearID,
							X.TimeClassID,
							dd.PayCycleID
	)		

	,MissingList AS (
		SELECT '+replace(@keyNameCSV, ',', ',')+',
			DepartmentID,
			Unpvt.FiscalYearID,
			mm.PayPeriodID,
			TimeClassID,
			unpvt.PeriodNumber
		FROM (
			SELECT '+replace(@keyNameCSV, ',', ',')+',
				DepartmentID,
				FiscalYearID,
				TimeClassID,
				PayCycleID,
				'+@PeriodsList+',
				MinPeriodNumber
			FROM (
			SELECT 
				isnull(TP.DepartmentID,MP.DepartmentID) as DepartmentID,
				' + (select dbo.straggr('isnull (TP.' + csv.val + ',MP.' + csv.val +') as ' + csv.val+',', ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
				isnull(TP.FiscalYearID,MP.FiscalYearID) as FiscalYearID,
				TP.PayPeriodID as PayPeriodID,
				isnull(TP.PayCycleID,MP.PayCycleID) as PayCycleID,
				isnull(TP.TimeClassID,MP.TimeClassID) as TimeClassID,
				0 as '+replace(@measureNameCSV, ',', ', 0 as ')+',
				0 as isDeleted,
				1 as isSystemGenerated,
				MP.MinPeriodNumber,
				isnull(TP.PeriodNumber,mp.MinPeriodNumber) as PeriodNumber
			FROM '+@stagingTableName+' TP
			FULL join MinPresent MP ON
				TP.DepartmentID = mp.DepartmentID
				' + (select dbo.straggr('AND TP.' + csv.val + ' = MP.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
				and TP.TimeClassID = mp.TimeClassID
				and TP.FiscalYearID = mp.FiscalYearID
			where (TP.PeriodNumber >= mp.MinPeriodNumber) or TP.PeriodNumber is null) ss /* there can be a subquery here*/
			PIVOT /*formation of the pivot table*/
				(count(PayPeriodID) /*is an aggregate function that forms the contents of a pivot table*/
				FOR PeriodNumber IN ('+@PeriodsList+'))  Pvt /* alias for the pivot table*/
		) X 
		UNPIVOT (isPresent /* the header of the column that will contain the values
		 from the columns of the source table listed below*/
		FOR PeriodNumber IN ('+@PeriodsList+')) Unpvt
		INNER JOIN #dimPayPeriod mm
			ON mm.PeriodNumber = Unpvt.PeriodNumber 
			and mm.FiscalYearID = Unpvt.FiscalYearID 
			and mm.PayCycleID = unpvt.PayCycleID
		WHERE isPresent = 0 and Unpvt.PeriodNumber >= MinPeriodNumber)

		
		, calculatedMeasures as (
		select
		    uoag.DepartmentID,
		    uoag.' + replace(@keyNameCSV, ',', ', uoag.') + ',
		    uoag.FiscalYearID,
		    uoag.PayPeriodID,
		    pp.PayCycleID,
		    uoag.TimeClassID,
		    pp.PeriodNumber,
			' + (select dbo.straggr('SUM(uoag.' + csv.val + ') OVER (PARTITION BY uoag.DepartmentID,' + @keyNameCSV + ',TimeClassID,FiscalYearID,pp.PayCycleID ORDER BY pp.PeriodNumber) AS ' + csv.val + 'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		    ' + @measureNameCSV + ',
			uoag.isSystemGenerated
		from
			(
					SELECT 
			ML.DepartmentID,
			ML.' + replace(@keyNameCSV, ',', ', ML.') + ',
			ML.FiscalYearID,
			ML.PayPeriodID,
			ML.TimeClassID,
			0 as '+replace(@measureNameCSV, ',', ', 0 as ')+',
			1 as isSystemGenerated
		FROM MissingList ML ' + case when @fiscalYearID > 0 then ' where ML.FiscalYearID = ' + cast(@fiscalYearID as nvarchar(4)) else '' end +'
		UNION 
		SELECT data.DepartmentID,
			data.' + replace(@keyNameCSV, ',', ', data.') + ',
			data.FiscalYearID,
		    data.PayPeriodID,
		    data.TimeClassID,
			' + @measureNameCSV + ',
			data.isSystemGenerated
		    from '+@stagingTableName+' data
		where
			(1 = 1)
			' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + '' + case when @fiscalYearID > 0 then '
		UNION 
		SELECT data.DepartmentID,
			data.' + replace(@keyNameCSV, ',', ', data.') + ',
			mm.FiscalYearID,
		    data.PayPeriodID,
		    data.TimeClassID,
			' + @measureNameCSV + ',
			data.isSystemGenerated
		    from ' + @factTableName + ' data
			INNER JOIN #dimPayPeriod mm
					ON mm.PayPeriodID = data.PayPeriodID
		where mm.FiscalYearID = ' + cast(@fiscalYearID-1 as nvarchar(4)) + case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end
	else '' end + '

		) uoag /* union ald and generated*/
		inner join fw.dimPayPeriod pp on uoag.PayPeriodID = pp.PayPeriodID
		)

		SELECT 
			PreSelect.*
		INTO fw.'+replace(@stagingTableName,'#','')+'WithCalcs
		FROM (
		SELECT 
			cm.DepartmentID,
			cm.' + replace(@keyNameCSV, ',', ',cm.') + ',
			cm.FiscalYearID,
		    cm.PayPeriodID,
		    cm.TimeClassID,
		' + (select dbo.straggr('isnull(cm.' + csv.val+',0) as '+ csv.val+',', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) +'
		' + (select dbo.straggr('isnull(cm.' + csv.val+'YTD,0) as '+csv.val+'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		' + (select dbo.straggr('isnull(cm_py.' + csv.val + ',0) as '+ csv.val+'PriorYear,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		' + (select dbo.straggr('isnull(cm_py.' + csv.val + 'YTD,0) as ' + csv.val + 'PriorYTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
			isnull(cm.isSystemGenerated,0) as isSystemGenerated
		from calculatedMeasures cm
		LEFT JOIN calculatedMeasures cm_py ON
		                cm.DepartmentID = cm_py.DepartmentID 
						' + (select dbo.straggr('AND cm.' + csv.val + ' = cm_py.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
	                    AND cm.PeriodNumber = cm_py.PeriodNumber
	                    AND cm.PayCycleID = cm_py.PayCycleID
	                    AND cm.TimeClassID = cm_py.TimeClassID
	                    and cm.FiscalYearID = cm_py.FiscalYearID+1
		' + case when @fiscalYearID > 0 then ' WHERE cm.FiscalYearId = '+cast(@fiscalYearID as varchar(4)) else '' end+'
		) PreSelect
		WHERE NOT(' + (select dbo.straggr(csv.val+'=0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) +'
		and ' + (select dbo.straggr(csv.val + 'YTD=0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		and ' + (select dbo.straggr(csv.val + 'PriorYear=0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		and ' + (select dbo.straggr(csv.val + 'PriorYTD=0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
		and isSystemGenerated = 1)
		UNION ALL
		SELECT 
			data.DepartmentID,
			data.' + replace(@keyNameCSV, ',', ', data.') + ',
			data.FiscalYearID,
		    data.PayPeriodID,
		    data.TimeClassID,
			' + (select dbo.straggr(csv.val+',', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) +'
			' + (select dbo.straggr(csv.val+'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
			' + (select dbo.straggr(csv.val+'PriorYear,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
			' + (select dbo.straggr(csv.val+'PriorYTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
			data.isSystemGenerated
		    from '+@stagingTableName+' data
			WHERE TimeClassID <> 20
	
	drop table '+@stagingTableName+'
	'
	if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end
GO


---------------------------------------------

-- fw.procFactPayPeriodYTDPriorYearUpdate_Staging
/**************************************************************
** Change History
**************************************************************
** 1		2017-06-15	IP		B-15086 Modify SP to use unique temp table
** 2		2017-07-13	IP		TK-45395 	fixed isSystemGenerated for generated records
** 3		2017-09-20	IP		TK-48127 	fixed taking only Timeclasses 1,2,20 (excepted 4)
** 4		2018-08-10	OV		B-19715 	added condition IsPR = 1 for jobcode
** 5		2018-09-20	OV		B-20797     fixed @isJobCodeIDColumnPresent value
** 6		2018-11-05	KF		D-06432		PR - YTD Labor Expense PR Metrics Do Not Match Payroll
** 7		2019-08-21	vfay	D-08586		PR Sampling Proc : removed filtering out 0 Value Rows
** 8		2020-12-09	HV		JAZZ-11135		Remove table variable in procPayrollSampledPayPeriodDetailedInsert
** 9		2020-12-21	HV 		JAZZ-10222	Proc procPayrollSampledPayPeriodDetailedInsert is timing out
** 10		2022-04-12	HV		JAZZ-35448	Remove PR Feature Flag
** 11		2023-10-18	KF		JAZZ-62485	Technical - Update procs to support 7 days pay periods for Pay Period and Daily
** 12		2024-01-29	KF		JAZZ-66821	Run PR Process Task: Some procs don't support non-consecutive pay period id (expect consecutive pay period id). It causes wrong YTD values & wrong Rolling Average Baseline Target values
** 13		2024-02-08	KF		JAZZ-67258	Current year runs of the Run PR Process Task have been failing.
*************************************************************/
CREATE PROC [fw].[procFactPayPeriodYTDPriorYearUpdate_Staging] 
	@factTableName nvarchar(100),
	@stagingTableName nvarchar(100),
	@keyNameCSV nvarchar(450),
	@measureNameCSV nvarchar(450),
	@fiscalYearID smallint = 0,
	@timeClassID tinyint = 0,
	@isDebugOnly bit = 0
as
set nocount on

	declare @sql nvarchar(max)
	declare @MaxYearForCalculation int= (select max(FiscalYearID) from int.FactStaffing)
	declare @PeriodsList nvarchar(max) = ''
	select @PeriodsList = @PeriodsList+',['+cast(PeriodNumber as varchar(3))+']' FROM (select distinct PeriodNumber from fw.DimPayPeriod where PeriodNumber <> 0 ) PN
	set @PeriodsList = SUBSTRING(@PeriodsList,2,LEN(@PeriodsList)-1)
	 declare @isJobCodeIDColumnPresent BIT
	 IF EXISTS (SELECT val from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') WHERE val = 'JobCodeID')
	   SET @isJobCodeIDColumnPresent = 1
	 ELSE
	   SET @isJobCodeIDColumnPresent = 0
	
		set @sql = '
		IF OBJECT_ID(''tempdb..' + @stagingTableName + 'Updated'') IS NOT NULL DROP TABLE ' + @stagingTableName + 'Updated
		create table ' + @stagingTableName + 'Updated (
		DepartmentID int,
		'+replace(@keyNameCSV, ',', ' int,')+' int, 
		PayPeriodID int, 
		TimeClassID int, 
		'+replace(@measureNameCSV, ',', ' decimal(18, 6),')+' decimal(18, 6),
		isDeleted bit default (0),
		isSystemGenerated bit default(0),
		PeriodNumber int,
		FiscalYearID int,
		PayCycleID int)

		insert INTO ' + @stagingTableName + 'Updated
		SELECT
		tp.DepartmentID,
		tp.' + replace(@keyNameCSV, ',', ', tp.') + ',
		tp.PayPeriodID,
		tp.TimeClassID,
		tp.' + replace(@measureNameCSV, ',', ', tp.') + ',
		tp.isDeleted, 
		tp.isSystemGenerated, 
		fm.PeriodNumber,
		fm.FiscalYearIDSecond,
		d.PayCycleID 
		FROM ' + @stagingTableName + ' tp 
		INNER JOIN fw.DimPayPeriod fm ON tp.PayPeriodID = fm.PayPeriodID  
		INNER JOIN fw.DimDepartment d ON tp.DepartmentID = d.DepartmentID
		
		IF OBJECT_ID(''tempdb..' + @stagingTableName + ''') IS NOT NULL DROP TABLE ' + @stagingTableName + '

		IF OBJECT_ID(''tempdb..#dimPayPeriod'') IS NOT NULL  DROP TABLE #dimPayPeriod
		CREATE TABLE #dimPayPeriod (PayPeriodID INT,FiscalYearID int, PeriodNumber TINYINT, PayCycleID int, UNIQUE CLUSTERED (PeriodNumber,FiscalYearID,PayCycleID))

		INSERT INTO #dimPayPeriod
		SELECT dpp.PayPeriodID, dpp.FiscalYearIDSecond, dpp.PeriodNumber, dpp.PayCycleID    
		FROM fw.DimPayPeriod dpp
		INNER JOIN pi.viewNextAfterCurrentPayPeriod npp on npp.PayCycleID = dpp.PayCycleID
		WHERE dpp.PayPeriodID <> 0 AND dpp.FiscalYearIDSecond <= npp.FiscalYearIDSecond
		ORDER BY dpp.PayCycleID, dpp.FiscalYearIDSecond, dpp.PeriodNumber

		IF OBJECT_ID(''tempdb..#MinSO'') IS NOT NULL DROP TABLE #MinSO
		CREATE TABLE #MinSO (
			'+replace(@keyNameCSV, ',', ' int,')+' int,
			DepartmentID int,
			FiscalYearID int,
			TimeClassID int,
			MinPeriodNumber int)
		INSERT INTO #MinSO('+@keyNameCSV+', DepartmentID, FiscalYearID, TimeClassID, MinPeriodNumber)'+(select case when @fiscalYearID > 0 THEN '
				SELECT '+replace(@keyNameCSV, ',', ',X.')+',
						X.DepartmentID,
						mm.FiscalYearID,
						X.TimeClassID,
						min(mm.PeriodNumber) as MinPeriodNumber
					FROM ' + @factTableName + ' X 
					INNER JOIN #dimPayPeriod mm
						ON mm.PayPeriodID = x.PayPeriodID
					WHERE FiscalYearID ='+cast(@fiscalYearID-1 as varchar(4))+'
					group by '+replace(@keyNameCSV, ',', ',X.')+',
						X.DepartmentID,
						mm.FiscalYearID,
						X.TimeClassID
				UNION
					SELECT '+replace(@keyNameCSV, ',', ',X.')+',
						X.DepartmentID,
						X.FiscalYearID,
						X.TimeClassID,
						min(X.PeriodNumber) as MinPeriodNumber
					FROM ' + @stagingTableName + 'Updated X 
					WHERE FiscalYearID ='+cast(@fiscalYearID as varchar(4))+'
					group by '+replace(@keyNameCSV, ',', ',X.')+',
						X.DepartmentID,
						X.FiscalYearID,
						X.TimeClassID

					' else '
					SELECT '+replace(@keyNameCSV, ',', ',X.')+',
						X.DepartmentID,
						X.FiscalYearID,
						X.TimeClassID,
						min(X.PeriodNumber) as MinPeriodNumber
					FROM ' + @stagingTableName + 'Updated X 
					group by '+replace(@keyNameCSV, ',', ',X.')+',
						X.DepartmentID,
						X.FiscalYearID,
						X.TimeClassID
					' end )+'
			IF OBJECT_ID(''tempdb..#MinPresent'') IS NOT NULL DROP TABLE #MinPresent'
			
			set @sql = @sql + '
			create table #MinPresent (
				'+replace(@keyNameCSV, ',', ' int,')+' int,
				DepartmentID int,
				FiscalYearID int,
				TimeClassID int,
				PayCycleID int,
				MinPeriodNumber int)
			INSERT INTO #MinPresent('+@keyNameCSV+', DepartmentID, FiscalYearID, TimeClassID, PayCycleID, MinPeriodNumber)
			SELECT '+replace(@keyNameCSV, ',', ',X.')+',
						X.DepartmentID,
						X.FiscalYearID,
						X.TimeClassID,
						dd.PayCycleID,
						min(X.MinPeriodNumber) as MinPeriodNumber
					FROM (SELECT '+replace(@keyNameCSV, ',', ',')+',
							DepartmentID,
							FiscalYearID,
							TimeClassID,
							MinPeriodNumber
						 FROM #MinSO 
						 UNION ALL
						 SELECT '+replace(@keyNameCSV, ',', ',')+',
							DepartmentID,
							FiscalYearID+1 as FiscalYearID,
							TimeClassID,
							MinPeriodNumber
						 FROM #MinSO 
						 ) X
						 inner join fw.DimDepartment dd on dd.DepartmentID = x.DepartmentID
						 where FiscalYearID <= (SELECT max(FiscalYearID)  FROM ' + @stagingTableName + 'Updated)
						 and TimeClassID in (1,2,20)
						 GROUP BY '+replace(@keyNameCSV, ',', ',')+',
								X.DepartmentID,
								X.FiscalYearID,
								X.TimeClassID,
								dd.PayCycleID
	
		IF OBJECT_ID(''tempdb..#MinSO'') IS NOT NULL DROP TABLE #MinSO
		IF OBJECT_ID(''tempdb..#MissingList'') IS NOT NULL DROP TABLE #MissingList
		CREATE TABLE #MissingList (
			'+replace(@keyNameCSV, ',', ' int,')+' int,
			DepartmentID int,
			FiscalYearID int,
			PayPeriodID int,
			TimeClassID int,
			PeriodNumber int)
		INSERT INTO #MissingList ('+@keyNameCSV+', DepartmentID, FiscalYearID, PayPeriodID, TimeClassID, PeriodNumber) 
			SELECT '+replace(@keyNameCSV, ',', ',')+',
				DepartmentID,
				Unpvt.FiscalYearID,
				mm.PayPeriodID,
				TimeClassID,
				unpvt.PeriodNumber
			FROM (
				SELECT '+replace(@keyNameCSV, ',', ',')+',
					DepartmentID,
					FiscalYearID,
					TimeClassID,
					PayCycleID,
					'+@PeriodsList+',
					MinPeriodNumber
				FROM (
				SELECT 
					isnull(TP.DepartmentID,MP.DepartmentID) as DepartmentID,
					' + (select dbo.straggr('isnull (TP.' + csv.val + ',MP.' + csv.val +') as ' + csv.val+',', ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
					isnull(TP.FiscalYearID,MP.FiscalYearID) as FiscalYearID,
					TP.PayPeriodID as PayPeriodID,
					isnull(TP.PayCycleID,MP.PayCycleID) as PayCycleID,
					isnull(TP.TimeClassID,MP.TimeClassID) as TimeClassID,
					0 as '+replace(@measureNameCSV, ',', ', 0 as ')+',
					0 as isDeleted,
					1 as isSystemGenerated,
					MP.MinPeriodNumber,
					isnull(TP.PeriodNumber,mp.MinPeriodNumber) as PeriodNumber
				FROM ' + @stagingTableName + 'Updated TP
				FULL join #MinPresent MP ON
					TP.DepartmentID = mp.DepartmentID
					' + (select dbo.straggr('AND TP.' + csv.val + ' = MP.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
					and TP.TimeClassID = mp.TimeClassID
					and TP.FiscalYearID = mp.FiscalYearID
				where (TP.PeriodNumber >= mp.MinPeriodNumber) or TP.PeriodNumber is null) ss /* there can be a subquery here*/
				PIVOT /*formation of the pivot table*/
					(count(PayPeriodID) /*is an aggregate function that forms the contents of a pivot table*/
					FOR PeriodNumber IN ('+@PeriodsList+'))  Pvt /* alias for the pivot table*/
			) X 
			UNPIVOT (isPresent /* the header of the column that will contain the values
			 from the columns of the source table listed below*/
			FOR PeriodNumber IN ('+@PeriodsList+')) Unpvt
			INNER JOIN  #dimPayPeriod mm
				ON mm.PeriodNumber = Unpvt.PeriodNumber 
				and mm.FiscalYearID = Unpvt.FiscalYearID 
				and mm.PayCycleID = unpvt.PayCycleID
			WHERE isPresent = 0 and Unpvt.PeriodNumber >= MinPeriodNumber

			IF OBJECT_ID(''tempdb..#MinPresent'') IS NOT NULL DROP TABLE #MinPresent	
			IF OBJECT_ID(''tempdb..#calculatedMeasures'') IS NOT NULL DROP TABLE #calculatedMeasures
			CREATE TABLE #calculatedMeasures (
				DepartmentID int,
				'+replace(@keyNameCSV, ',', ' int,')+' int,
				FiscalYearID int,
				PayPeriodID int,
				PayCycleID int,
				TimeClassID int, 
				PeriodNumber int, 
				'+replace(@measureNameCSV, ',', 'YTD decimal(18, 6),')+'YTD decimal(18, 6),
				'+replace(@measureNameCSV, ',', ' decimal(18, 6),')+' decimal(18, 6),
				isSystemGenerated int)

			insert into #calculatedMeasures(DepartmentID, '+@keyNameCSV+', FiscalYearID, PayPeriodID, PayCycleID, TimeClassID, PeriodNumber, ' + replace(@measureNameCSV, ',', 'YTD,') + 'YTD, ' + @measureNameCSV + ', isSystemGenerated)
			select
				uoag.DepartmentID,
				uoag.' + replace(@keyNameCSV, ',', ', uoag.') + ',
				uoag.FiscalYearID,
				uoag.PayPeriodID,
				pp.PayCycleID,
				uoag.TimeClassID,
				pp.PeriodNumber,
				' + (select dbo.straggr('SUM(uoag.' + csv.val + ') OVER (PARTITION BY uoag.DepartmentID,' + @keyNameCSV + ',TimeClassID,FiscalYearID,pp.PayCycleID ORDER BY pp.PeriodNumber) AS ' + csv.val + 'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
				' + @measureNameCSV + ',
				uoag.isSystemGenerated
			from
				(
						SELECT 
				ML.DepartmentID,
				ML.' + replace(@keyNameCSV, ',', ', ML.') + ',
				ML.FiscalYearID,
				ML.PayPeriodID,
				ML.TimeClassID,
				0 as '+replace(@measureNameCSV, ',', ', 0 as ')+',
				1 as isSystemGenerated
			FROM #MissingList ML ' + case when @fiscalYearID > 0 then ' where ML.FiscalYearID = ' + cast(@fiscalYearID as nvarchar(4)) else '' end +'
			UNION 
			SELECT data.DepartmentID,
				data.' + replace(@keyNameCSV, ',', ', data.') + ',
				data.FiscalYearID,
				data.PayPeriodID,
				data.TimeClassID,
				' + @measureNameCSV + ',
				data.isSystemGenerated
				from ' + @stagingTableName + 'Updated data
			where
				(1 = 1)
				' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + '' + case when @fiscalYearID > 0 then '
			UNION 
			SELECT data.DepartmentID,
				data.' + replace(@keyNameCSV, ',', ', data.') + ',
				mm.FiscalYearID,
				data.PayPeriodID,
				data.TimeClassID,
				' + @measureNameCSV + ',
				1 as isSystemGenerated
				from ' + @factTableName + ' data
				INNER JOIN #dimPayPeriod mm
						ON mm.PayPeriodID = data.PayPeriodID
			where mm.FiscalYearID = ' + cast(@fiscalYearID-1 as nvarchar(4)) + case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else ' and TimeClassID in (1,2,20) ' end
		else '' end + '

			) uoag /* union ald and generated*/
			inner join fw.dimPayPeriod pp on uoag.PayPeriodID = pp.PayPeriodID'
			
			set @sql = @sql + '	
			IF OBJECT_ID(''tempdb..#MissingList'') IS NOT NULL DROP TABLE #MissingList

			SELECT 
				PreSelect.*,
				FTEs=cast(0 as decimal(19, 4)),
				FTEsYTD=cast(0 as decimal(19, 4)),
				FTEsPriorYear=cast(0 as decimal(19, 4)),
				FTEsPriorYTD=cast(0 as decimal(19, 4))
			INTO fw.' + replace(@stagingTableName,'#','') + 'WithCalcs
			FROM (
			SELECT 
				cm.DepartmentID,
				cm.' + replace(@keyNameCSV, ',', ',cm.') + ',
				cm.FiscalYearID,
				cm.PayPeriodID,
				cm.TimeClassID,
			' + (select dbo.straggr('isnull(cm.' + csv.val+',0) as '+ csv.val+',', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) +'
			' + (select dbo.straggr('isnull(cm.' + csv.val+'YTD,0) as '+csv.val+'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
			' + (select dbo.straggr('isnull(cm_py.' + csv.val + ',0) as '+ csv.val+'PriorYear,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
			' + (select dbo.straggr('isnull(cm_py.' + csv.val + 'YTD,0) as ' + csv.val + 'PriorYTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
				isnull(cm.isSystemGenerated,0) as isSystemGenerated
			from #calculatedMeasures cm
			LEFT JOIN #calculatedMeasures cm_py ON
							cm.DepartmentID = cm_py.DepartmentID 
							' + (select dbo.straggr('AND cm.' + csv.val + ' = cm_py.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + '
							AND cm.PeriodNumber = cm_py.PeriodNumber
							AND cm.PayCycleID = cm_py.PayCycleID
							AND cm.TimeClassID = cm_py.TimeClassID
							and cm.FiscalYearID = cm_py.FiscalYearID+1
			' + case when @fiscalYearID > 0 then ' WHERE cm.FiscalYearId = '+cast(@fiscalYearID as varchar(4)) else '' end+'
			) PreSelect

		'+ case when @isJobCodeIDColumnPresent =1  then 'inner join fw.DimJobCode jc on jc.JobCodeID = PreSelect.JobCodeID and jc.IsPR = 1 ' else '' end + '
	
			
			WHERE NOT(' + (select dbo.straggr(csv.val+'= 0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) +'
			and ' + (select dbo.straggr(csv.val + 'YTD = 0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
			and ' + (select dbo.straggr(csv.val + 'PriorYear = 0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
			and ' + (select dbo.straggr(csv.val + 'PriorYTD = 0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + '
			and isSystemGenerated = 1)
	
		IF OBJECT_ID(''tempdb..' + @stagingTableName + 'Updated'') IS NOT NULL DROP TABLE ' + @stagingTableName + 'Updated
		IF OBJECT_ID(''tempdb..#dimPayPeriod'') IS NOT NULL  DROP TABLE #dimPayPeriod
		IF OBJECT_ID(''tempdb..#calculatedMeasures'') IS NOT NULL  DROP TABLE #calculatedMeasures
		'

	if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end

	--delete zero records, possible only if YTD aggregates to zero due to negative values
GO


---------------------------------------------

-- fw.procFactPayrollSampledBaselineTargetUpdate
/**************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI			Description
** 1		2017-03-06	gforeman	B-14693		Added year filter
** 2		2017-03-28	ipetriv		D-05641		Logic for Prior and Actual was changed to simply copy actuals from previous year
** 3		2017-04-05 	ipetriv		D-05789		Changed algorithm for rolling average calculation
** 4		2018-05-16	IP			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 5		2018-05-24	KF			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 6		2018-06-05	IP 			TK-58643 added filetr for current year only and non-zero records in output
** 7		2024-06-14  SM      	JAZZ-71536  change JobCodeID from smallint to int
*************************************************************/
CREATE proc [fw].[procFactPayrollSampledBaselineTargetUpdate]
    @targetType int = null,
    @numberOfMonths int = null,
	@fiscalYearID int = 0
with recompile
as
	if (@targetType is null) set @targetType = (select Value from mr.SystemSetting where Name = 'Target Basis')
	if (@numberOfMonths is null) set @numberOfMonths = (select Value from mr.SystemSetting where Name = 'Number Of Rolling Average Months')
	declare @sql varchar(max)
	create table #temp
	(
		DepartmentID int,
		JobCodeID int,
		PayCodeID smallint,
		PayCodeGroupID int,
		FiscalYearID smallint,
		FiscalMonthID tinyint,
		Hours decimal (18, 6),
		Dollars decimal (18, 6),
		FTEs decimal (18, 6)
	)

	create table #YearsScope (FiscalYearID int)
	
	IF @fiscalYearID <> 0
		INSERT INTO #YearsScope (FiscalYearID)
		select distinct FiscalYearID from fw.dimFiscalYear dm where dm.FiscalYearID in (@fiscalYearID-1,@fiscalYearID,@fiscalYearID+1)
		UNION
		SELECT @fiscalYearID+1 as FiscalYearID
	ELSE 
		INSERT INTO #YearsScope (FiscalYearID)
		select distinct FiscalYearID from fw.dimFiscalYear dm where FiscalYearID between (select min(FiscalYearID) FROM fw.FactPayrollSampledMonthly) and (select max(FiscalYearID)+1 FROM fw.FactPayrollSampledMonthly)	

	if (@targetType = 1) begin --Prior Year Actual
		insert into #temp
		select d.DepartmentID, d.JobCodeID, d.PayCodeID, d.PayCodeGroupID, d.FiscalYearID+1, d.FiscalMonthID, d.Hours, d.Dollars, d.FTEs
		FROM fw.FactPayrollSampledMonthly d WHERE d.TimeClassID = 1 and (@fiscalYearID = 0 or d.FiscalYearID = @fiscalYearID-1)
	end else if (@targetType = 10) begin --Rolling Average
		set @sql = '
		insert into #temp (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID,Dollars,Hours,FTEs)
		select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, isnull(Dollars,0.0), isnull(Hours,0.0),0 FROM (
		select FullScope.DepartmentID, FullScope.JobCodeID, FullScope.PayCodeID, FullScope.PayCodeGroupID, FullScope.FiscalYearID, m.FiscalMonthID,
		Dollars = ISNULL((Sum(Dollars) over(PARTITION BY DepartmentID,JobCodeID,PayCodeID,PayCodeGroupID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfMonths as nvarchar(2))+', 0),
		Hours	= ISNULL((Sum(Hours)   over(PARTITION BY DepartmentID,JobCodeID,PayCodeID,PayCodeGroupID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfMonths as nvarchar(2))+', 0)
		FROM (
			select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/
					JobCodeID,
					PayCodeID,
					PayCodeGroupID,
					FiscalYearID,
					SortOrder,
					SUM(Hours) as Hours,
					SUM(Dollars) as Dollars 
			FROM  (
				SELECT /*recods for months which are present in current year*/
						DepartmentID,
						JobCodeID,
						PayCodeID,
						PayCodeGroupID,
						FiscalYearID,
						m.SortOrder,
						Hours,
						Dollars
					FROM fw.FactPayrollSampledMonthly p
					JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
					where m.FiscalMonthID <> 0  and p.TimeClassID = 1 and p.isSystemGenerated = 0
					' + case when @fiscalYearID <> 0 then ' and FiscalYearID in ('+cast(@fiscalYearID-1 as nvarchar(4))+','+cast(@fiscalYearID as nvarchar(4))+')' else '' end +'
				UNION ALL
				SELECT /*combination of all for key columns months for (year-1). If some combination was in previous year - same should be in current, to receive baseline value*/
						p.DepartmentID,
						p.JobCodeID,
						p.PayCodeID,
						p.PayCodeGroupID,
						fy.FiscalYearID,
						m.SortOrder,
						0 as Hours,
						0 as Dollars
				FROM fw.FactPayrollSampledMonthly p
				CROSS JOIN fw.DimFiscalMonth m
				CROSS JOIN #YearsScope fy
				WHERE m.FiscalMonthID <> 0 and p.TimeClassID = 1  and p.IsSystemGenerated = 0
				' + case when @fiscalYearID <> 0 then ' and p.FiscalYearID in ('+cast(@fiscalYearID-1 as nvarchar(4))+','+cast(@fiscalYearID as nvarchar(4))+')' else '' end +'
				) AllCombinations
				GROUP BY DepartmentID,JobCodeID,PayCodeID,PayCodeGroupID,FiscalYearID,SortOrder
	) FullScope
	JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder
	) FinalDataset
	WHERE	(Dollars is not null 
		 or Hours is not null)
	' + case when @fiscalYearID <> 0 then ' and FiscalYearID = '+cast(@fiscalYearID as nvarchar(4)) else '' end
	print @sql
	exec (@sql)
	end else begin --Budget
		insert into #temp
		select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, Hours, Dollars, FTEs
		from fw.FactPayrollSampledMonthly
		where TimeClassID = 2 and (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID)
	end
    
	merge
		fw.FactPayrollSampledMonthly as fact
	using 
		(select * from #temp where (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID) and not (Hours = 0 and Dollars = 0)) as source
	on
		fact.DepartmentID = source.DepartmentID and fact.JobCodeID = source.JobCodeID and fact.PayCodeID = source.PayCodeID and fact.PayCodeGroupID = source.PayCodeGroupID and fact.FiscalYearID = source.FiscalYearID and
		fact.FiscalMonthID = source.FiscalMonthID and fact.TimeClassID = 20 and (@fiscalYearID = 0 or fact.FiscalYearID = @fiscalYearID)
	when not matched by target then
		insert (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, TimeClassID, Hours, Dollars, FTEs) values
		(source.DepartmentID, source.JobCodeID, source.PayCodeID, source.PayCodeGroupID, source.FiscalYearID, source.FiscalMonthID, 20, source.Hours, source.Dollars, source.FTEs)    
	when not matched by source and fact.TimeClassID = 20 and (@fiscalYearID = 0 or fact.FiscalYearID = @fiscalYearID) then
		update set fact.IsDeleted = 1
	when matched then
		update set fact.Hours = source.Hours, fact.Dollars = source.Dollars, fact.FTEs = source.FTEs, fact.IsSystemGenerated = 0;

	exec [dbo].[procRollingDeleteOnTable] 'fw', 'FactPayrollSampledMonthly', 'RowID', 'fw.FactPayrollSampledMonthly', 'TimeClassID = 20 and IsDeleted = 1', 10000, 0.5, 0

	drop table #temp
	drop table #YearsScope;
GO


---------------------------------------------

-- fw.procFactPayrollSampledDailyFTEsInsert
CREATE PROCEDURE [fw].[procFactPayrollSampledDailyFTEsInsert] 
  @departmentIDs NVARCHAR(max) = NULL,
  @fiscalYearID INT = 0,
  @onePayPeriodOnlyDate datetime = null,
  @timeClassID INT = 4
AS

/*
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2022-08-16	ishah	JAZZ-41955	Daily Flexing - Calculating Payroll FTEs
************************************************************
*/

IF OBJECT_ID('tempdb..#departments') IS NOT NULL DROP TABLE #departments
SELECT val INTO #departments
FROM ConvertCSValuesToTable(@departmentIDs, ',')

IF OBJECT_ID('tempdb..#WorkWeekHours') IS NOT NULL DROP TABLE #WorkWeekHours
SELECT DeptJobCode.DepartmentID,
	DeptJobCode.JobCodeID,
	WorkingHoursCoef = cast(dww.Hours AS NUMERIC(20, 6)) / 7
INTO #WorkWeekHours
FROM (
	SELECT DepartmentID,
		JobCodeID,
		WorkWeekID = COALESCE(jc.WorkWeekID, de.WorkWeekID, - 1)
	FROM (
		SELECT dp.DepartmentID,
			WorkWeekID = CASE 
				WHEN e.WorkWeekID > - 1 THEN e.WorkWeekID 
				ELSE NULL
				END
		FROM fw.DimEntity e
		INNER JOIN fw.DimDepartment dp on e.EntityID = dp.EntityID
		) DE
	CROSS JOIN (
		SELECT djc.JobCodeID,
			djcg.JobCodeGroupID,
			WorkWeekID = CASE 
				WHEN djc.WorkWeekOverrideID > - 1 THEN djc.WorkWeekOverrideID
				WHEN djc.WorkWeekOverrideID = - 1 AND djcg.WorkWeekOverrideID > - 1
				THEN djcg.WorkWeekOverrideID ELSE NULL
				END
		FROM fw.DimJobCode djc
		INNER JOIN fw.DimJobCodeGroup djcg ON djc.JobCodeGroupID = djcg.JobCodeGroupID
		WHERE djc.IsDaily = 1 and djc.IsPR = 1
		) JC
	) DeptJobCode
LEFT JOIN fw.DimWorkWeek dww ON DeptJobCode.WorkWeekID = dww.WorkWeekID

DECLARE @BatchSize INT = 100000000

IF OBJECT_ID('tempdb..#inputPayPeriods') IS NOT NULL DROP TABLE #inputPayPeriods
	
-- Added support for one pay period only 
SELECT fp.PayPeriodID, pp.WorkingDays as WorkingDays, pp.PeriodDays as PeriodDays, COUNT(*) AS RecordsCount, 0 AS BatchID INTO #inputPayPeriods
FROM fw.FactPayrollSampledDaily fp 
INNER JOIN fw.DimPayPeriod pp ON fp.PayPeriodID = pp.PayPeriodID
WHERE fp.TimeClassID = @timeClassID AND pp.PeriodNumber != 0 AND
((@onePayPeriodOnlyDate IS NOT NULL AND @onePayPeriodOnlyDate BETWEEN pp.PeriodStartCalendarDate AND pp.PeriodEndCalendarDate)
OR 
(@onePayPeriodOnlyDate IS NULL AND (pp.FiscalYearIDSecond = @fiscalYearID OR @fiscalYearID = 0)))
GROUP BY fp.PayPeriodID, pp.WorkingDays, pp.PeriodDays

-- Split data into batches
WHILE EXISTS (SELECT TOP 1 1 FROM #inputPayPeriods WHERE BatchID = 0)
BEGIN
	;WITH PayPeriodInfo AS 
	(
		SELECT IPP.PayPeriodID, ROW_NUMBER() OVER (ORDER BY IPP.PayPeriodID) AS RowNumber, SUM(RecordsCount) OVER (ORDER BY IPP.PayPeriodID) AS Total, MaxBatchID+1 AS BatchID
		FROM #inputPayPeriods IPP
		CROSS JOIN (SELECT MAX(BatchID) AS MaxBatchID FROM #inputPayPeriods) M
		WHERE IPP.BatchID = 0
	)
	UPDATE IPP
	SET IPP.BatchID = MI.BatchID
	FROM #inputPayPeriods IPP
	INNER JOIN PayPeriodInfo MI ON MI.PayPeriodID = IPP.PayPeriodID
	WHERE Total <= @BatchSize OR RowNumber = 1
END

DECLARE @BatchID INT, @MaxBatchID INT
SELECT @MaxBatchID = MAX(BatchID) FROM #inputPayPeriods

-- Loop thru batches and insert data
SET @BatchID = 1
WHILE @BatchID <= @MaxBatchID
BEGIN
	UPDATE fact
	SET fact.FTEs = CASE 
			WHEN WorkingHoursCoef IS NOT NULL
				THEN (fact.Hours) / WorkingHoursCoef
			ELSE fact.Hours / (IPP.WorkingDays * 8.0 / IPP.PeriodDays)
			END
	FROM fw.FactPayrollSampledDaily fact
	INNER JOIN #inputPayPeriods IPP ON IPP.PayPeriodID = fact.PayPeriodID and IPP.BatchID = @BatchID
	INNER JOIN fw.viewDimPayCodeGroup pcg ON fact.PayCodeGroupID = pcg.PayCodeGroupID
	INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID
		AND fact.JobCodeID = ww.JobCodeID
	WHERE pcg.ProductiveClass IN ( 'Productive', 'Non-Productive' )
		AND fact.TimeClassID = @timeClassID
		AND (
			@departmentIDs IS NULL
			OR fact.DepartmentID IN (
				SELECT val 
				FROM #departments
				)
			)
	SET @BatchID = @BatchID + 1
END
GO


---------------------------------------------

-- fw.procFactPayrollSampledDetailedBaselineTargetUpdate
/**************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI			Description
** 1		2017-03-06	gforeman	B-14693		Added year filter
** 2		2017-03-28	IPetriv		D-05641		Logic for Prior and Actual was changed to simply copy actuals from previous year
** 3		2017-04-11	IPetriv		B-15086		Sampling Performance Improvements. Using temp tables insead of fw.FactPayrollSampledMonthlyDetailed. Update fw.FactPayrollSampledMonthlyDetailed only once by the final dataset.
** 4		2017-06-15	IP			B-15086 	Modify SP to use unique temp table
** 5		2018-05-16	IP			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 6		2018-05-24	KF			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 7		2018-06-01	IP 			D-07006	Rolling Average method for metric target calculation doesn't include months with 0 values (one year part)
** 8		2018-06-05	IP 			TK-58643 added filetr for current year only and non-zero records in output
** 9		2024-06-14  SM      	JAZZ-71536  change JobCodeID from smallint to int
*************************************************************/
CREATE proc [fw].[procFactPayrollSampledDetailedBaselineTargetUpdate]
    @targetType int = null,
    @numberOfMonths int = null,
	@fiscalYearID int = 0
as
	if (@targetType is null) set @targetType = (select Value from mr.SystemSetting where Name = 'Target Basis')
	if (@numberOfMonths is null) set @numberOfMonths = (select Value from mr.SystemSetting where Name = 'Number Of Rolling Average Months')
	declare @maxCalculatingFiscalYear int = (select max(FiscalYearID) from #PayrollSampledMonthlyDetailedStaging)

	create table #temp
	(
		DepartmentID int,
		JobCodeID int,
		PayCodeID smallint,
		PayCodeGroupID int,
		EmployeeID int,
		FiscalYearID smallint,
		FiscalMonthID tinyint,
		Hours decimal (19, 4),
		Dollars decimal (19, 4),
		FTEs decimal (19, 4)
	)

	if (@targetType = 1) begin --Prior Year Actual
	if (@fiscalYearID = 0)
		insert into #temp
		select d.DepartmentID, d.JobCodeID, d.PayCodeID, d.PayCodeGroupID, d.EmployeeID, d.FiscalYearID+1, d.FiscalMonthID, d.Hours, d.Dollars, d.FTEs
		from #PayrollSampledMonthlyDetailedStaging d 
		where d.TimeClassID = 1
	else 
		insert into #temp
		select d.DepartmentID, d.JobCodeID, d.PayCodeID, d.PayCodeGroupID, d.EmployeeID, d.FiscalYearID+1, d.FiscalMonthID, d.Hours, d.Dollars, d.FTEs
		from fw.FactPayrollSampledMonthlyDetailed d 
		where (d.FiscalYearID = @fiscalYearID-1) and d.TimeClassID = 1
	end else if (@targetType = 10) begin --Rolling Average
	declare @sql nvarchar(max)
	if @fiscalYearID = 0
	set @sql = '
		insert into #temp (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, FiscalYearID, FiscalMonthID,Hours,Dollars)
		select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, FiscalYearID, FiscalMonthID,isnull(Hours,0.0),isnull(Dollars,0.0) FROM (
		select FullScope.DepartmentID, FullScope.JobCodeID, FullScope.PayCodeID, FullScope.PayCodeGroupID, FullScope.EmployeeID, FullScope.FiscalYearID, m.FiscalMonthID,
		Dollars = ISNULL((Sum(Dollars) over(PARTITION BY DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0),
		Hours	= ISNULL((Sum(Hours)   over(PARTITION BY DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0)
		FROM (
			select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/
					JobCodeID,
					EmployeeID,
					PayCodeID,
					PayCodeGroupID,
					FiscalYearID,
					SortOrder,
					SUM(Hours) as Hours,
					SUM(Dollars) as Dollars 
			FROM  (
				SELECT /*recods for months which are present in current year*/
						DepartmentID,
						JobCodeID,
						EmployeeID,
						PayCodeID,
						PayCodeGroupID,
						FiscalYearID,
						m.SortOrder,
						Hours,
						Dollars
					FROM #PayrollSampledMonthlyDetailedStaging p
					JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
					where m.FiscalMonthID <> 0   and isnull(p.IsSystemGenerated,0) = 0 and p.TimeClassID = 1
				UNION ALL
					SELECT /*combination of all for key columns months for (year-1). If some combination was in previous year - same should be in current, to receive baseline value*/
						p.DepartmentID,
						p.JobCodeID,
						p.EmployeeID,
						p.PayCodeID,
						p.PayCodeGroupID,
						fy.FiscalYearID,
						fy.SortOrder,
						0 AS Hours,
						0 AS Dollars
					FROM #PayrollSampledMonthlyDetailedStaging p
					INNER JOIN fw.DimFiscalMonth m on m.FiscalMonthID = p.FiscalMonthID
					INNER JOIN (select FiscalYearID,FiscalMonthID,fm.sortOrder,fy.FiscalYearID*12+fm.SortOrder as ChronologicalOrder from fw.DimFiscalYear fy
								full join fw.DimFiscalMonth fm on 1= 1 
								where FiscalMonthID  <> 0 and FiscalYearID <> 0) fy ON ChronologicalOrder - (p.FiscalYearID*12+m.SortOrder) between 1 and '+cast(@numberOfMonths as nvarchar(2))+'
					WHERE p.TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0
				) AllCombinations
				GROUP BY DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID,FiscalYearID,SortOrder
	) FullScope
	JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder
	) FinalDataset
	WHERE	Dollars is not null 
		 or Hours is not null'
	else 
	set @sql  = '
		insert into #temp (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, FiscalYearID, FiscalMonthID,Hours,Dollars)
		select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, FiscalYearID, FiscalMonthID,isnull(Hours,0.0),isnull(Dollars,0.0) FROM (
		select FullScope.DepartmentID, FullScope.JobCodeID, FullScope.PayCodeID, FullScope.PayCodeGroupID, FullScope.EmployeeID, FullScope.FiscalYearID, m.FiscalMonthID,
		Dollars = ISNULL((Sum(Dollars) over(PARTITION BY DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0),
		Hours	= ISNULL((Sum(Hours)   over(PARTITION BY DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0)
		FROM (
			select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/
					JobCodeID,
					EmployeeID,
					PayCodeID,
					PayCodeGroupID,
					FiscalYearID,
					SortOrder,
					SUM(Hours) as Hours,
					SUM(Dollars) as Dollars 
			FROM  (
				SELECT /*recods for months which are present in current year*/
						DepartmentID,
						JobCodeID,
						EmployeeID,
						PayCodeID,
						PayCodeGroupID,
						FiscalYearID,
						m.SortOrder,
						Hours,
						Dollars
					FROM #PayrollSampledMonthlyDetailedStaging p
					JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
					where m.FiscalMonthID <> 0  and isnull(p.IsSystemGenerated,0) = 0  and p.TimeClassID = 1
				UNION ALL 
				SELECT /*recods for months which are present in current year*/
						DepartmentID,
						JobCodeID,
						EmployeeID,
						PayCodeID,
						PayCodeGroupID,
						FiscalYearID,
						m.SortOrder,
						Hours,
						Dollars
				FROM fw.FactPayrollSampledMonthlyDetailed p
				JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
				where m.FiscalMonthID <> 0  and isnull(p.IsSystemGenerated,0) = 0  and p.TimeClassID = 1 and p.FiscalYearID = '+cast(@fiscalYearID-1 as nvarchar(4))+'
				UNION ALL
				SELECT /*combination of all for key columns months for current year*/
						DepartmentID,
						JobCodeID,
						EmployeeID,
						PayCodeID,
						PayCodeGroupID,
						FiscalYearID,
						m.SortOrder,
						0 AS Hours,
						0 AS Dollars
				FROM #PayrollSampledMonthlyDetailedStaging p
				CROSS APPLY fw.DimFiscalMonth m
				where m.FiscalMonthID <> 0  and isnull(p.IsSystemGenerated,0) = 0 and p.TimeClassID = 1
				UNION ALL
				SELECT /*combination of all for key columns months for (year-1). If some combination was in previous year - same should be in current, to receive baseline value*/
						p.DepartmentID,
						p.JobCodeID,
						p.EmployeeID,
						p.PayCodeID,
						p.PayCodeGroupID,
						fy.FiscalYearID,
						m.SortOrder,
						0 AS Hours,
						0 AS Dollars
					FROM fw.FactPayrollSampledMonthlyDetailed p
					CROSS JOIN fw.DimFiscalMonth m
					CROSS JOIN (select distinct FiscalYearID from int.FactStaffing dm where dm.FiscalYearID in ('+cast(@fiscalYearID-1 as nvarchar(4))+','+cast(@fiscalYearID as nvarchar(4))+')) fy
					WHERE m.FiscalMonthID <> 0 and p.TimeClassID = 1    and isnull(p.IsSystemGenerated,0) = 0 and p.TimeClassID <> 20 and p.FiscalYearID = '+cast(@fiscalYearID-1 as nvarchar(4))+'
				) AllCombinations
				GROUP BY DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID,FiscalYearID,SortOrder
	) FullScope
	JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder
	) FinalDataset
	WHERE	Dollars is not null 
		 or Hours is not null'
	print @sql
	exec (@sql)
	end else begin --Budget
		insert into #temp
		select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, FiscalYearID, FiscalMonthID, Hours, Dollars, FTEs
		from #PayrollSampledMonthlyDetailedStaging
		where TimeClassID = 2
	end
    
	delete from #PayrollSampledMonthlyDetailedStaging where TimeClassID = 20 and (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID)
	insert into #PayrollSampledMonthlyDetailedStaging(DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, FiscalYearID, FiscalMonthID, TimeClassID, Hours, Dollars, FTEs)
	select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, FiscalYearID, FiscalMonthID, 20, Hours, Dollars, FTEs from #temp
	where (FiscalYearID = @fiscalYearID or @fiscalYearID = 0) and not (Hours =0 and Dollars = 0)
	
	drop table #temp;
GO


---------------------------------------------

-- fw.procFactPayrollSampledMonthlyUpdateFTEs
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1        2019-10-21  KF      D-08819     FTE Baseline Calculation Issue
** 2        2020-09-03  KF      JAZZ-4280   FTEs YTD logic for Rolling Methodology incorrectly calculating
** 3        2020-02-18  HV      JAZZ-15496  Bug - Run Management Reporting Monthly Process is failed due to "Divide by zero error encountered..." error
** 4        2021-06-08  KF      JAZZ-21092  Monthly FTE Factor for Rolling Average
** 5        2021-09-14  KF      JAZZ-26273  Update Monthly FTE YTD Factor for Rolling Average
** 6        2024-04-23  HV      JAZZ-68507  Inconsistencies in MR conversion factor used across TimeClasses
*************************************************************/
CREATE PROCEDURE [fw].[procFactPayrollSampledMonthlyUpdateFTEs]
@fiscalYearID SMALLINT = 0,
@timeClassID TINYINT = 20
AS

DECLARE @targetType int = (select Value from mr.SystemSetting where Name = 'Target Basis')
IF(@targetType = 10) --Rolling Average
    BEGIN
        CREATE TABLE #workingHours (FiscalYearID smallint, FiscalMonthID tinyint, WorkWeekID INT,
		    WorkingHours Decimal(19,4), WorkingHoursYTD Decimal(38,4),
		    RollingWorkingHours Decimal(19,4), RollingWorkingHoursYTD Decimal(38,4))
	
        DECLARE @useCurrentMonthFTEFactor bit = (SELECT Value FROM mr.SystemSetting WHERE Name = 'Use The Current Month FTE Factor Instead Of The Rolling Average')
        DECLARE @numberOfMonths INT = (select Value from mr.SystemSetting where Name = 'Number Of Rolling Average Months')
        DECLARE @sql nvarchar(max)		

        SET @sql = '
            INSERT INTO #workingHours (FiscalYearID, FiscalMonthID, WorkWeekID, WorkingHours, WorkingHoursYTD, RollingWorkingHours, RollingWorkingHoursYTD)
            SELECT FiscalYearID, FiscalMonthID, WorkWeekID, WorkingHours, WorkingHoursYTD, RollingWorkingHours,
                    COALESCE((Sum(RollingWorkingHours) over(PARTITION BY WorkWeekID, FiscalYearID ORDER BY SortOrder)), 0) AS RollingWorkingHoursYTD
                FROM (
                    SELECT FY.FiscalYearID, FM.FiscalMonthID, wpmCY.WorkWeekID, FM.SortOrder, wpmCY.Hours AS WorkingHours, wpmCY.YTDHours AS WorkingHoursYTD,
					    COALESCE((Sum(wpmCY.Hours) over(PARTITION BY wpmCY.WorkWeekID ORDER BY FY.FiscalYearID*12+FM.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfMonths as nvarchar(2))+', 0) AS RollingWorkingHours
                    FROM [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY
                    INNER JOIN fw.DimFiscalMonth FM ON FM.FiscalMonthID = wpmCY.FiscalMonthID
                    INNER JOIN fw.DimFiscalYear FY ON FY.FiscalYearID = wpmCY.FiscalYearID
                ) S
                '		
        exec (@sql)

        IF(@useCurrentMonthFTEFactor = 1 AND @timeClassID IN (4, 20, 22))
        BEGIN
          UPDATE fact
            SET
                fact.FTEs= CASE WHEN wpmCY.WorkingHours = 0 THEN 0 ELSE fact.Hours/wpmCY.WorkingHours END,
                fact.FTEsYTD= CASE WHEN wpmCY.WorkingHoursYTD = 0 THEN 0 ELSE fact.HoursYTD/wpmCY.WorkingHoursYTD END,
                fact.FTEsPriorYear = CASE WHEN COALESCE(wpmPY.WorkingHours, 0) = 0 THEN 0 ELSE fact.HoursPriorYear / wpmPY.WorkingHours END,
                fact.FTEsPriorYTD = CASE WHEN COALESCE(wpmPY.WorkingHoursYTD, 0) = 0 THEN 0 ELSE fact.HoursPriorYTD / wpmPY.WorkingHoursYTD END
            FROM
            (
                SELECT fact.*,
                    CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID
                            WHEN jc.WorkWeekOverrideID = -1 AND jcg.WorkWeekOverrideID != -1 THEN jcg.WorkWeekOverrideID
                            WHEN jc.WorkWeekOverrideID = -1 and jcg.WorkWeekOverrideID =- 1 THEN D.WorkWeekID
                    END AS WorkWeekID
                FROM fw.FactPayrollSampledMonthly fact
                inner join fw.DimDepartment D on fact.DepartmentID= D.DepartmentID
                inner join fw.DimJobCode JC on fact.JobCodeID= JC.JobCodeID
                inner join fw.DimJobCodeGroup JCG on JC.jobCodeGroupID = JCG.JobCodeGroupID
                inner join fw.DimPayCodeGroup PCG on fact.PayCodeGroupID = PCG.PayCodeGroupID
                WHERE PCG.ProductiveClassID in ('3','2')	--Productive and Non-Productive
                    and (fact.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0)
                    and fact.TimeClassID = @timeClassID
            ) fact
            inner join #workingHours wpmCY on fact.FiscalMonthID= wpmCY.FiscalMonthID and fact.FiscalYearID= wpmCY.FiscalYearID and wpmCY.WorkWeekID= fact.WorkWeekID
            left join #workingHours wpmPY on fact.FiscalMonthID= wpmPY.FiscalMonthID and (fact.FiscalYearID-1)=wpmPY.FiscalYearID and wpmPY.WorkWeekID=fact.WorkWeekID
        END
        ELSE BEGIN
          UPDATE fact
            SET
                fact.FTEs= CASE WHEN wpmCY.RollingWorkingHours = 0 THEN 0 ELSE fact.Hours/wpmCY.RollingWorkingHours END,
                fact.FTEsYTD= CASE WHEN wpmCY.RollingWorkingHoursYTD = 0 THEN 0 ELSE fact.HoursYTD/wpmCY.RollingWorkingHoursYTD END,
                fact.FTEsPriorYear = CASE WHEN COALESCE(wpmPY.RollingWorkingHours, 0) = 0 THEN 0 ELSE fact.HoursPriorYear / wpmPY.RollingWorkingHours END,
                fact.FTEsPriorYTD = CASE WHEN COALESCE(wpmPY.RollingWorkingHoursYTD, 0) = 0 THEN 0 ELSE fact.HoursPriorYTD / (wpmPY.RollingWorkingHoursYTD) END
            FROM
            (
                  SELECT fact.*,
                      CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID
                           WHEN jc.WorkWeekOverrideID = -1 AND jcg.WorkWeekOverrideID != -1 THEN jcg.WorkWeekOverrideID
                           WHEN jc.WorkWeekOverrideID = -1 and jcg.WorkWeekOverrideID =- 1 THEN D.WorkWeekID
                      END AS WorkWeekID
                  FROM fw.FactPayrollSampledMonthly fact
                  inner join fw.DimDepartment D on fact.DepartmentID= D.DepartmentID
                  inner join fw.DimJobCode JC on fact.JobCodeID= JC.JobCodeID
                  inner join fw.DimJobCodeGroup JCG on JC.jobCodeGroupID = JCG.JobCodeGroupID
                  inner join fw.DimPayCodeGroup PCG on fact.PayCodeGroupID = PCG.PayCodeGroupID 
                  WHERE
                    PCG.ProductiveClassID in ('3','2')	--Productive and Non-Productive
                    and (fact.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0)
                    and fact.TimeClassID = @timeClassID
            ) fact
            inner join #workingHours wpmCY on fact.FiscalMonthID= wpmCY.FiscalMonthID and fact.FiscalYearID= wpmCY.FiscalYearID and wpmCY.WorkWeekID= fact.WorkWeekID
            left join #workingHours wpmPY on fact.FiscalMonthID= wpmPY.FiscalMonthID and (fact.FiscalYearID-1)=wpmPY.FiscalYearID and wpmPY.WorkWeekID=fact.WorkWeekID

            IF OBJECT_ID('tempdb..#workingHours') IS NOT NULL DROP TABLE #workingHours
        END        
    END
ELSE -- Not rolling average
    BEGIN	
		update fact
		set
		    fact.FTEs=fact.Hours / (wpmCY.Hours),
            fact.FTEsYTD = fact.HoursYTD / (wpmCY.YTDHours),
            fact.FTEsPriorYear = CASE WHEN COALESCE(wpmPY.Hours, 0) = 0 THEN 0 ELSE fact.HoursPriorYear / (wpmPY.Hours) END,
            fact.FTEsPriorYTD = CASE WHEN COALESCE(wpmPY.YTDHours, 0) = 0 THEN 0 ELSE fact.HoursPriorYTD / (wpmPY.YTDHours) END
        from
            fw.FactPayrollSampledMonthly fact
            inner join [fw].[DimDepartment] D on fact.DepartmentID=D.DepartmentID
            inner join [fw].[DimJobCode] JC on fact.JobCodeID=JC.JobCodeID
            inner join fw.DimJobCodeGroup JCG on JC.jobCodeGroupID = JCG.JobCodeGroupID
            inner join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY on fact.FiscalMonthID=wpmCY.FiscalMonthID and CASE WHEN @targetType = 1 AND TimeClassID in (20,4,22) THEN fact.FiscalYearID-1 ELSE fact.FiscalYearID   END=wpmCY.FiscalYearID and wpmCY.WorkWeekID=D.WorkWeekID
            left join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmPY on fact.FiscalMonthID=wpmPY.FiscalMonthID and CASE WHEN @targetType = 1 AND TimeClassID in (20,4,22) THEN fact.FiscalYearID-2 ELSE fact.FiscalYearID-1 END=wpmPY.FiscalYearID and wpmPY.WorkWeekID=D.WorkWeekID
            inner join fw.DimFiscalMonth fm on fact.FiscalMonthID=fm.FiscalMonthID
            inner join [fw].[DimPayCodeGroup] pcg on fact.PayCodeGroupID = pcg.PayCodeGroupID
        where
            pcg.ProductiveClassID in ('3','2')	--Productive and Non-Productive
            and jc.WorkWeekOverrideID=-1 and jcg.WorkWeekOverrideID=-1 
            and (fact.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0)
            and fact.TimeClassID = @timeClassID
	    option (recompile)

        update fact
        set
            fact.FTEs=fact.Hours / (wpmCY.Hours),
            fact.FTEsYTD = fact.HoursYTD / (wpmCY.YTDHours),
            fact.FTEsPriorYear = CASE WHEN COALESCE(wpmPY.Hours, 0) = 0 THEN 0 ELSE fact.HoursPriorYear / (wpmPY.Hours) END,
            fact.FTEsPriorYTD = CASE WHEN COALESCE(wpmPY.YTDHours, 0) = 0 THEN 0 ELSE fact.HoursPriorYTD / (wpmPY.YTDHours) END
        from
            fw.FactPayrollSampledMonthly fact
            inner join [fw].[DimJobCode] JC on fact.JobCodeID=JC.JobCodeID
            inner join fw.DimJobCodeGroup JCG on JC.jobCodeGroupID = JCG.JobCodeGroupID
            inner join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY on fact.FiscalMonthID=wpmCY.FiscalMonthID and CASE WHEN @targetType = 1 AND TimeClassID in (20,4,22) THEN fact.FiscalYearID-1 ELSE fact.FiscalYearID   END=wpmCY.FiscalYearID and wpmCY.WorkWeekID=jcg.WorkWeekOverrideID
            left join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmPY on fact.FiscalMonthID=wpmPY.FiscalMonthID and CASE WHEN @targetType = 1 AND TimeClassID in (20,4,22) THEN fact.FiscalYearID-2 ELSE fact.FiscalYearID-1 END=wpmPY.FiscalYearID and wpmPY.WorkWeekID=jcg.WorkWeekOverrideID
            inner join fw.DimFiscalMonth fm on fact.FiscalMonthID=fm.FiscalMonthID
            inner join [fw].[DimPayCodeGroup] pcg on fact.PayCodeGroupID = pcg.PayCodeGroupID
        where
            pcg.ProductiveClassID in ('3','2')	--Productive and Non-Productive
            and jcg.WorkWeekOverrideID<>-1 and jc.WorkWeekOverrideID=-1 
            and (fact.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0)
            and fact.TimeClassID = @timeClassID
       option (recompile)

       update fact
       set
            fact.FTEs=fact.Hours / (wpmCY.Hours),
            fact.FTEsYTD = fact.HoursYTD / (wpmCY.YTDHours),
            fact.FTEsPriorYear = CASE WHEN COALESCE(wpmPY.Hours, 0) = 0 THEN 0 ELSE fact.HoursPriorYear / (wpmPY.Hours) END,
            fact.FTEsPriorYTD = CASE WHEN COALESCE(wpmPY.YTDHours, 0) = 0 THEN 0 ELSE fact.HoursPriorYTD / (wpmPY.YTDHours) END
       from
            fw.FactPayrollSampledMonthly fact
            inner join [fw].[DimJobCode] JC on fact.JobCodeID=JC.JobCodeID
            inner join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY on fact.FiscalMonthID=wpmCY.FiscalMonthID and CASE WHEN @targetType = 1 AND TimeClassID in (20,4,22) THEN fact.FiscalYearID-1 ELSE fact.FiscalYearID   END=wpmCY.FiscalYearID and wpmCY.WorkWeekID=jc.WorkWeekOverrideID
            left join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmPY on fact.FiscalMonthID=wpmPY.FiscalMonthID and CASE WHEN @targetType = 1 AND TimeClassID in (20,4,22) THEN fact.FiscalYearID-2 ELSE fact.FiscalYearID-1 END=wpmPY.FiscalYearID and wpmPY.WorkWeekID=jc.WorkWeekOverrideID
            inner join fw.DimFiscalMonth fm on fact.FiscalMonthID=fm.FiscalMonthID
            inner join [fw].[DimPayCodeGroup] pcg on fact.PayCodeGroupID = pcg.PayCodeGroupID
       where
            pcg.ProductiveClassID in ('3','2')	--Productive and Non-Productive
            and jc.WorkWeekOverrideID<>-1
            and (fact.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0)
            and fact.TimeClassID = @timeClassID
       option (recompile)

    END
GO


---------------------------------------------

-- fw.procFactPayrollSampledPayPeriodBaselineTargetOverridesUpdate
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1        2021-02-18  KF      JAZZ-15158	Variable Productive Hours - Detailed Target Spread
*************************************************************/
CREATE PROCEDURE [fw].[procFactPayrollSampledPayPeriodBaselineTargetOverridesUpdate]
-- #PayrollSampledPayPeriodStaging should be created before calling this procedure
AS
  IF OBJECT_ID('tempdb..#VariableHours') IS NOT NULL  DROP TABLE #VariableHours
  IF OBJECT_ID('tempdb..#Spreads') IS NOT NULL  DROP TABLE #Spreads

  DECLARE @ProductiveClassProductiveID INT = 3

  SELECT FP.DepartmentID, FP.PayPeriodID, FP.JobCodeID, FP.PayCodeGroupID, CAST(FP.Hours AS decimal(21,6)) AS Hours, PT.VariableWorkedHoursPerUOS
  INTO #VariableHours
  FROM #PayrollSampledPayPeriodStaging FP
  INNER JOIN fw.DimPayPeriod PP ON PP.PayPeriodID = FP.PayPeriodID
  INNER JOIN clientpi.ProductivityTargetsByDepartment PT ON PT.FiscalYearID = PP.FiscalYearIDSecond AND PT.DepartmentID = FP.DepartmentID AND (PT.PeriodNumber = PP.PeriodNumber OR PT.PeriodNumber = 0)
  LEFT JOIN
  (
    SELECT VO.DepartmentID, VO.JobCodeID, VO.PayCodeGroupID, CASE WHEN VO.Variability > 0 THEN 1 ELSE 0 END AS IsVariable
    FROM ob.PayrollVariabilityOverrideCache VO
    INNER JOIN fw.DimPayCodeGroup PCG ON PCG.PayCodeGroupID = VO.PayCodeGroupID
    WHERE PCG.ProductiveClassID = @ProductiveClassProductiveID
  ) V1 ON V1.DepartmentID = FP.DepartmentID AND V1.JobCodeID = FP.JobCodeID AND V1.PayCodeGroupID = FP.PayCodeGroupID
  LEFT JOIN
  (
    SELECT D.DepartmentID, JC.JobCodeID, PCG.PayCodeGroupID, 1 AS IsVariable
    FROM fw.DimDepartment D
    CROSS JOIN fw.DimJobCode JC
    CROSS JOIN fw.DimPayCodeGroup PCG
    WHERE D.IsVariable = 1 AND JC.IsVariable = 1 AND PCG.IsVariable = 1 AND PCG.ProductiveClassID = @ProductiveClassProductiveID
  ) V2 ON V2.DepartmentID = FP.DepartmentID AND V2.JobCodeID = FP.JobCodeID AND V2.PayCodeGroupID = FP.PayCodeGroupID
  WHERE FP.TimeClassID = 20 AND COALESCE(V1.IsVariable, V2.IsVariable) = 1 AND (NOT (FP.IsSystemGenerated = 1 AND FP.Hours = 0))
  
  SELECT VH.DepartmentID, VH.PayPeriodID, VH.JobCodeID, VH.PayCodeGroupID, (CASE WHEN D.IsZeroSum = 1 THEN 1.0 ELSE VH.Hours END)/D.Total AS Spread
  INTO #Spreads
  FROM #VariableHours VH
  INNER JOIN
  (
    SELECT DepartmentID, PayPeriodID,
	CASE WHEN SUM(Hours) = 0 THEN 1 ELSE 0 END AS IsZeroSum,
	CASE WHEN SUM(Hours) = 0 THEN COUNT(1) ELSE SUM(Hours) END AS Total
    FROM #VariableHours
    GROUP BY DepartmentID, PayPeriodID
  ) D ON D.DepartmentID = VH.DepartmentID AND D.PayPeriodID = VH.PayPeriodID

  UPDATE ST
  SET Hours = S.Spread * VH.VariableWorkedHoursPerUOS * COALESCE(FS.Units, 0)
  FROM #VariableHours VH
  INNER JOIN #Spreads S ON S.DepartmentID = VH.DepartmentID AND S.PayPeriodID = VH.PayPeriodID AND S.JobCodeID = VH.JobCodeID AND S.PayCodeGroupID = VH.PayCodeGroupID
  INNER JOIN #PayrollSampledPayPeriodStaging ST ON ST.DepartmentID = VH.DepartmentID AND ST.PayPeriodID = VH.PayPeriodID AND ST.JobCodeID = VH.JobCodeID AND ST.PayCodeGroupID = VH.PayCodeGroupID
  LEFT JOIN
  (
    SELECT DepartmentID, PayPeriodID, SUM(Units) AS Units
    FROM fw.viewPrimaryStatisticsStaffingByPayPeriod
    WHERE TimeClassID = 20 AND IsDeleted = 0
    GROUP BY DepartmentID, PayPeriodID
  ) FS ON FS.DepartmentID = VH.DepartmentID AND FS.PayPeriodID = VH.PayPeriodID
  WHERE ST.TimeClassID = 20

  IF OBJECT_ID('tempdb..#VariableHours') IS NOT NULL  DROP TABLE #VariableHours
  IF OBJECT_ID('tempdb..#Spreads') IS NOT NULL  DROP TABLE #Spreads
GO


---------------------------------------------

-- fw.procFactPayrollSampledPayPeriodBaselineTargetUpdate
/**************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI			Description
** 1		2018-05-16	IP			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 2		2018-05-24	KF			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 3		2018-06-01	IP 			D-07006	Rolling Average method for metric target calculation doesn't include months with 0 values (one year part)
** 4		2018-06-05	IP 			TK-58643 added filetr for current year only and non-zero records in output
** 5		2019-08-20	vfay		D-08311		PR Sampling Proc : removed filtering out 0 Value Rows
** 6		2024-01-30	KF 			JAZZ-66821	Run PR Process Task: Some procs don't support non-consecutive pay period id (expect consecutive pay period id). It causes wrong YTD values & wrong Rolling Average Baseline Target values
** 7		2024-06-14  SM      	JAZZ-71536  change JobCodeID from smallint to int
*************************************************************/
CREATE PROC [fw].[procFactPayrollSampledPayPeriodBaselineTargetUpdate]
    @targetType tinyint = null,
    @numberOfPayPeriods tinyint = null,
    @departmentIDs nvarchar(max) = null,
    @fiscalYearID int = 0
as
	if (@targetType is null) set @targetType = (select Value from pi.SystemSetting where Name = 'Target Basis')
	if (@numberOfPayPeriods is null) set @numberOfPayPeriods = (select Value from pi.SystemSetting where Name = 'Number Of Rolling Average Pay Periods')

	create table #departments (val int primary key)
	insert into #departments select val from ConvertCSValuesToTable(@departmentIDs, ',')

	create table #payperiods (val smallint primary key, PayCycleID int)
	insert into #payperiods 
	select PayPeriodID, PayCycleID from fw.DimPayPeriod where FiscalYearIDSecond = @fiscalYearID

	create table #PayPeriodsPriorYear (val smallint primary key, PayCycleID int)
	insert into #PayPeriodsPriorYear select PayPeriodID, PayCycleID from fw.DimPayPeriod where FiscalYearIDSecond = @fiscalYearID-1

	declare @sql varchar(max)

	create table #temp
	(
		DepartmentID int,
		JobCodeID int,
		PayCodeGroupID int,
		PayPeriodID smallint,
		Hours decimal (18, 6),
		Dollars decimal (18, 6)
	)

	if (@targetType = 10) begin --Rolling Average
		IF OBJECT_ID('tempdb..#fullscope') IS NOT NULL DROP TABLE #fullscope
		IF OBJECT_ID('tempdb..#tempSortedPayPeriods') IS NOT NULL DROP TABLE #tempSortedPayPeriods
		select PayCycleID, PayPeriodID, SortOrder into #tempSortedPayPeriods from pi.viewPayPeriodsSortedInPayCycles

		IF @fiscalYearID = 0 BEGIN
		set @sql = '
		insert into #temp (DepartmentID, JobCodeID,  PayCodeGroupID, PayPeriodID,Hours,Dollars)
		select DepartmentID, JobCodeID,  PayCodeGroupID, PayPeriodID, isnull(Hours,0.0),isnull(Dollars,0.0) 
		FROM (
			select FullScope.DepartmentID, FullScope.JobCodeID,  FullScope.PayCodeGroupID,  FullScope.PayPeriodID,
			Dollars = ISNULL((SUM(Dollars) over(PARTITION BY DepartmentID, JobCodeID, PayCodeGroupID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfPayPeriods AS NVARCHAR(2)) +', 0),
			Hours	= ISNULL((SUM(Hours)   over(PARTITION BY DepartmentID, JobCodeID, PayCodeGroupID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfPayPeriods AS NVARCHAR(2)) +', 0)
			FROM (
				select DepartmentID, JobCodeID, PayCodeGroupID, PayPeriodID, /*records for months, which are absent in current year, but exist at least one month*/
					SUM(Dollars) as Dollars,
					SUM(Hours) as Hours
				FROM  (
					SELECT /*recods for months which are present in current year*/
						p.DepartmentID, p.JobCodeID,  p.PayCodeGroupID,  p.PayPeriodID,
						p.Hours,
						p.Dollars
					FROM #PayrollSampledPayPeriodStaging p
					where p.TimeClassID = 1 and p.isSystemGenerated = 0 

					UNION ALL

					SELECT /*combination of all for key columns months for current year*/
						p.DepartmentID, p.JobCodeID,  p.PayCodeGroupID,  dpp.PayPeriodID,
						0 AS Hours,
						0 AS Dollars
					FROM #PayrollSampledPayPeriodStaging p
					inner join #tempSortedPayPeriods pp on pp.PayPeriodID = p.PayPeriodID
					FULL join #tempSortedPayPeriods dpp on dpp.PayCycleID = pp.PayCycleID
					where dpp.SortOrder - pp.SortOrder between 1 and '+cast(@numberOfPayPeriods as nvarchar(2))+'
					and  p.TimeClassID = 1 and p.isSystemGenerated = 0
				) AllCombinations
				GROUP BY DepartmentID, JobCodeID,  PayCodeGroupID, PayPeriodID
			) FullScope
			inner join #tempSortedPayPeriods t on t.PayPeriodID = FullScope.PayPeriodID
		) FinalDataset
		WHERE (Dollars is not null 
			or Hours is not null)'
		END
		ELSE BEGIN -- @fiscalYearID != 0
			IF OBJECT_ID('tempdb..#PayPeriodsAllScope') IS NOT NULL DROP TABLE #PayPeriodsAllScope
			select * into #PayPeriodsAllScope from #payperiods
		
			insert into #PayPeriodsAllScope
			select pp.PayPeriodID, pp.PayCycleID
			from fw.DimPayPeriod pp
			inner join #tempSortedPayPeriods t on t.PayPeriodID = pp.PayPeriodID
			inner join
			(
				select s.PayCycleID, MIN(s.SortOrder-@numberOfPayPeriods) as MinSortOrder, MIN(s.SortOrder -1) as MaxSortOrder
				from #payperiods pp
				inner join #tempSortedPayPeriods s on s.PayPeriodID = pp.val
				group by s.PayCycleID
			) r on r.PayCycleID = pp.PayCycleID and t.SortOrder between MinSortOrder and MaxSortOrder

			set @sql = '
			select C.DepartmentID, C.JobCodeID, C.PayCodeGroupID, C.PayPeriodID, /*records for months, which are absent in current year, but exist at least one month*/
				SUM(C.Dollars) as Dollars,
				SUM(C.Hours) as Hours
			into #fullscope
			FROM  (
				SELECT /*recods for months which are present in current year*/
					p.DepartmentID, p.JobCodeID,  p.PayCodeGroupID ,  p.PayPeriodID,
					p.Hours,
					p.Dollars
				FROM #PayrollSampledPayPeriodStaging p /*table contains only this particular actuals (filtered by Depts, Year) no need for additional filters*/
				where TimeClassID = 1 and isSystemGenerated = 0
					
				UNION ALL
					
				SELECT /*recods for months which are present in current year*/
					p.DepartmentID, p.JobCodeID,  p.PayCodeGroupID ,  p.PayPeriodID,
					p.Hours,
					p.Dollars
				FROM fw.FactPayrollSampledPayPeriod p
				inner join #PayPeriodsPriorYear pppy on p.PayPeriodID = pppy.val /*filtering only values for "prior year", in fact periods, which affects current year*/
				'+ case when @departmentIDs IS NULL then '' else ' INNER JOIN #departments dpt on dpt.val = p.DepartmentID' end+'
				where p.TimeClassID = 1 and p.isSystemGenerated = 0
					
				UNION ALL
					
				SELECT /*combination of all for key columns months for current year*/
					p.DepartmentID, p.JobCodeID,  p.PayCodeGroupID, dpp.Val as PayPeriodID,
					0 AS Hours,
					0 AS Dollars
				FROM #PayrollSampledPayPeriodStaging p
				inner join fw.DimPayPeriod pp on pp.PayPeriodID = p.PayPeriodID
				FULL join #PayPeriodsAllScope dpp on dpp.PayCycleID = pp.PayCycleID
				where p.TimeClassID = 1 and p.isSystemGenerated = 0
					
				UNION ALL
				
				SELECT /*combination of all for key columns months for current year*/
					p.DepartmentID, p.JobCodeID,  p.PayCodeGroupID,  dpp.PayPeriodID,
					0 AS Hours,
					0 AS Dollars
				FROM fw.FactPayrollSampledPayPeriodDetailed p
				INNER JOIN #PayPeriodsPriorYear pppy on p.PayPeriodID = pppy.val /*filtering only values for "prior year", in fact periods, which affects current year*/
				INNER JOIN fw.DimPayPeriod dpp ON dpp.PayCycleID = pppy.PayCycleID
				'+ case when @departmentIDs IS NULL then '' else ' INNER JOIN #departments dpt on dpt.val = p.DepartmentID' end
				+' where p.TimeClassID = 1 and p.isSystemGenerated = 0
			) C
			inner join #PayPeriodsAllScope P on p.val = C.PayPeriodID
			GROUP BY C.DepartmentID, C.JobCodeID, C.PayCodeGroupID, C.PayPeriodID

			insert into #temp (DepartmentID, JobCodeID,  PayCodeGroupID, PayPeriodID,Hours,Dollars)
			select DepartmentID, JobCodeID,  PayCodeGroupID,   PayPeriodID, isnull(Hours,0.0),isnull(Dollars,0.0)
			FROM
			(
				select f.DepartmentID, f.JobCodeID, f.PayCodeGroupID, f.PayPeriodID, 
				Dollars = ISNULL((SUM(f.Dollars) over(PARTITION BY f.DepartmentID, f.JobCodeID, f.PayCodeGroupID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfPayPeriods AS NVARCHAR(2)) +', 0),
				Hours	= ISNULL((SUM(f.Hours)   over(PARTITION BY f.DepartmentID, f.JobCodeID, f.PayCodeGroupID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfPayPeriods AS NVARCHAR(2)) +', 0)
				FROM #fullscope f			
				inner join #tempSortedPayPeriods t on t.PayPeriodID = f.PayPeriodID
			) FinalDataset
			INNER JOIN #PayPeriods PP on pp.Val = FinalDataset.PayPeriodID
			WHERE (Dollars is not null 
				or Hours is not null)'
		END
	exec(@sql)
	IF OBJECT_ID('tempdb..#fullscope') IS NOT NULL DROP TABLE #fullscope

	end else begin --Budget
		insert into #temp 
			  (DepartmentID, JobCodeID,  PayCodeGroupID,   PayPeriodID, Hours ,Dollars)
		select DepartmentID, JobCodeID,  PayCodeGroupID,   PayPeriodID, isnull(Hours,0.0),isnull(Dollars,0.0)
		from #PayrollSampledPayPeriodStaging
		where TimeClassID = 2 and (@departmentIDs is null or DepartmentID in (select val from #departments)) and (@fiscalYearID = 0 or PayPeriodID in(select val from #payperiods))
	end

	insert into #PayrollSampledPayPeriodStaging (DepartmentID, JobCodeID, PayPeriodID, PayCodeGroupID,   TimeClassID, Hours,Dollars,HoursYTD,HoursPriorYear,HoursPriorYTD,DollarsYTD,DollarsPriorYear,DollarsPriorYTD,FTEs,FTEsYTD,FTEsPriorYear,FTEsPriorYTD, isSystemGenerated) 
	SELECT DepartmentID, JobCodeID, PayPeriodID, PayCodeGroupID,  20 as TimeClassID, Hours,Dollars,0 as HoursYTD,0 as HoursPriorYear,0 as HoursPriorYTD,0 as DollarsYTD,0 as DollarsPriorYear,0 as DollarsPriorYTD,0 as FTEs,0 as FTEsYTD,0 as FTEsPriorYear,0 as FTEsPriorYTD, 0 as isSystemGenerated from #temp
	where  (@fiscalYearID = 0 or PayPeriodID in(select val from #payperiods))
	drop table #temp
	drop table #departments
	IF OBJECT_ID('tempdb..#PayPeriodsAllScope') IS NOT NULL DROP TABLE #PayPeriodsAllScope
	IF OBJECT_ID('tempdb..#tempSortedPayPeriods') IS NOT NULL DROP TABLE #tempSortedPayPeriods;
GO


---------------------------------------------

-- fw.procFactPayrollSampledPayPeriodDetailedBaselineTargetUpdate
/**************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI			Description
** 1		2018-05-16	IP			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 2		2018-05-16	KF			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 3		2018-06-01	IP 			D-07006	Rolling Average method for metric target calculation doesn't include months with 0 values (one year part)
** 4		2018-06-05	IP 			TK-58643 added filetr for current year only and non-zero records in output
** 5		2019-08-23	vfay		D-08311		PR Sampling Proc : removed filtering out 0 Value Rows
** 6		2024-01-30	KF 			JAZZ-66821	Run PR Process Task: Some procs don't support non-consecutive pay period id (expect consecutive pay period id). It causes wrong YTD values & wrong Rolling Average Baseline Target values
** 7		2024-06-14  SM      	JAZZ-71536  change JobCodeID from smallint to int
*************************************************************/
CREATE proc [fw].[procFactPayrollSampledPayPeriodDetailedBaselineTargetUpdate]
    @targetType tinyint = null,
    @numberOfPayPeriods tinyint = null,
    @departmentIDs nvarchar(max) = null,
	@fiscalYearID int = 0
with recompile
as
	if (@targetType is null) set @targetType = (select Value from pi.SystemSetting where Name = 'Target Basis')
	if (@numberOfPayPeriods is null) set @numberOfPayPeriods = (select Value from pi.SystemSetting where Name = 'Number Of Rolling Average Pay Periods')

	create table #departments (val int primary key)
	insert into #departments select val from ConvertCSValuesToTable(@departmentIDs, ',')

	create table #payperiods (val smallint primary key, PayCycleID int)
	insert into #payperiods 
	select PayPeriodID, PayCycleID from fw.DimPayPeriod where FiscalYearIDSecond = @fiscalYearID

	create table #PayPeriodsPriorYear (val smallint primary key, PayCycleID int)
	insert into #PayPeriodsPriorYear select PayPeriodID, PayCycleID from fw.DimPayPeriod where FiscalYearIDSecond = @fiscalYearID-1

	declare @sql varchar(max)

	create table #temp
	(
		DepartmentID int,
		JobCodeID int,
		PayCodeID int,
		PayCodeGroupID int,
		EmployeeID int,
		PayPeriodID smallint,
		Hours decimal (18, 6),
		Dollars decimal (18, 6)
	)

	if (@targetType = 10) begin --Rolling Average
		IF OBJECT_ID('tempdb..#fullscope') IS NOT NULL DROP TABLE #fullscope
		IF OBJECT_ID('tempdb..#tempSortedPayPeriods') IS NOT NULL DROP TABLE #tempSortedPayPeriods
		select PayCycleID, PayPeriodID, SortOrder into #tempSortedPayPeriods from pi.viewPayPeriodsSortedInPayCycles

	IF @fiscalYearID = 0 BEGIN
		set @sql = '
		insert into #temp (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID,  PayPeriodID, Hours, Dollars)
		select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID,  PayPeriodID, isnull(Hours,0.0),isnull(Dollars,0.0) 
		FROM (
		select FullScope.DepartmentID, FullScope.JobCodeID, FullScope.PayCodeID, FullScope.PayCodeGroupID, FullScope.EmployeeId, FullScope.PayPeriodID,
		Dollars = ISNULL((Sum(Dollars) over(PARTITION BY DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfPayPeriods as nvarchar(2))+', 0),
		Hours	= ISNULL((Sum(Hours)   over(PARTITION BY DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfPayPeriods as nvarchar(2))+', 0)
		FROM (
			select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID,  PayPeriodID, /*records for months, which are absent in current year, but exist at least one month*/
					SUM(Dollars) as Dollars,
					SUM(Hours) as Hours
			FROM (
				SELECT /*recods for months which are present in current year*/
						p.DepartmentID, p.JobCodeID, p.PayCodeID, p.PayCodeGroupID, p.EmployeeID, p.PayPeriodID,
						p.Hours,
						p.Dollars
				FROM  #PayrollSampledPayPeriodDetailedStaging p
				where p.TimeClassID = 1 and p.isSystemGenerated = 0

				UNION ALL

				SELECT /*combination of all for key columns months for current year*/
						p.DepartmentID, p.JobCodeID, p.PayCodeID, p.PayCodeGroupID, p.EmployeeID, dpp.PayPeriodID,
						0 AS Hours,
						0 AS Dollars
				FROM  #PayrollSampledPayPeriodDetailedStaging p
				inner join #tempSortedPayPeriods pp on pp.PayPeriodID = p.PayPeriodID
				FULL join #tempSortedPayPeriods dpp on dpp.PayCycleID = pp.PayCycleID
				where dpp.SortOrder - pp.SortOrder between 1 and '+cast(@numberOfPayPeriods as nvarchar(2))+'
				and  p.TimeClassID = 1 and p.isSystemGenerated = 0
				) AllCombinations
				GROUP BY DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, PayPeriodID, EmployeeID
			) FullScope
			inner join #tempSortedPayPeriods t on t.PayPeriodID = FullScope.PayPeriodID
		) FinalDataset
		WHERE (Dollars is not null 
			or Hours is not null)'
	end
	ELSE BEGIN -- @fiscalYearID != 0
		IF OBJECT_ID('tempdb..#PayPeriodsAllScope') IS NOT NULL DROP TABLE #PayPeriodsAllScope
		select * into #PayPeriodsAllScope from #payperiods

		insert into #PayPeriodsAllScope
		select pp.PayPeriodID, pp.PayCycleID
		from fw.DimPayPeriod pp
		inner join #tempSortedPayPeriods t on t.PayPeriodID = pp.PayPeriodID
		inner join
		(
			select s.PayCycleID, MIN(s.SortOrder-@numberOfPayPeriods) as MinSortOrder, MIN(s.SortOrder -1) as MaxSortOrder
			from #payperiods pp
			inner join #tempSortedPayPeriods s on s.PayPeriodID = pp.val
			group by s.PayCycleID
		) r on r.PayCycleID = pp.PayCycleID and t.SortOrder between MinSortOrder and MaxSortOrder

		set @sql = '
			select C.DepartmentID, C.JobCodeID, C.PayCodeID, C.PayCodeGroupID, C.EmployeeID, C.PayPeriodID, /*records for months, which are absent in current year, but exist at least one month*/
				SUM(C.Dollars) as Dollars,
				SUM(C.Hours) as Hours
			into #fullscope
			FROM (
				SELECT 
					p.DepartmentID, p.JobCodeID, p.PayCodeID, p.PayCodeGroupID , EmployeeID, p.PayPeriodID,
					p.Hours,
					p.Dollars
				FROM  #PayrollSampledPayPeriodDetailedStaging p /*table contains only this particular actuals (filtered by Depts, Year) no need for additional filters*/
				where TimeClassID = 1 and isSystemGenerated = 0

				UNION ALL
					
				SELECT 
					p.DepartmentID, p.JobCodeID, p.PayCodeID, p.PayCodeGroupID, p.EmployeeID, p.PayPeriodID,
					Hours,
					Dollars
				FROM fw.FactPayrollSampledPayPeriodDetailed p
				inner join #PayPeriodsPriorYear pppy on p.PayPeriodID = pppy.val /*filtering only values for "prior year", in fact periods, which affects current year*/
				'+ case when @departmentIDs IS NULL then '' else ' INNER JOIN #departments dpt on dpt.val = p.DepartmentID' end+'
				where p.TimeClassID = 1 and p.isSystemGenerated = 0
					
				UNION ALL
					
				SELECT
					p.DepartmentID, p.JobCodeID, p.PayCodeID, p.PayCodeGroupID, EmployeeID ,dpp.Val as PayPeriodID,
					0 AS Hours,
					0 AS Dollars
				FROM  #PayrollSampledPayPeriodDetailedStaging p
				inner join fw.DimPayPeriod pp on pp.PayPeriodID = p.PayPeriodID
				FULL join #PayPeriodsAllScope dpp on dpp.PayCycleID = pp.PayCycleID
				where p.TimeClassID = 1 and p.isSystemGenerated = 0
					
				UNION ALL
					
				SELECT 
					p.DepartmentID, p.JobCodeID, p.PayCodeID, p.PayCodeGroupID, p.EmployeeID, dpp.PayPeriodID,
					0 AS Hours,
					0 AS Dollars
				FROM fw.FactPayrollSampledPayPeriodDetailed p
				INNER JOIN #PayPeriodsPriorYear pppy on p.PayPeriodID = pppy.val /*filtering only values for "prior year", in fact periods, which affects current year*/
				INNER JOIN fw.DimPayPeriod dpp ON dpp.PayCycleID = pppy.PayCycleID
				'+ case when @departmentIDs IS NULL then '' else ' INNER JOIN #departments dpt on dpt.val = p.DepartmentID' end
			+' where p.TimeClassID = 1 and p.isSystemGenerated = 0
			) C
			inner join #PayPeriodsAllScope P on p.val = C.PayPeriodID
			GROUP BY C.DepartmentID, C.JobCodeID, C.PayCodeID, C.PayCodeGroupID, C.EmployeeID, C.PayPeriodID

			insert into #temp (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID,  PayPeriodID, Hours, Dollars)
			select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID,  PayPeriodID, isnull(Hours,0.0), isnull(Dollars,0.0)
			FROM (
				select f.DepartmentID, f.JobCodeID, f.PayCodeID, f.PayCodeGroupID, f.EmployeeID, f.PayPeriodID, 
				Dollars = ISNULL((Sum(f.Dollars) over(PARTITION BY f.DepartmentID, f.JobCodeID, f.PayCodeID, f.PayCodeGroupID, f.EmployeeID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfPayPeriods as nvarchar(2))+', 0),
				Hours	= ISNULL((Sum(f.Hours)   over(PARTITION BY f.DepartmentID, f.JobCodeID, f.PayCodeID, f.PayCodeGroupID, f.EmployeeID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfPayPeriods as nvarchar(2))+', 0)
				FROM #fullscope f
				inner join #tempSortedPayPeriods t on t.PayPeriodID = f.PayPeriodID
			) FinalDataset
			INNER JOIN #PayPeriods PP on  pp.Val = FinalDataset.PayPeriodID
			WHERE (Dollars is not null 
				or Hours is not null)'
	END
	exec(@sql)

	IF OBJECT_ID('tempdb..#fullscope') IS NOT NULL DROP TABLE #fullscope

	end else begin --Budget
		insert into #temp 
			  (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID,  PayPeriodID, Hours ,Dollars)
		select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID,  PayPeriodID, isnull(Hours,0.0),isnull(Dollars,0.0)
		from  #PayrollSampledPayPeriodDetailedStaging
		where TimeClassID = 2 and (@departmentIDs is null or DepartmentID in (select val from #departments)) and (@fiscalYearID = 0 or PayPeriodID in(select val from #payperiods))
	end

	insert into  #PayrollSampledPayPeriodDetailedStaging (DepartmentID, JobCodeID, PayPeriodID, PayCodeGroupID, PayCodeID, EmployeeID, TimeClassID, Hours, Dollars) 
	SELECT DepartmentID, JobCodeID, PayPeriodID, PayCodeGroupID, PayCodeID, EmployeeID, 20 as TimeClassID, Hours, Dollars from #temp
	where (@fiscalYearID = 0 or PayPeriodID in(select val from #payperiods))

	drop table #temp
	drop table #departments
	drop table #payperiods
	IF OBJECT_ID('tempdb..#PayPeriodsAllScope') IS NOT NULL DROP TABLE #PayPeriodsAllScope
	IF OBJECT_ID('tempdb..#tempSortedPayPeriods') IS NOT NULL DROP TABLE #tempSortedPayPeriods;
GO


---------------------------------------------

-- fw.procFactProviderSampledBaselineTargetUpdate
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
** 1		2018-06-27	KF			B-20195	MR - Provider calculate baseline target
** 2		2018-07-24	KF			B-20342	MR - Update provider sampling to be in the appropriate format
*************************************************************/
CREATE PROCEDURE [fw].[procFactProviderSampledBaselineTargetUpdate]
	@fiscalYearID INT = 0
AS

CREATE TABLE #temp
(
  DepartmentID INT,
  ProviderID INT,
  FiscalYearID INT,
  FiscalMonthID INT,
  OBForecastDetailID INT,
  Dollars DECIMAL(18,6),
  Hours DECIMAL(18,6),
  Volume DECIMAL(18,6),
  FTEs DECIMAL(18,6)
)

--DECLARE @maxCalculatingFiscalYear INT = (SELECT MAX(FiscalYearID) FROM #ProviderSampledStaging)

--TODO: if Prior Year YTD/Rolling Average types are added, @targetType initialization should be changed in proc client.procFactProviderSampledMonthlyFTEsInsert based on mr.SystemSetting
--Budget
		INSERT INTO #temp
		SELECT DepartmentID, ProviderID, FiscalYearID, FiscalMonthID, OBForecastDetailID, Dollars, Hours, Volume, FTEs
		FROM #ProviderSampledStaging
		WHERE TimeClassID = 2
			AND (FiscalYearID = @FiscalYearID OR @FiscalYearID = 0)


DELETE FROM #ProviderSampledStaging WHERE TimeClassID = 20 and (FiscalYearID = @FiscalYearID or @FiscalYearID = 0)
INSERT INTO #ProviderSampledStaging (DepartmentID, ProviderID, FiscalYearID, FiscalMonthID, TimeClassID, OBForecastDetailID, Dollars, Hours, Volume, FTEs)
SELECT source.DepartmentID, source.ProviderID, source.FiscalYearID, source.FiscalMonthID, 20, source.OBForecastDetailID, source.Dollars, source.Hours, source.Volume, source.FTEs FROM #temp source
WHERE NOT(Dollars = 0 AND Hours = 0 AND Volume = 0 AND FTEs = 0)

DROP TABLE #temp
GO


---------------------------------------------

-- fw.procFactRoleAssignmentImportSample
CREATE proc [fw].[procFactRoleAssignmentImportSample]
as
	declare @rowID int
	declare @userGUID uniqueidentifier
	declare @roleID smallint
	declare @lootID nvarchar(16)

	declare crsRoleImport cursor fast_forward for select RowID, UserGUID, RoleID, LootGroupID from client.viewFactRoleAssignmentImport

	open crsRoleImport
	fetch next from crsRoleImport into @rowID, @userGUID, @roleID, @lootID

	while(@@FETCH_STATUS = 0) begin
		exec procS3AssignIdentityToRole @userGUID, @roleID, @lootID
		update client.FactRoleAssignmentImport set ImportDate = GETDATE() where RowID = @rowID and SampleDate = '01/01/1900'
		fetch next from crsRoleImport into @rowID, @userGUID, @roleID, @lootID
	end

	close crsRoleImport
	deallocate crsRoleImport
GO


---------------------------------------------

-- fw.procFactStatisticPrimarySampledBaselineTargetUpdate
/**************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI			Description
** 1		2017-03-06	gforeman	B-14693		Added year filter
** 2		2017-03-28	ipetriv		D-05641		Logic for Prior and Actual was changed to simply copy actuals from previous year
** 3		2017-04-05 	ipetriv		D-05789		Changed algorithm for rolling average calculation
** 4		2017-05-24	IPetriv		B-15086		Sampling Performance Improvements. Using temp tables insead of fw.FactStatisticPrimarySampledMonthly.
** 5		2017-06-15	IP			B-15086 	Modify SP to use unique temp table
** 6		2018-05-16	IP			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 7		2018-05-16	KF			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 8		2018-06-01	IP 			D-07006	Rolling Average method for metric target calculation doesn't include months with 0 values (one year part)
** 9		2018-06-05	IP 			TK-58643 added filetr for current year only and non-zero records in output
*************************************************************/
CREATE proc [fw].[procFactStatisticPrimarySampledBaselineTargetUpdate]
    @targetType int = null,
    @numberOfMonths int = null,
	@fiscalYearID int = 0

as
	if (@targetType is null) set @targetType = (select Value from mr.SystemSetting where Name = 'Target Basis')
	if (@numberOfMonths is null) set @numberOfMonths = (select Value from mr.SystemSetting where Name = 'Number Of Rolling Average Months')

	declare @sql varchar(max)
	declare @maxCalculatingFiscalYear int = (select max(FiscalYearID) from  #StatisticPrimarySampledStaging)

	create table #temp
	(
		DepartmentID int,
		AccountID int,
		FiscalYearID smallint,
		FiscalMonthID tinyint,
		Amount decimal (19, 4)
	)

	if (@targetType = 1) begin --Prior Year Actual
	if @fiscalYearID <> 0
		insert into #temp
		select d.DepartmentID, d.AccountID, d.FiscalYearID+1, d.FiscalMonthID, d.Amount
		from fw.FactStatisticPrimarySampledMonthly d WHERE d.TimeClassID = 1 and d.FiscalYearID = @fiscalYearID-1
	else 
		insert into #temp
		select d.DepartmentID, d.AccountID, d.FiscalYearID+1, d.FiscalMonthID, d.Amount
		from  #StatisticPrimarySampledStaging d WHERE d.TimeClassID = 1
	end else if (@targetType = 10) begin --Rolling Average
		IF @fiscalYearID = 0
		set @sql = '
		insert into #temp
		select DepartmentID, AccountID, FiscalYearID, FiscalMonthID,isnull(Amount,0.0) FROM (
		select FullScope.DepartmentID, FullScope.AccountID, FullScope.FiscalYearID, m.FiscalMonthID,
		Amount	= ISNULL((Sum(Amount)   over(PARTITION BY DepartmentID,AccountID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0)
		FROM (
			select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/
					AccountID,
					FiscalYearID,
					SortOrder,
					SUM(Amount) as Amount
			FROM  (
					SELECT /*recods for months which are present in current year*/
						DepartmentID,
						AccountID,
						FiscalYearID,
						m.SortOrder,
						Amount
					FROM  #StatisticPrimarySampledStaging p
					JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
					where m.FiscalMonthID <> 0 and TimeClassID = 1   and isnull(p.IsSystemGenerated,0) = 0
					UNION ALL
					SELECT /*combination of all for key columns months which were present in prior year*/
						p.DepartmentID,
						p.AccountID,
						fy.FiscalYearID,
						m.SortOrder,
						0 AS Amount
					FROM  #StatisticPrimarySampledStaging p
					CROSS JOIN fw.DimFiscalMonth m
					CROSS JOIN (select FiscalYearID 
							from fw.DimFiscalYear dm 
							) fy
					where m.FiscalMonthID <> 0 and p.TimeClassID = 1  and isnull(p.IsSystemGenerated,0) = 0
				) AllCombinations
				GROUP BY DepartmentID,AccountID,FiscalYearID,SortOrder
	) FullScope
	JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder
	) FinalDataset
	WHERE Amount is not null
	AND FiscalYearID <='+cast(@maxCalculatingFiscalYear as nvarchar(4))
	ELSE 
	SET @sql = '
		insert into #temp
		select DepartmentID, AccountID, FiscalYearID, FiscalMonthID,isnull(Amount,0.0) FROM (
		select FullScope.DepartmentID, FullScope.AccountID, FullScope.FiscalYearID, m.FiscalMonthID,
		Amount	= ISNULL((Sum(Amount)   over(PARTITION BY DepartmentID,AccountID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0)
		FROM (
			select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/
					AccountID,
					FiscalYearID,
					SortOrder,
					SUM(Amount) as Amount
			FROM  (
					SELECT /*recods for months which are present in current year*/
						DepartmentID,
						AccountID,
						FiscalYearID,
						m.SortOrder,
						Amount
					FROM  #StatisticPrimarySampledStaging p
					JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
					where m.FiscalMonthID <> 0 and TimeClassID = 1  and isnull(p.IsSystemGenerated,0) = 0
				UNION ALL
					SELECT /*recods with amounts from previous year*/
							DepartmentID,
							AccountID,
							FiscalYearID,
							m.SortOrder,
							Amount
					FROM fw.FactStatisticPrimarySampledMonthly p
					JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
					where m.FiscalMonthID <> 0 and TimeClassID = 1  and isnull(p.IsSystemGenerated,0) = 0
					and FiscalYearID = '+cast(@fiscalYearID-1 as nvarchar(4)) +'
				UNION ALL
					SELECT /*combination of all for key columns months for current year*/
							DepartmentID,
							AccountID,
							FiscalYearID,
							m.SortOrder,
							0 AS Amount
					FROM  #StatisticPrimarySampledStaging  p
					CROSS APPLY fw.DimFiscalMonth m
					where m.FiscalMonthID <> 0 and TimeClassID = 1  and isnull(p.IsSystemGenerated,0) = 0
				UNION ALL
					SELECT /*combination of all for key columns months which were present in prior year*/
						p.DepartmentID,
						p.AccountID,
						fy.FiscalYearID,
						m.SortOrder,
						0 AS Amount
					FROM fw.FactStatisticPrimarySampledMonthly p
					CROSS JOIN fw.DimFiscalMonth m
					CROSS JOIN (select FiscalYearID 
								from fw.DimFiscalYear dm 
								where FiscalYearID in ('+cast(@fiscalYearID-1 as nvarchar(4))+','+cast(@fiscalYearID as nvarchar(4))+')'+'
								) fy
					where m.FiscalMonthID <> 0 and p.TimeClassID = 1  and isnull(p.IsSystemGenerated,0) = 0 and p.FiscalYearID = '+cast(@fiscalYearID-1 as nvarchar(4)) +'
				) AllCombinations
				GROUP BY DepartmentID,AccountID,FiscalYearID,SortOrder
	) FullScope
	JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder
	) FinalDataset
	WHERE Amount is not null
	AND FiscalYearID ='+cast(@fiscalYearID as nvarchar(4))
	exec (@sql)
	end else begin --Budget
		insert into #temp
		select DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Amount
		from  #StatisticPrimarySampledStaging
		where TimeClassID = 2 and (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID)
	end
    
	insert into  #StatisticPrimarySampledStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount)
	select  DepartmentID, AccountID, FiscalYearID, FiscalMonthID, 20, Amount from #temp
	where (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID) and Amount !=0

	drop table #temp
GO


---------------------------------------------

-- fw.procFactStatisticSampledBaselineTargetUpdate
/**************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI			Description
** 1		2017-03-06	gforeman	B-14693		Added year filter
** 2		2017-03-28	ipetriv		D-05641		Logic for Prior and Actual was changed to simply copy actuals from previous year
** 3		2017-04-05 	ipetriv		D-05789		Changed algorithm for rolling average calculation
** 4		2017-05-24	IPetriv		B-15086		Sampling Performance Improvements. Using temp tables insead of fw.FactPayrollSampledMonthlyDetailed.
** 5		2017-06-07	IPetriv		B-15086		Fixed after integration test fails
** 6		2017-06-15	IP			B-15086 	Modify SP to use unique temp table
** 7		2018-05-16	IP			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 8		2018-05-16	KF			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 9		2018-06-01	IP 			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values (one year part)
** 10		2018-06-05	IP 			TK-58643 added filetr for current year only and non-zero records in output
*************************************************************/
CREATE proc [fw].[procFactStatisticSampledBaselineTargetUpdate]
    @targetType int = null,
    @numberOfMonths int = null,
	@fiscalYearID int = 0
with recompile
as
	
	if (@targetType is null) set @targetType = (select Value from mr.SystemSetting where Name = 'Target Basis')
	if (@numberOfMonths is null) set @numberOfMonths = (select Value from mr.SystemSetting where Name = 'Number Of Rolling Average Months')
	
	declare @sql varchar(max)
	declare @maxCalculatingFiscalYear int = (select max(FiscalYearID) from  #StatisticSampledMonthlyStaging)

	create table #temp
	(
		DepartmentID int,
		AccountID int,
		FiscalYearID smallint,
		FiscalMonthID tinyint,
		Amount decimal (18, 6)
	)

	if (@targetType = 1) begin --Prior Year Actual
	if @fiscalYearID <> 0
		insert into #temp
		select d.DepartmentID, d.AccountID, d.FiscalYearID+1, d.FiscalMonthID, d.Amount
		from fw.FactStatisticSampledMonthly d where d.TimeClassID = 1 and d.FiscalYearID = @fiscalYearID-1
	else 
		insert into #temp
		select d.DepartmentID, d.AccountID, d.FiscalYearID+1, d.FiscalMonthID, d.Amount
		from  #StatisticSampledMonthlyStaging d where d.TimeClassID = 1
	end else if (@targetType = 10) begin --Rolling Average
	IF @fiscalYearID = 0
	set @sql = '

		insert into #temp
		select DepartmentID, AccountID, FiscalYearID, FiscalMonthID,isnull(Amount,0.0) FROM (
		select FullScope.DepartmentID, FullScope.AccountID, FullScope.FiscalYearID, m.FiscalMonthID,
		Amount	= ISNULL((Sum(Amount) over(PARTITION BY DepartmentID,AccountID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0)
		FROM (
			select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/
					AccountID,
					FiscalYearID,
					SortOrder,
					SUM(Amount) as Amount
			FROM  (
				SELECT /*recods for months which are present in current year*/
						DepartmentID,
						AccountID,
						FiscalYearID,
						m.SortOrder,
						Amount
					FROM  #StatisticSampledMonthlyStaging p
					JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
					where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0
				UNION ALL
					SELECT /*combination of all for key columns months for current year*/
						p.DepartmentID,
						p.AccountID,
						fy.FiscalYearID,
						fy.SortOrder,
						0 AS Amount
					FROM  #StatisticSampledMonthlyStaging p
					INNER JOIN fw.DimFiscalMonth m on m.FiscalMonthID = p.FiscalMonthID
					INNER JOIN (select FiscalYearID,FiscalMonthID,fm.sortOrder,fy.FiscalYearID*12+fm.SortOrder as ChronologicalOrder from fw.DimFiscalYear fy
								full join fw.DimFiscalMonth fm on 1= 1 
								where FiscalMonthID  <> 0 and FiscalYearID <> 0) fy ON ChronologicalOrder - (p.FiscalYearID*12+m.SortOrder) between 1 and '+cast(@numberOfMonths as nvarchar(2))+'
					where m.FiscalMonthID <> 0 and p.TimeClassID = 1  and isnull(p.IsSystemGenerated,0) = 0
				) AllCombinations
				GROUP BY DepartmentID,AccountID,FiscalYearID,SortOrder
	) FullScope
	JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder
	) FinalDataset
	WHERE Amount is not null
	AND FiscalYearID <='+cast(@maxCalculatingFiscalYear as nvarchar(4))
	ELSE 
	set @sql = '

		insert into #temp
		select DepartmentID, AccountID, FiscalYearID, FiscalMonthID,isnull(Amount,0.0) FROM (
		select FullScope.DepartmentID, FullScope.AccountID, FullScope.FiscalYearID, m.FiscalMonthID,
		Amount	= ISNULL((Sum(Amount) over(PARTITION BY DepartmentID,AccountID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0)
		FROM (
			select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/
					AccountID,
					FiscalYearID,
					SortOrder,
					SUM(Amount) as Amount
			FROM  (
				SELECT /*recods for months which are present in current year*/
						DepartmentID,
						AccountID,
						FiscalYearID,
						m.SortOrder,
						Amount
					FROM  #StatisticSampledMonthlyStaging p
					JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
					where m.FiscalMonthID <> 0 and TimeClassID = 1  and isnull(isSystemGenerated,0) = 0
				UNION ALL
					SELECT /*recods with amounts from previous year*/
							DepartmentID,
							AccountID,
							FiscalYearID,
							m.SortOrder,
							Amount
					FROM fw.FactStatisticSampledMonthly p
					INNER JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
					where m.FiscalMonthID <> 0 and TimeClassID = 1  and isnull(isSystemGenerated,0) = 0
					and FiscalYearID = '+cast(@fiscalYearID-1 as nvarchar(4)) +'
				UNION ALL
					SELECT /*combination of all for key columns months for current year*/
							DepartmentID,
							AccountID,
							FiscalYearID,
							m.SortOrder,
							0 AS Amount
					FROM  #StatisticSampledMonthlyStaging p
					CROSS APPLY fw.DimFiscalMonth m
					where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0
				UNION ALL
					SELECT /*combination of all for key columns months for current year*/
						p.DepartmentID,
						p.AccountID,
						fy.FiscalYearID,
						m.SortOrder,
						0 AS Amount
					FROM fw.FactStatisticSampledMonthly p
					CROSS JOIN fw.DimFiscalMonth m
					CROSS JOIN (select FiscalYearID 
								from fw.DimFiscalYear dm 
								where FiscalYearID in ('+cast(@fiscalYearID-1 as nvarchar(4))+','+cast(@fiscalYearID as nvarchar(4))+')'+'
								) fy
					where m.FiscalMonthID <> 0 and p.TimeClassID = 1  and isnull(p.IsSystemGenerated,0) = 0 and p.FiscalYearID ='+cast(@fiscalYearID-1 as nvarchar(4))+'
				) AllCombinations
				GROUP BY DepartmentID,AccountID,FiscalYearID,SortOrder
	) FullScope
	JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder
	) FinalDataset
	WHERE Amount is not null
	AND FiscalYearID ='+cast(@fiscalYearID as nvarchar(4))
	exec (@sql)
	end else begin --Budget
		insert into #temp
		select DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Amount
		from  #StatisticSampledMonthlyStaging
		where TimeClassID = 2 and (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID)
	end
    
	insert into  #StatisticSampledMonthlyStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, isSystemGenerated)
	select  DepartmentID, AccountID, FiscalYearID, FiscalMonthID, 20, Amount, 0 as isSystemGenerated from #temp
	WHERE (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID) and Amount !=0

	drop table #temp
GO


---------------------------------------------

-- fw.procFactStatisticSampledPayPeriodBaselineTargetUpdate
/************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI			Description
** 1		2017-02-08	GJF			B-14308 	Added year filter
** 2		2017-04-05 	ipetriv		D-05789		Changed algorithm for rolling average calculation
** 3		2017-05-29 	ipetriv		B-15994		Refactored sampling process and implemented using of staging tables
** 4		2017-06-15	IP			B-15086		Modify SP to use unique temp table
** 5		2018-05-16	IP			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 6		2018-05-16	KF			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 7		2018-06-01	IP 			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values (one year part)
** 8		2018-06-05	IP 			TK-58643	added filetr for current year only and non-zero records in output
** 9		2018-06-05	IP 			TK-58643	added filetr for current year only and non-zero records in output
** 10		2020-07-30	HV 			JAZZ-2302	YTD PR Calculations Incorrect when Processing Current Year Only
** 11		2024-01-30	KF 			JAZZ-66821	Run PR Process Task: Some procs don't support non-consecutive pay period id (expect consecutive pay period id). It causes wrong YTD values & wrong Rolling Average Baseline Target values
*************************************************************/
CREATE PROCEDURE [fw].[procFactStatisticSampledPayPeriodBaselineTargetUpdate]
    @targetType tinyint = null,
    @numberOfPayPeriods tinyint = null,
    @departmentIDs nvarchar(max) = null,
	@fiscalYearID int = 0
with recompile
as
	if (@targetType is null) set @targetType = (select Value from pi.SystemSetting where Name = 'Target Basis')
	if (@numberOfPayPeriods is null) set @numberOfPayPeriods = (select Value from pi.SystemSetting where Name = 'Number Of Rolling Average Pay Periods')
	declare @sql varchar(max)

	create table #departments (val int primary key)
	insert into #departments select val from ConvertCSValuesToTable(@departmentIDs, ',')

	create table #payperiods(val smallint primary key, PayCycleID int)
	insert into #payperiods select PayPeriodID, PayCycleID from fw.DimPayPeriod where FiscalYearIDSecond = @fiscalYearID

	create table #PayPeriodsPriorYear (val smallint primary key, PayCycleID int)
	insert into #PayPeriodsPriorYear select PayPeriodID, PayCycleID from fw.DimPayPeriod where FiscalYearIDSecond = @fiscalYearID-1
	
	create table #temp
	(
		DepartmentID int,
		AccountID int,
		PayPeriodID smallint,
		Units decimal (18, 6)
	)

	if (@targetType = 10) begin --Rolling Average
		IF OBJECT_ID('tempdb..#fullscope') IS NOT NULL DROP TABLE #fullscope
		IF OBJECT_ID('tempdb..#tempSortedPayPeriods') IS NOT NULL DROP TABLE #tempSortedPayPeriods
		SELECT PayCycleID, PayPeriodID, SortOrder INTO #tempSortedPayPeriods FROM pi.viewPayPeriodsSortedInPayCycles

	IF @fiscalYearID = 0 BEGIN
		set @sql = '
		insert into #temp (DepartmentID, AccountID, PayPeriodID, Units)
		select DepartmentID, AccountID, PayPeriodID, isnull(Units,0.0) 
		FROM (
			select FullScope.DepartmentID, FullScope.AccountID, FullScope.PayPeriodID,
			Units = ISNULL((Sum(Units) over(PARTITION BY DepartmentID, AccountID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfPayPeriods as nvarchar(2))+', 0)
			FROM
			(
				select DepartmentID, AccountID, PayPeriodID, /*records for months, which are absent in current year, but exist at least one month*/
						SUM(Units) as Units
				FROM  (
						SELECT /*recods for months which are present in current year*/
							p.DepartmentID, p.AccountID, p.PayPeriodID,
							p.Units
						FROM #StatisticSampledPayPeriod p
						where TimeClassID = 1 and isSystemGenerated = 0
					UNION ALL
						SELECT /*combination of all for key columns months for current year*/
								p.DepartmentID, p.AccountID, dpp.PayPeriodID,
								0 AS Units
						FROM #StatisticSampledPayPeriod p
						inner join #tempSortedPayPeriods pp on pp.PayPeriodID = p.PayPeriodID
						FULL join #tempSortedPayPeriods dpp on dpp.PayCycleID = pp.PayCycleID
						where dpp.SortOrder - pp.SortOrder between 1 and '+cast(@numberOfPayPeriods as nvarchar(2))+'
						and  p.TimeClassID = 1 and p.isSystemGenerated = 0
					) AllCombinations
					GROUP BY DepartmentID, AccountID, PayPeriodID
			) FullScope
			inner join #tempSortedPayPeriods t on t.PayPeriodID = FullScope.PayPeriodID
		) FinalDataset
		WHERE Units is not null'
		END
	ELSE BEGIN  -- @fiscalYearID != 0
		IF OBJECT_ID('tempdb..#PayPeriodsAllScope') IS NOT NULL DROP TABLE #PayPeriodsAllScope
		select * into #PayPeriodsAllScope from #payperiods

		insert into #PayPeriodsAllScope
		select pp.PayPeriodID, pp.PayCycleID
		from fw.DimPayPeriod pp
		inner join #tempSortedPayPeriods t on t.PayPeriodID = pp.PayPeriodID
		inner join
		(
			select s.PayCycleID, MIN(s.SortOrder-@numberOfPayPeriods) as MinSortOrder, MIN(s.SortOrder -1) as MaxSortOrder
			from #payperiods pp
			inner join #tempSortedPayPeriods s on s.PayPeriodID = pp.val
			group by s.PayCycleID
		) r on r.PayCycleID = pp.PayCycleID and t.SortOrder between MinSortOrder and MaxSortOrder

		set @sql = '
			select C.DepartmentID, C.AccountID, C.PayPeriodID, /*records for months, which are absent in current year, but exist at least one month*/
				SUM(C.Units) as Units
			into #fullscope
			FROM (
				SELECT /*recods for months which are present in current year*/
					p.DepartmentID, p.AccountID, p.PayPeriodID,
					p.Units
				FROM #StatisticSampledPayPeriod p /*table contains only this particular actuals (filtered by Depts, Year) no need for additional filters*/
				where TimeClassID = 1 and isSystemGenerated = 0
					
				UNION ALL
					
				SELECT /*recods for months which are present in current year*/
					p.DepartmentID, p.AccountID, p.PayPeriodID,
					p.Units
				FROM fw.FactStatisticSampledPayPeriod p
				inner join #PayPeriodsPriorYear pppy on p.PayPeriodID = pppy.val /*filtering only values for "prior year", in fact periods, which affects current year*/
				'+ case when @departmentIDs IS NULL then '' else ' INNER JOIN #departments dpt on dpt.val = p.DepartmentID' end+'
				where p.TimeClassID = 1 and p.isSystemGenerated = 0
					
				UNION ALL
					
				SELECT /*combination of all for key columns months for current year*/
						p.DepartmentID, p.AccountID, dpp.val as PayPeriodID,
						0 AS Units
				FROM #StatisticSampledPayPeriod p
				inner join fw.DimPayPeriod pp on pp.PayPeriodID = p.PayPeriodID
				FULL join #PayPeriodsAllScope dpp on dpp.PayCycleID = pp.PayCycleID
				where p.TimeClassID = 1 and p.isSystemGenerated = 0
					
				UNION ALL
					
				SELECT /*combination of all for key columns months for current year*/
						p.DepartmentID, p.AccountID, dpp.PayPeriodID,
						0 AS Units
				FROM fw.FactStatisticSampledPayPeriod p
				INNER JOIN #PayPeriodsPriorYear pppy on p.PayPeriodID = pppy.val /*filtering only values for "prior year", in fact periods, which affects current year*/
				INNER JOIN fw.DimPayPeriod dpp ON dpp.PayCycleID = pppy.PayCycleID
				'+ case when @departmentIDs IS NULL then '' else ' INNER JOIN #departments dpt on dpt.val = p.DepartmentID' end
					+' where p.TimeClassID = 1 and p.isSystemGenerated = 0
			) C
			inner join #PayPeriodsAllScope P on p.val = C.PayPeriodID
			GROUP BY C.DepartmentID, C.AccountID, C.PayPeriodID

			insert into #temp (DepartmentID, AccountID, PayPeriodID, Units)
			select DepartmentID, AccountID, PayPeriodID, isnull(Units,0.0) 
			FROM
			(
				select f.DepartmentID, f.AccountID, f.PayPeriodID,
				Units = ISNULL((Sum(f.Units) over(PARTITION BY f.DepartmentID, f.AccountID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfPayPeriods as nvarchar(2))+', 0)
				FROM #fullscope f
				inner join #tempSortedPayPeriods t on t.PayPeriodID = f.PayPeriodID
			) FinalDataset
			INNER JOIN #PayPeriods PP on pp.Val = FinalDataset.PayPeriodID
			WHERE Units is not null'
	END
	exec(@sql)
	IF OBJECT_ID('tempdb..#fullscope') IS NOT NULL DROP TABLE #fullscope

	end else begin --Budget
		insert into #temp (DepartmentID, AccountID, PayPeriodID, Units)
		select DepartmentID, AccountID, PayPeriodID, Units
		from #StatisticSampledPayPeriod
		where TimeClassID = 2 and (@departmentIDs is null or DepartmentID in (select val from #departments)) and (@fiscalYearID = 0 or PayPeriodID in(select val from #payperiods))
	end

	insert into #StatisticSampledPayPeriod (DepartmentID, AccountID,PayPeriodID, TimeClassID, Units)
	select source.DepartmentID, source.AccountID, source.PayPeriodID, 20, source.Units from #temp source
	where (@fiscalYearID = 0 or PayPeriodID in(select val from #payperiods)) and Units !=0
	
	
	drop table #temp
	drop table #departments
	drop table #payperiods
	drop table #PayPeriodsPriorYear
	IF OBJECT_ID('tempdb..#PayPeriodsAllScope') IS NOT NULL DROP TABLE #PayPeriodsAllScope
	IF OBJECT_ID('tempdb..#tempSortedPayPeriods') IS NOT NULL DROP TABLE #tempSortedPayPeriods
GO


---------------------------------------------

-- fw.procFactStatisticSecondarySampledBaselineTargetUpdate
/**************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI			Description
** 1		2017-03-07	gforeman	B-14693		Added year filter
** 2		2017-03-28	ipetriv		D-05641		Logic for Prior and Actual was changed to simply copy actuals from previous year
** 3		2017-04-05 	ipetriv		D-05789		Changed algorithm for rolling average calculation
** 4		2017-05-29 	ipetriv		B-15994		Refactored sampling process and implemented using of staging tables
** 5		2017-06-15	IP			B-15086		Modify SP to use unique temp table
** 6		2017-07-20	IP			D-06150		Fixed updating values for Target Type = 2
** 7		2018-05-16	IP			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 8		2018-05-16	KF			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 9		2018-06-01	IP 			D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values (one year part)
** 10		2018-06-05	IP 			TK-58643 added filetr for current year only and non-zero records in output
*************************************************************/
CREATE proc [fw].[procFactStatisticSecondarySampledBaselineTargetUpdate]
    @targetType int = null,
    @numberOfMonths int = null,
	@fiscalYearID int = 0

as
	if (@targetType is null) set @targetType = (select Value from mr.SystemSetting where Name = 'Target Basis')
	if (@numberOfMonths is null) set @numberOfMonths = (select Value from mr.SystemSetting where Name = 'Number Of Rolling Average Months')
	declare @sql varchar(max)
	declare @maxCalculatingFiscalYear int = (select max(FiscalYearID) from #StatisticSecondarySampledMonthlyStaging)
	create table #temp
	(
		DepartmentID int,
		AccountID int,
		FiscalYearID smallint,
		FiscalMonthID tinyint,
		Amount decimal (19, 4)
	)

	if (@targetType = 1) begin --Prior Year Actual
		insert into #temp
		select d.DepartmentID, d.AccountID, d.FiscalYearID+1, d.FiscalMonthID, d.Amount
		from fw.FactStatisticSecondarySampledMonthly d where  d.TimeClassID = 1 and (@fiscalYearID = 0 or d.FiscalYearID = @fiscalYearID-1)
	end else if (@targetType = 10) begin --Rolling Average
		IF @fiscalYearID = 0
		set @sql = '
		insert into #temp
		select DepartmentID, AccountID, FiscalYearID, FiscalMonthID,isnull(Amount,0.0) FROM (
		select FullScope.DepartmentID, FullScope.AccountID, FullScope.FiscalYearID, m.FiscalMonthID,
		Amount	= ISNULL((Sum(Amount)   over(PARTITION BY DepartmentID,AccountID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0)
		FROM (
			select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/
					AccountID,
					FiscalYearID,
					SortOrder,
					SUM(Amount) as Amount
			FROM  (
					SELECT /*recods for months which are present in current year*/
						DepartmentID,
						AccountID,
						FiscalYearID,
						m.SortOrder,
						Amount
					FROM #StatisticSecondarySampledMonthlyStaging p
					JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
					where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0
					UNION ALL
					SELECT /*combination of all for key columns months for current year*/
							p.DepartmentID,
							p.AccountID,
							fy.FiscalYearID,
							m.SortOrder,
							0 AS Amount
					FROM #StatisticSecondarySampledMonthlyStaging p
					CROSS JOIN fw.DimFiscalMonth m
					CROSS JOIN (select FiscalYearID from fw.DimFiscalYear dm) fy
					where m.FiscalMonthID <> 0 and p.TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0
				) AllCombinations
				GROUP BY DepartmentID,AccountID,FiscalYearID,SortOrder
	) FullScope
	JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder
	) FinalDataset
	WHERE Amount is not null
	AND FiscalYearID <='+cast(@maxCalculatingFiscalYear as nvarchar(4))
	ELSE 
	SET @sql = '
		insert into #temp
		select DepartmentID, AccountID, FiscalYearID, FiscalMonthID,isnull(Amount,0.0) FROM (
		select FullScope.DepartmentID, FullScope.AccountID, FullScope.FiscalYearID, m.FiscalMonthID,
		Amount	= ISNULL((Sum(Amount)   over(PARTITION BY DepartmentID,AccountID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0)
		FROM (
			select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/
					AccountID,
					FiscalYearID,
					SortOrder,
					SUM(Amount) as Amount
			FROM  (
					SELECT /*recods for months which are present in current year*/
						DepartmentID,
						AccountID,
						FiscalYearID,
						m.SortOrder,
						Amount
					FROM #StatisticSecondarySampledMonthlyStaging p
					JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
					where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0
				UNION ALL
					SELECT /*combination of all for key columns months for current year*/
							DepartmentID,
							AccountID,
							FiscalYearID,
							m.SortOrder,
							Amount
					FROM fw.FactStatisticSecondarySampledMonthly p
					JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID
					where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0
					and FiscalYearID = '+cast(@fiscalYearID-1 as nvarchar(4)) +'
				UNION ALL
					SELECT /*combination of all for key columns months for current year*/
							DepartmentID,
							AccountID,
							FiscalYearID,
							m.SortOrder,
							0 AS Amount
					FROM #StatisticSecondarySampledMonthlyStaging  p
					CROSS APPLY fw.DimFiscalMonth m
					where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0
					and FiscalYearID = '+cast(@fiscalYearID as nvarchar(4)) +'
				UNION ALL
					SELECT /*combination of all for key columns months for current year*/
						p.DepartmentID,
						p.AccountID,
						fy.FiscalYearID,
						m.SortOrder,
						0 AS Amount
					FROM fw.FactStatisticSecondarySampledMonthly p
					CROSS JOIN fw.DimFiscalMonth m
					CROSS JOIN (select FiscalYearID 
								from fw.DimFiscalYear dm 
								where dm.FiscalYearID in ('+cast(@fiscalYearID-1 as nvarchar(4))+','+cast(@fiscalYearID as nvarchar(4))+')'+'
								) fy
					where m.FiscalMonthID <> 0 and p.TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 and p.FiscalYearID = '+cast(@fiscalYearID-1 as nvarchar(4))+'
				) AllCombinations
				GROUP BY DepartmentID,AccountID,FiscalYearID,SortOrder
	) FullScope
	JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder
	) FinalDataset
	WHERE Amount is not null
	AND FiscalYearID ='+cast(@fiscalYearID as nvarchar(4))
	exec (@sql)
	end else begin --Budget
		insert into #temp
		select DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Amount
		from #StatisticSecondarySampledMonthlyStaging
		where TimeClassID = 2 and (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID)
	end
    
	INSERT INTO #StatisticSecondarySampledMonthlyStaging (DepartmentID,AccountID,FiscalYearID,FiscalMonthID,Amount,TimeClassID) 
	SELECT DepartmentID,AccountID,FiscalYearID,FiscalMonthID,Amount,20 FROM #temp
	WHERE (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID) and Amount !=0

	exec [dbo].[procRollingDeleteOnTable] 'fw', 'FactStatisticSecondarySampledMonthly', 'RowID', 'fw.FactStatisticSecondarySampledMonthly', 'TimeClassID = 20 and IsDeleted = 1', 10000, 0.5, 0

	drop table #temp
GO


---------------------------------------------

-- fw.procFillFactPatientBillingLineItemGroupedCache
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI			Description
** 1		2022-10-13	KF			JAZZ-44078	Charge Based Statistics Modals Performance Improvement
** 2		2022-02-01	KF			JAZZ-48413	Charge Based Statistics Modals Performance Improvement- Bug Fixing
*************************************************************/
CREATE PROC [fw].[procFillFactPatientBillingLineItemGroupedCache]
AS
	-- Truncate table, drop indexes
	TRUNCATE TABLE fw.FactPatientBillingLineItemGroupedCache

	EXEC dbo.procSysDropIndex @schema = 'fw', @table = 'FactPatientBillingLineItemGroupedCache', @indexName = 'CORE_PostDateID_DepartmentID_ChargeCodeID_PatientTypeRollupID_inc'
	EXEC dbo.procSysDropIndex @schema = 'fw', @table = 'FactPatientBillingLineItemGroupedCache', @indexName = 'CORE_ServiceDateID_DepartmentID_ChargeCodeID_PatientTypeRollupID_inc'

	-- Split by batches
	DECLARE @batchSize INT = 200000000

	IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments
	CREATE TABLE #inputDepartments (DepartmentID INT, RecordsCount INT, BatchID INT)

	DECLARE
		@fromClause nvarchar(max) = '
	dss.FactPatientBillingLineItemDetail fd
	INNER JOIN fw.DimDepartment d ON d.DepartmentID = fd.DepartmentID',
		@whereClause nvarchar(max) = '',
		@declareParameters nvarchar(max) = ''
		
	INSERT INTO #inputDepartments
	EXEC dbo.procGetInputDataByBatches
	  	@batchSize = @batchSize,
		@columnName = 'DepartmentID',
		@tableAlias = 'fd',
		@fromClause = @fromClause,
		@whereClause = @whereClause,
		@declareParameters = @declareParameters,
		@isDebug = 0

	DECLARE @BatchID INT, @MaxBatchID INT
	SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

	-- Loop thru batches and insert data
	SET @BatchID = 1
	WHILE @BatchID <= @MaxBatchID
	BEGIN
		INSERT INTO fw.FactPatientBillingLineItemGroupedCache (DepartmentID, ChargeCodeID, PatientTypeRollupID, ServiceDateID, PostDateID, FiscalYearID, UnitsOfService)
		SELECT fd.DepartmentID, fd.ChargeCodeId, pt.PatientTypeRollupId, fd.ServiceDateId, fd.PostDateID, fd.FiscalYearID, COALESCE(SUM(fd.UnitsOfService), 0.0E0) AS UnitsOfService
		FROM dss.FactPatientBillingLineItemDetail fd
		INNER JOIN clientdss.FactPatientEncounterSummary fs ON fs.EncounterID = fd.EncounterID
		INNER JOIN fw.DimPatientType pt ON pt.PatientTypeID = fs.PatientTypeID
		INNER JOIN fw.DimChargeCode c ON c.ChargeCodeID = fd.ChargeCodeID
		INNER JOIN fw.DimPatientTypeRollup ptr ON ptr.PatientTypeRollupId = pt.PatientTypeRollupId
		INNER JOIN #inputDepartments ID ON ID.DepartmentID = fd.DepartmentID
		WHERE ID.BatchID = @BatchID
		GROUP BY fd.DepartmentID, fd.ChargeCodeId, pt.PatientTypeRollupId, fd.ServiceDateId, fd.PostDateID, fd.FiscalYearID
				
		SET @BatchID = @BatchID + 1
	END

	-- Recreate indexes
	CREATE INDEX CORE_PostDateID_DepartmentID_ChargeCodeID_PatientTypeRollupID_inc 
	ON fw.FactPatientBillingLineItemGroupedCache (PostDateID, DepartmentID, ChargeCodeID, PatientTypeRollupID)
		INCLUDE(UnitsOfService)

	CREATE INDEX CORE_ServiceDateID_DepartmentID_ChargeCodeID_PatientTypeRollupID_inc
	ON fw.FactPatientBillingLineItemGroupedCache (ServiceDateID, DepartmentID, ChargeCodeID, PatientTypeRollupID)
		INCLUDE(UnitsOfService)
	
	IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments
	IF OBJECT_ID('tempdb..#transactions') IS NOT NULL DROP TABLE #transactions
GO


---------------------------------------------

-- fw.procFlexProviderStatisticsMonthly
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
** 1		2018-06-27	KZ			B-19363	MR - Provider flexing - flexing
** 2		2018-06-28	KF			B-19363	MR - Provider flexing - flexing
** 3		2018-07-10	KZ			B-20342	MR - Update provider sampling to be in the appropriate format
*************************************************************/
CREATE PROCEDURE  [fw].[procFlexProviderStatisticsMonthly]
	@fiscalYearID INT = 0,
	@departmentIDs nvarchar(max) = null
AS

declare @minYear int = @fiscalYearID - 1
declare @maxYear int = @fiscalYearID
if (@minYear = 0 or @maxYear = 0) begin
    select @minYear = min(FiscalYearID) from [fw].[FactProviderSampledMonthly_Pivoted]
    select @maxYear = max(FiscalYearID) from [fw].[FactProviderSampledMonthly_Pivoted]
end

declare @currentYear int
select @currentYear = Setting from [dbo].[DBSetting] where Name='Current_GL_YearID'

declare @currentMonth int
select @currentMonth = Setting from [dbo].[DBSetting] where Name='Current_GL_MonthID'

declare @month int
select @month = SortOrder + @currentYear * 12 from [fw].[DimFiscalMonth] where FiscalMonthID=@currentMonth

DELETE FROM [fw].[FactProviderSampledMonthly_Pivoted] WHERE TimeClassID = 4 AND (FiscalYearID between @minYear AND @maxYear)
AND (@departmentIDs is null or DepartmentID in (select val from ConvertCSValuesToTable(@departmentIDs, ',')))

INSERT INTO [fw].[FactProviderSampledMonthly_Pivoted] ([DepartmentID], [ProviderID], [OBForecastDetailID], [FiscalYearID], [FiscalMonthID], [TimeClassID], [Volume])
SELECT F.[DepartmentID], F.[ProviderID], F.[OBForecastDetailID], F.[FiscalYearID], F.[FiscalMonthID], 4 as [TimeClassID], 
    iif(F.FiscalYearID * 12 + max(M.SortOrder) <= @month, 
        sum(
            case when F.TimeClassID = 1 then F.[Volume] * cast(FD.IsVariable as decimal(18, 6)) * cast(D.IsVariable as decimal(18, 6)) * cast(P.IsVariable as decimal(18, 6))
            when F.TimeClassID = 20 then F.[Volume] * (1.0 - (cast(FD.IsVariable as decimal(18, 6)) * cast(D.IsVariable as decimal(18, 6)) * cast(P.IsVariable as decimal(18, 6))))
            else 0 end)
        , coalesce(sum(case when F.TimeClassID = 20 then F.[Volume] end), 0)) as [Amount]
FROM [fw].[FactProviderSampledMonthly_Pivoted] F
INNER JOIN [fw].[DimDepartment] D on D.DepartmentID = F.DepartmentID 
INNER JOIN [ob].[DimOBForecastDetail] FD on FD.OBForecastDetailID = F.OBForecastDetailID
INNER JOIN [fw].[DimProvider] P on P.ProviderID = F.ProviderID
INNER JOIN [fw].[DimFiscalMonth] M on M.FiscalMonthID = F.FiscalMonthID
WHERE F.IsDeleted = 0 and F.TimeClassID in(1, 20) AND (FiscalYearID between @minYear AND @maxYear)
AND (@departmentIDs is null or F.DepartmentID in (select val from ConvertCSValuesToTable(@departmentIDs, ',')))
GROUP BY F.[DepartmentID], F.[ProviderID], F.[OBForecastDetailID], F.[FiscalYearID], F.[FiscalMonthID]
GO


---------------------------------------------

-- fw.procFlexStatisticsDaily
CREATE PROCEDURE [fw].[procFlexStatisticsDaily]
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
** 1		2019-03-19	KF			D-08059	PR | Daily and pay period screens are calculating targets differently
** 2		2022-07-05	HV			JAZZ-39736	PR Metrics Definition - Statistics Daily Flexing
** 3		2022-08-02	HV			JAZZ-41284	Daily flexing - Payroll Hours and Dollars
** 4		2022-08-30	KF			JAZZ-42568	Flex UOS not accounting for account variability for daily PR
** 5		2024-02-23	HV			JAZZ-67657	[RowId] Convert fw.FactStatisticSampledDaily.Rowid to bigint
*************************************************************/
	@FiscalYearID INT = 0,
	@DepartmentIDs NVARCHAR(MAX) = null,
	@isOnlyOnePayPeriod BIT = 0
AS

DECLARE @currentDateOverride nvarchar(max) = (SELECT Value FROM [pi].[SystemSetting] WHERE Name = 'Current Date Override')
DECLARE @currentDate date =  CASE 
								WHEN @currentDateOverride = '' THEN CAST(GETDATE() AS DATE)
								ELSE CAST (@currentDateOverride AS date) 
								END
DECLARE @yesterdayDate date = DATEADD(DAY, - 1, @currentDate) 
DECLARE @yesterdayDateID int = (SELECT DateID FROM fw.DimDate WHERE CalendarDateTime = @yesterdayDate)

IF OBJECT_ID('tempdb..#DailyCalcPeriodsScope') IS NOT NULL DROP TABLE #DailyCalcPeriodsScope
CREATE TABLE #DailyCalcPeriodsScope (PayPeriodID int primary key,PayCycleID int,PeriodStartCalendarDate date,PeriodEndCalendarDate date)

INSERT INTO #DailyCalcPeriodsScope (PayPeriodID,PayCycleID,PeriodStartCalendarDate,PeriodEndCalendarDate) 
SELECT PayPeriodID,PayCycleID,PeriodStartCalendarDate,PeriodEndCalendarDate
FROM fw.DimPayPeriod
WHERE 
	(@isOnlyOnePayPeriod = 1 and @yesterdayDate BETWEEN PeriodStartCalendarDate and PeriodEndCalendarDate)
	or
	(@isOnlyOnePayPeriod = 0 and (FiscalYearIDSecond = @fiscalYearID or @fiscalYearID = 0))

IF OBJECT_ID('tempdb..#DepartmentIDs') IS NOT NULL DROP TABLE #DepartmentIDs
CREATE TABLE #DepartmentIDs (val int primary key)
INSERT INTO #DepartmentIDs select val from ConvertCSValuesToTable(@departmentIDs, ',')

DECLARE @FromClause NVARCHAR(MAX) = 'fw.FactStatisticSampledDaily F INNER JOIN #DailyCalcPeriodsScope dcp on dcp.PayPeriodID = F.PayPeriodID'
DECLARE @WhereClause NVARCHAR(MAX) = 'F.TimeClassID = 4'

IF(@DepartmentIDs IS NOT NULL)
BEGIN
  SET @FromClause = @fromClause + ' INNER JOIN #DepartmentIDs TD ON TD.val = F.DepartmentID'
END

exec [dbo].[procRollingDeleteOnTable]
		    @tableSchema = 'fw',
			@tableName = 'FactStatisticSampledDaily',
			@identityColumn = 'RowID',
			@fromClause = @FromClause,
			@whereClause = @WhereClause,
			@deleteRecordCount = 10000000,
			@truncateThreshold = 0.5,
			@isPrintingStatement = 0

DECLARE @nextRowID BIGINT
SELECT @nextRowID = ISNULL((SELECT MAX(RowID) FROM fw.FactStatisticSampledDaily), 1)
DBCC CHECKIDENT('fw.FactStatisticSampledDaily','RESEED', @nextRowID);

DECLARE @BatchSize INT = 30000000

IF OBJECT_ID('tempdb..#inputPayPeriods') IS NOT NULL DROP TABLE #inputPayPeriods

SELECT F.PayPeriodID, COUNT(1) AS RecordsCount, 0 AS BatchID INTO #inputPayPeriods
FROM fw.FactStatisticSampledDaily F
INNER JOIN #DailyCalcPeriodsScope dcp on F.PayPeriodID = dcp.PayPeriodID
WHERE F.IsDeleted = 0 AND F.TimeClassID in(1, 20)
GROUP BY F.PayPeriodID

-- Split data into batches
WHILE EXISTS (SELECT TOP 1 1 FROM #inputPayPeriods WHERE BatchID = 0)
BEGIN
	;WITH PayPeriodInfo AS 
	(
		SELECT DM.PayPeriodID, ROW_NUMBER() OVER (ORDER BY DM.PayPeriodID) AS RowNumber, SUM(RecordsCount) OVER (ORDER BY DM.PayPeriodID) AS Total, M.MaxBatchID+1 AS BatchID
		FROM #inputPayPeriods IPP
		INNER JOIN fw.DimPayPeriod DM ON DM.PayPeriodID = IPP.PayPeriodID
		CROSS JOIN (SELECT MAX(BatchID) AS MaxBatchID FROM #inputPayPeriods) M
		WHERE IPP.BatchID = 0
	)
	UPDATE IPP
	SET IPP.BatchID = MI.BatchID
	FROM #inputPayPeriods IPP
	INNER JOIN PayPeriodInfo MI ON MI.PayPeriodID = IPP.PayPeriodID
	WHERE MI.Total <= @BatchSize OR MI.RowNumber = 1
END

DECLARE @BatchID INT, @MaxBatchID INT
SELECT @MaxBatchID = MAX(BatchID) FROM #inputPayPeriods

-- Loop thru batches and insert data
SET @BatchID = 1
WHILE @BatchID <= @MaxBatchID
BEGIN  	

	INSERT INTO fw.FactStatisticSampledDaily (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units)
	SELECT S.DepartmentID, S.AccountID, S.PayPeriodID, S.DateID, S.TimeClassID, S.Units
	FROM
	(
	  SELECT F.DepartmentID, F.AccountID, F.PayPeriodID, F.DateID, 4 AS TimeClassID,
	  CASE 
	  WHEN F.DateID <= @yesterdayDateID 
	  THEN
		SUM(CASE
			WHEN F.TimeClassID = 1 THEN F.Units * A.Variability * CAST(D.IsVariable as decimal(18, 6))
			WHEN F.TimeClassID = 20 THEN F.Units * (1.0 - (A.Variability * CAST(D.IsVariable as decimal(18, 6))))
			ELSE 0
		END)
		ELSE 
		COALESCE(SUM(CASE WHEN F.TimeClassID = 20 THEN F.Units END), 0)
		END
		AS Units
	  FROM fw.FactStatisticSampledDaily F
	  INNER JOIN fw.DimDepartment D on D.DepartmentID = F.DepartmentID
	  INNER JOIN fw.DimAccount A on A.AccountID = F.AccountID
	  INNER JOIN fw.DimDate DD on DD.DateID = F.DateID
	  INNER JOIN #inputPayPeriods IPP ON IPP.PayPeriodID = F.PayPeriodID
	  LEFT JOIN #DepartmentIDs TD ON TD.val = D.DepartmentID
	  WHERE F.IsDeleted = 0 
  		AND F.TimeClassID in(1, 20)
		AND (@DepartmentIDs IS NULL OR TD.val IS NOT NULL)
		AND IPP.BatchID = @BatchID
	  GROUP BY F.DepartmentID, F.AccountID, F.DateID, F.PayPeriodID
	) S

SET @BatchID = @BatchID + 1
END

IF OBJECT_ID('tempdb..#DepartmentIDs') IS NOT NULL DROP TABLE #DepartmentIDs
GO


---------------------------------------------

-- fw.procGLSampledAdjustedTargetMonthlyInsert
/*************************************************************
** Change History
**************************************************************
** CID	Date        Author    	WI			Description
** 1	2017-10-02	IP	    	B-17596		Created 
** 2	2018-11-19	OV			D-06627   fix: GL Dollars Adjusted Target records are not added when there is only Actual data
** 3	2020-02-05	IH			D-08896		Add handling of Units
** 4   2022-08-23   BC        JAZZ-11498  Change Table Variable to Temporary Tables 
*************************************************************/
CREATE PROCEDURE [fw].[procGLSampledAdjustedTargetMonthlyInsert] (@FiscalYearID INT = 0)
AS
BEGIN
	/*
Proposal

If the client is not using flexing, this will be the target plus the efficiency factor
This should work regardless of the target basis (i.e. rolling avg or budget)
The factor will be applied after the inversion
If the factor type is percentage, the adjusted target will be the target*(1+factor)
i.e. if my target is 100 and my factor is 5%, the adjusted target will be 100*(1+0.05)=105
i.e. if my target is 100 and my factor is -5%, the adjusted target will be 100*(1+-0.05)=95
If the factor type is value, the adjusted value will be target + factor
i.e. if my target is 1000 and my factor is 200, the adjusted target will be will be 1000+200=1200
i.e. if my target is 1000 and my factor is -200, the adjusted target will be 1000-200=800
If there is more than one factor impacting a department and account or job code/pay code group combination, then the factors should layer on top of each other based on history order
If an efficiency factor does not exist for a particular account/job code, then the value in the new time class will be either flex or baseline target if flex is not used
This will happen after Flex is calculated
Include integration tests

*/ 	DECLARE @IsFlexingEnabled INT = (
			SELECT VALUE
			FROM [mr].[SystemSetting]
			WHERE NAME = 'Is Target Flexed'
			)

	
	IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE #EfficiencyFactorScope	
	CREATE TABLE #EfficiencyFactorScope (
		EfficiencyFactorGUID [uniqueidentifier] NOT NULL
		,[DepartmentID] [int] NOT NULL
		,[AccountID] [int] NOT NULL
		,[FiscalYearID] [smallint] NOT NULL
		,[FiscalMonthID] [tinyint] NOT NULL
		,Value NUMERIC(25, 6) NOT NULL
		,Type TINYINT
		,FactorType CHAR(1)
		,DateCreated DATETIME
		,UNIQUE CLUSTERED (
			FiscalYearID
			,FiscalMonthID
			,DepartmentID
			,AccountID
			,EfficiencyFactorGUID
			)
		);

 IF EXISTS (SELECT TOP 1 * FROM [mr].[EfficiencyFactor]) BEGIN
		WITH EfficiencyFactorScope
		AS (
			SELECT *
				,rn = ROW_NUMBER() OVER (
					PARTITION BY FiscalYearID
					,FiscalMonthID
					,DepartmentID
					,AccountID
					,EfficiencyFactorGUID ORDER BY FiscalYearID
						,FiscalMonthID
						,DepartmentID
						,AccountID
						,EfficiencyFactorGUID
					)
			FROM (
				SELECT DISTINCT ef.EfficiencyFactorGUID
					,ef.FiscalYearID
					,efgd.FiscalMonthID
					,efd.DepartmentID
					,isnull(efgd.AccountID, da.AccountID) AS AccountID
					,CASE 
						WHEN isnull(efgd.AccountID, - 999) = da.AccountID
							THEN 0
						ELSE efgd.Value
						END AS Value
					,ef.Type
					,ef.FactorType
					,ef.DateCreated
				FROM mr.EfficiencyFactor ef
				INNER JOIN mr.EfficiencyFactorDepartment efd ON ef.EfficiencyFactorGUID = efd.EfficiencyFactorGUID
				INNER JOIN mr.EfficiencyFactorGLDetails efgd ON efgd.EfficiencyFactorGUID = ef.EfficiencyFactorGUID
				LEFT JOIN fw.DimAccount da ON efgd.OBFinancialReportingID = da.OBDollarsFinancialReportingID
					AND efgd.AccountID IS NULL
				LEFT JOIN mr.EfficiencyFactorGLDetails efgd_exist ON efgd.EfficiencyFactorGUID = efgd_exist.EfficiencyFactorGUID
					AND efgd_exist.AccountID = da.AccountID
					AND efgd_exist.FiscalMonthID = efgd.FiscalMonthID
				WHERE (
						@FiscalYearID = ef.FiscalYearID
						OR @FiscalYearID = 0
						)
					AND (
						efgd_exist.AccountID IS NULL
						OR da.AccountID IS NULL
						)
					AND ef.Type = 0
					AND isnull(efgd.AccountID, da.AccountID) IS NOT NULL
				) X
			)
		INSERT INTO #EfficiencyFactorScope (
			EfficiencyFactorGUID
			,[DepartmentID]
			,[AccountID]
			,[FiscalYearID]
			,[FiscalMonthID]
			,Value
			,Type
			,FactorType
			,DateCreated
			)
		SELECT EfficiencyFactorGUID
			,[DepartmentID]
			,[AccountID]
			,[FiscalYearID]
			,[FiscalMonthID]
			,Value
			,Type
			,FactorType
			,DateCreated
		FROM EfficiencyFactorScope
		WHERE RN = 1

		DELETE
		FROM fw.FactGLSampled
		WHERE (
				@FiscalYearID = FiscalYearID
				OR @FiscalYearID = 0
				)
			AND TimeClassID = 22

		INSERT INTO fw.FactGLSampled (
			DepartmentID
			,AccountID
			,FiscalYearID
			,FiscalMonthID
			,TimeClassID
			,IsDeleted
			,Dollars
			,Units
			)
		SELECT DepartmentID
			,AccountID
			,FiscalYearID
			,FiscalMonthID
			,22 AS TimeClassID
			,0 AS IsDeleted
			,SUM(Dollars)
			,SUM(Units)
		FROM (
			SELECT isnull(fact.DepartmentID, ToApply.DepartmentID) AS DepartmentID
				,isnull(fact.AccountID, toApply.AccountID) AS AccountID
				,isnull(fact.FiscalYearID, toApply.FiscalYearID) AS FiscalYearID
				,isnull(fact.FiscalMonthID, toApply.FiscalMonthID) AS FiscalMonthID
				,Dollars = CASE WHEN FactorType = 'P' THEN isnull(Dollars, 0.0) * isnull(Value, 0.0) / 100.00 
						     ELSE isnull(Value, 0.0)
					    END
				,Units = 0.0
			FROM #EfficiencyFactorScope ToApply
			INNER JOIN (
				SELECT DISTINCT DepartmentID
				            	,AccountID
				FROM fw.FactGLSampled
				) GenCand ON GenCand.DepartmentID = ToApply.DepartmentID
				AND GenCand.AccountID = ToApply.AccountID
			FULL JOIN (select DepartmentID
				, AccountID
				, FiscalYearID
				, FiscalMonthID
				, SUM(CASE WHEN (@IsFlexingEnabled = 1 and isnull(fact.TimeClassID, 0) = 4) OR (isnull(fact.TimeClassID, 0) = 20 AND @IsFlexingEnabled = 0) 
				         THEN isnull(fact.Dollars,0.0) 
						 ELSE 0.0
					END) as Dollars
				FROM fw.FactGLSampled fact
				WHERE fact.TimeClassID in (1, 4, 20) 
					 and fact.FiscalYearID = @FiscalYearID OR @FiscalYearID = 0					
				GROUP BY DepartmentID
						,AccountID
						,FiscalYearID
						,FiscalMonthID ) fact  ON fact.DepartmentID = ToApply.DepartmentID
				AND fact.AccountID = ToApply.AccountID
				AND fact.FiscalYearID = ToApply.FiscalYearID
				AND fact.FiscalMonthID = ToApply.FiscalMonthID
				where value is not null  
						
			UNION ALL
			
			SELECT DepartmentID
				,AccountID
				,FiscalYearID
				,FiscalMonthID
				,CASE WHEN (@IsFlexingEnabled = 1 and isnull(fact.TimeClassID, 0) = 4) OR (isnull(fact.TimeClassID, 0) = 20 AND @IsFlexingEnabled = 0)
				      THEN isnull(fact.Dollars,0.0)
					  ELSE 0.0 
			     END as Dollars
				,CASE WHEN (@IsFlexingEnabled = 1 and isnull(fact.TimeClassID, 0) = 4) OR (isnull(fact.TimeClassID, 0) = 20 AND @IsFlexingEnabled = 0)
					THEN fact.Units
					ELSE 0.0 
			     END as Units
			FROM fw.FactGLSampled fact
			WHERE fact.FiscalYearID = @FiscalYearID	OR @FiscalYearID = 0
		) X WHERE x.Dollars != 0 OR x.Units != 0
		GROUP BY DepartmentID
						,AccountID
						,FiscalYearID
						,FiscalMonthID
						

		EXEC [fw].[procFactMonthlyYTDPriorYearUpdate] @factTableName = 'fw.FactGLSampled'
			,@keyNameCSV = 'AccountID'
			,@measureNameCSV = 'Dollars,Units'
			,@fiscalYearID = @FiscalYearID
			,@timeClassID = 22
			,@isDebugOnly = 0
	END
END
IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE  #EfficiencyFactorScope
GO


---------------------------------------------

-- fw.procGLSampledFlexInsert
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI			Description
** 1		5/10/16		NL			B-11692	Including FiscalYearID in delete
** 2		10/38/17	GF			D-05545	Move duplicate record handling from YTD into sampling + general cleanup
*************************************************************/
CREATE PROC [fw].[procGLSampledFlexInsert]
	@fiscalyearid smallint
with recompile
as
   --delete existing data
	WHILE EXISTS(SELECT NULL FROM fw.FactGLSampled (nolock) WHERE FiscalYearID = @fiscalYearID and TimeClassID = 4) BEGIN
		DELETE TOP (10000) fw.FactGLSampled WHERE FiscalYearID = @fiscalYearID and TimeClassID = 4
	END

	--push new data to fact table
	INSERT INTO [fw].[FactGLSampled]([DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID], [Units], [Dollars])
	SELECT 
		GL.DepartmentID,
		GL.AccountID,
		GL.FiscalYearID,
		GL.FiscalMonthID,
		4,
		SUM(0) as Units,
		SUM(CASE 
			WHEN acc.Inversion = -1 THEN gl.value * -1
			ELSE gl.value
		END) AS Dollars
	FROM 
		[int].[FactGL] gl
		INNER JOIN [fw].[DimAccount] acc on acc.AccountCode = gl.AccountCode
	WHERE
		gl.TimeClassID = 2
		AND gl.FiscalYearID = @fiscalyearid
		AND (gl.value != 0)
	GROUP BY
		gl.DepartmentID,
		gl.AccountID,
		gl.FiscalYearID,
		gl.FiscalMonthID,
		gl.TimeClassID

	--run calculations
	exec fw.procFactMonthlyMergeDuplicates 'fw.FactGLSampled', 'AccountID', 'Dollars,Units', @fiscalYearID, 4, 0
	exec fw.procFactMonthlyYTDPriorYearUpdate 'fw.FactGLSampled', 'AccountID', 'Dollars,Units', @fiscalYearID, 4, 0
GO


---------------------------------------------

-- fw.procGLSampledInsert
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2014-01-13	AKK		D-01370	Fixing order of operations for WHEN condition
** 2		2014-09-30	JG				Kris updated proc to optimize performance
** 3		2015-07-15	NL		D-02813	Removing parameter from YTD call
** 4		2016-12-27	AK		D-05183	Added IsSystemGenerated reset
** 5		2017-02-20	GF		D-05545	Move duplicate record handling from YTD into sampling + general cleanup
** 6		2017-02-21	GF		D-05545	Add debug flag to disable output for standard run
** 7		2020-02-06	KF		D-08896	FP/ MR / Flexing / Drivers - MR GL Hours Flexing doesn't work
*************************************************************/
CREATE proc [fw].[procGLSampledInsert]
	@fiscalyearid smallint,
	@timeclassid tinyint,
	@isDebug bit = 0
with recompile
as
	--this proc is obsolete, call All instead
	exec fw.procGLSampledInsertAll @fiscalyearid, @isDebug
GO


---------------------------------------------

-- fw.procGLSampledInsertAll
/**************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		 Description
** 1		2017-07-05	IP			D-06023	 Changing columns size to support values over 1 trillion
** 2		2017-07-19	IP			TK-45395 Fixed conditions of merge statement (include isSystemGenerated column)
** 3		2018-01-12	IP			TK-53108 Fixed conditions of merge statement (include TimeClassID = 12 to target)
** 4		2018-01-12	IP			TK-53108 Fixed conditions of merge statement (include TimeClassID = 4 to target and source)
** 5		2018-02-01	IP			TK-53658 Re-applied stored procedure
** 6		2018-02-14 	GF					 Apply account inversion fix
** 7        2019-02-05  OV          D-07814  Optimize the proc to do truncate/insert for each year where @fiscalYearID = 0
** 8		2020-02-05	KF			D-08896  FP/ MR / Flexing / Drivers - MR GL Hours Flexing doesn't work
** 9		2020-02-18	KF			B-26204  MR | GL Hour Flexing
** 10		2021-11-11	HV			JAZZ-28155  Remove MR 3.0 Flag and all associated code
** 11		2023-09-14	BS			JAZZ-55750 Remove filter to allow other time classes in MR reporting
** 12		2024-06-04	ishah		JAZZ-61244 [TrLog][High] Bug - Run Management Reporting Monthly Process (MR Sampling, all years run): Task failed on Inserting GL Sampled.
*************************************************************/

CREATE PROC [fw].[procGLSampledInsertAll]
	@fiscalYearID smallint = 0,
	@isDebug bit = 0

as
print 'Starting calculating staging table --- '+convert(varchar(20),GETDATE(),113) 
	IF OBJECT_ID('tempdb..#FactGLStagingValue') IS NOT NULL DROP TABLE #FactGLStagingValue
	IF OBJECT_ID('tempdb..#FactGLStaging') IS NOT NULL DROP TABLE #FactGLStaging
	IF OBJECT_ID('tempdb..#StatisticSampledMonthlyStaging') IS NOT NULL DROP TABLE #StatisticSampledMonthlyStaging
	IF OBJECT_ID('fw.FactGLStagingWithCalcs') IS NOT NULL  DROP TABLE fw.FactGLStagingWithCalcs
	IF OBJECT_ID('tempdb..#SummaryOfChanges') IS NOT NULL DROP TABLE #SummaryOfChanges

	exec client.procGLSampledInsertPreprocess
	--push new data to fact table
	CREATE TABLE #SummaryOfChanges (Change VARCHAR(20), FiscalYearID smallint, TimeClassID tinyint, IsDeleted bit);

	CREATE TABLE #FactGLStagingValue (
		DepartmentID int, 
		AccountID int, 
		FiscalYearID int, 
		FiscalMonthID int, 
		TimeClassID int,
		Amount decimal(21,6), 
		ApplyDate datetime, 
		Src varchar(max), 
		UNIQUE NONCLUSTERED (DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID)
	)

	exec fw.procPrepareGL @fiscalYearID
	
	CREATE TABLE #FactGLStaging (RowID bigint identity(1,1), DepartmentID int, AccountID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Units decimal(21,6), Dollars decimal(21,6), FTEs decimal(21,6),isDeleted bit default 0, isSystemGenerated bit default 0)
	
	DECLARE @batchSize INT	

	IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments
	CREATE TABLE #inputDepartments (DepartmentID INT, RecordsCount INT, BatchID INT)

	-- Split by batches
	EXEC mr.procGetIntBatchSize
		@DefaultBatchSize = 30000000,
		@ResultBatchSize = @batchSize OUTPUT
	
	DECLARE @fromClause nvarchar(max), @whereClause nvarchar(max)
	
	SET @fromClause = '
	(
	select 
			GL.DepartmentID,
			GL.AccountID,
			GL.FiscalYearID,
			GL.FiscalMonthID,
			GL.TimeClassID
	from 
			#FactGLStagingValue GL
			inner join fw.DimAccount A on A.AccountID = GL.AccountID
	where
			gl.Amount != 0
	group by
			GL.DepartmentID,
			GL.AccountID,
			GL.FiscalYearID,
			GL.FiscalMonthID,
			GL.TimeClassID
	) X
	'

	INSERT INTO #inputDepartments
	EXEC dbo.procGetInputDataByBatches
	  	@batchSize = @batchSize,
		@columnName = 'DepartmentID',
		@tableAlias = 'X',
		@fromClause = @fromClause,
		@whereClause = '',
		@isDebug = 0
		
	DECLARE @BatchID INT, @MaxBatchID INT
	SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments
	
	SET @BatchID = 1
	WHILE @BatchID <= @MaxBatchID
	BEGIN
		INSERT INTO #FactGLStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Units, Dollars)
		select 
				GL.DepartmentID,
				GL.AccountID,
				GL.FiscalYearID,
				GL.FiscalMonthID,
				GL.TimeClassID,
				sum(0) as Units,
				sum(CASE 
					WHEN A.Inversion = -1 then GL.Amount * -1
					ELSE GL.Amount
				END) AS Dollars
		from 
				#FactGLStagingValue GL
				inner join #inputDepartments IP on IP.DepartmentID = GL.DepartmentID
				inner join fw.DimAccount A on A.AccountID = GL.AccountID
		where
				gl.Amount != 0 and IP.BatchID = @BatchID
		group by
				GL.DepartmentID,
				GL.AccountID,
				GL.FiscalYearID,
				GL.FiscalMonthID,
				GL.TimeClassID

		SET @BatchID = @BatchID + 1	
	END
	
	IF OBJECT_ID('tempdb..#FactGLStagingValue') IS NOT NULL DROP TABLE #FactGLStagingValue

	exec fw.procFactMonthlyMergeDuplicates '#FactGLStaging', 'AccountID', 'Dollars,Units', @fiscalYearID, 0, 0

    -- Statistics Hours to GL Units	
	IF EXISTS (SELECT * FROM mr.SystemSetting WHERE Name = 'Feature Flag Use GL Units' AND Value = 1)
	BEGIN

		CREATE TABLE #StatisticSampledMonthlyStaging (RowID bigint identity(1,1),AccountID int, DepartmentID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Amount decimal(19,4))
		insert into #StatisticSampledMonthlyStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount)
		exec fw.PrepareStatistics @FiscalYearID,0

		SELECT
			STAT.DepartmentID,
			STAT.AccountID,
			STAT.FiscalYearID,
			STAT.FiscalMonthID,
			STAT.TimeClassID,
			SUM(STAT.Amount) AS Units
		INTO #FactGLUnits
		FROM #StatisticSampledMonthlyStaging STAT
		INNER JOIN fw.DimAccount A ON A.AccountID = STAT.AccountID
		WHERE A.OBStatUnitTypeID = 51 --Hours
		GROUP BY
			STAT.DepartmentID,
			STAT.AccountID,
			STAT.FiscalYearID,
			STAT.FiscalMonthID,
			STAT.TimeClassID
		
		SET @fromClause = '
		(
		SELECT GL.DepartmentID, GL.AccountID, GL.FiscalYearID, GL.FiscalMonthID, GL.TimeClassID
		FROM #FactGLStaging GL
		INNER JOIN #FactGLUnits U ON
			U.DepartmentID = GL.DepartmentID AND
			U.AccountID = GL.AccountID AND
			U.FiscalYearID = GL.FiscalYearID AND
			U.FiscalMonthID = GL.FiscalMonthID AND
			U.TimeClassID = GL.TimeClassID
		) X
		'
				
		TRUNCATE TABLE #inputDepartments
		
		INSERT INTO #inputDepartments
		EXEC dbo.procGetInputDataByBatches
			@batchSize = @batchSize,
			@columnName = 'DepartmentID',
			@tableAlias = 'X',
			@fromClause = @fromClause,
			@whereClause = '',
			@isDebug = 0
			
		SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments
		
		SET @BatchID = 1
		WHILE @BatchID <= @MaxBatchID
		BEGIN
			UPDATE GL
			SET GL.Units = U.Units
			FROM #FactGLStaging GL
			INNER JOIN #FactGLUnits U ON
				U.DepartmentID = GL.DepartmentID AND
				U.AccountID = GL.AccountID AND
				U.FiscalYearID = GL.FiscalYearID AND
				U.FiscalMonthID = GL.FiscalMonthID AND
				U.TimeClassID = GL.TimeClassID
			INNER JOIN #inputDepartments IP on IP.DepartmentID = U.DepartmentID
			WHERE IP.BatchID = @BatchID

			SET @BatchID = @BatchID + 1	
		END
		
		SET @fromClause = '
		(
		SELECT U.DepartmentID, U.AccountID, U.FiscalYearID, U.FiscalMonthID, U.TimeClassID, U.Units, 0 as Dollars
		FROM #FactGLUnits U
		LEFT JOIN #FactGLStaging GL ON
			U.DepartmentID = GL.DepartmentID AND
			U.AccountID = GL.AccountID AND
			U.FiscalYearID = GL.FiscalYearID AND
			U.FiscalMonthID = GL.FiscalMonthID AND
			U.TimeClassID = GL.TimeClassID
		WHERE GL.RowID IS NULL
		) X
		'
		
		TRUNCATE TABLE #inputDepartments
				
		INSERT INTO #inputDepartments
		EXEC dbo.procGetInputDataByBatches
			@batchSize = @batchSize,
			@columnName = 'DepartmentID',
			@tableAlias = 'X',
			@fromClause = @fromClause,
			@whereClause = '',
			@isDebug = 0
			
		SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments
		
		SET @BatchID = 1
		WHILE @BatchID <= @MaxBatchID
		BEGIN
			INSERT INTO #FactGLStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Units, Dollars)
			SELECT U.DepartmentID, U.AccountID, U.FiscalYearID, U.FiscalMonthID, U.TimeClassID, U.Units, 0
			FROM #FactGLUnits U
			INNER JOIN #inputDepartments IP on IP.DepartmentID = U.DepartmentID
			LEFT JOIN #FactGLStaging GL ON
				U.DepartmentID = GL.DepartmentID AND
				U.AccountID = GL.AccountID AND
				U.FiscalYearID = GL.FiscalYearID AND
				U.FiscalMonthID = GL.FiscalMonthID AND
				U.TimeClassID = GL.TimeClassID
			WHERE GL.RowID IS NULL AND IP.BatchID = @BatchID
			
			SET @BatchID = @BatchID + 1	
		END
	END --'Feature Flag Use GL Units'
	--

	--run calculations
	exec fw.procFactGLSampledBaselineTargetUpdate @fiscalYearID = @fiscalYearID
	exec fw.procFactMonthlyYTDPriorYearUpdateStaging 'fw.FactGLSampled','#FactGLStaging', 'AccountID', 'Dollars,Units', @fiscalYearID, 0, 0
		
	if @FiscalYearID = 0 
	BEGIN
		truncate table fw.FactGLSampled
		declare @maxYear int = (select max(FiscalYearID) from fw.FactGLStagingWithCalcs)
		declare @minYear int = (select min(FiscalYearID) from fw.FactGLStagingWithCalcs)
			
		WHILE @minYear <= @maxYear 
			BEGIN
			
			SET @whereClause = 'FiscalYearID = ' + cast(@minYear as nvarchar(100)) + ' '
									
			IF OBJECT_ID('tempdb..#inputDepartmentsForFactGLSampled') IS NOT NULL DROP TABLE #inputDepartmentsForFactGLSampled
			CREATE TABLE #inputDepartmentsForFactGLSampled (DepartmentID INT, RecordsCount INT, BatchID INT)
					
			INSERT INTO #inputDepartmentsForFactGLSampled
			EXEC dbo.procGetInputDataByBatches
				@batchSize = @batchSize,
				@columnName = 'DepartmentID',
				@tableAlias = 'X',
				@fromClause = 'fw.FactGLStagingWithCalcs X',
				@whereClause = @whereClause,
				@isDebug = 0

			SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartmentsForFactGLSampled
		
			SET @BatchID = 1
			WHILE @BatchID <= @MaxBatchID
			BEGIN
				INSERT INTO fw.FactGLSampled (
					DepartmentID
					,AccountID
					,FiscalYearID
					,FiscalMonthID
					,TimeClassID
					,Units
					,UnitsYTD
					,UnitsPriorYear
					,UnitsPriorYTD
					,Dollars
					,DollarsYTD
					,DollarsPriorYear
					,DollarsPriorYTD
					,TransactionID
					,IsSystemGenerated)
				SELECT 
					FG.DepartmentID
					,FG.AccountID
					,FG.FiscalYearID
					,FG.FiscalMonthID
					,FG.TimeClassID
					,FG.Units
					,FG.UnitsYTD
					,FG.UnitsPriorYear
					,FG.UnitsPriorYTD
					,FG.Dollars
					,FG.DollarsYTD
					,FG.DollarsPriorYear
					,FG.DollarsPriorYTD
					,0
					,FG.IsSystemGenerated 
				FROM fw.FactGLStagingWithCalcs FG
				INNER JOIN #inputDepartmentsForFactGLSampled IP ON IP.DepartmentID = FG.DepartmentID
				WHERE FiscalYearID = @minYear AND IP.BatchID = @BatchID

				SET @BatchID = @BatchID + 1	
			END
			 
			SET @minYear = @minYear + 1
		END
	END
	ELSE
	BEGIN
	
	;with tgt (DepartmentID,
			AccountID,
			FiscalYearID,
			FiscalMonthID,
			TimeClassID,
			Units,
			UnitsYTD,
			UnitsPriorYear,
			UnitsPriorYTD,
			Dollars,
			DollarsYTD,
			DollarsPriorYear,
			DollarsPriorYTD,
			IsDeleted,
			IsSystemGenerated) as (
		select
			DepartmentID,
			AccountID,
			FiscalYearID,
			FiscalMonthID,
			TimeClassID,
			Units,
			UnitsYTD,
			UnitsPriorYear,
			UnitsPriorYTD,
			Dollars,
			DollarsYTD,
			DollarsPriorYear,
			DollarsPriorYTD,
			IsDeleted,
			IsSystemGenerated
		from	
			fw.FactGLSampled
		where
			(
				TimeClassID != 4
				or
				(TimeClassID = 4 and exists(select 1 from [mr].[SystemSetting] where Name = 'Is MR Flexing Manually Loaded' and Value = '1'))
			)
			AND (FiscalYearID = @fiscalYearID)
		),
		src (DepartmentID,
			AccountID,
			FiscalYearID,
			FiscalMonthID,
			TimeClassID,
			Units,
			UnitsYTD,
			UnitsPriorYear,
			UnitsPriorYTD,
			Dollars,
			DollarsYTD,
			DollarsPriorYear,
			DollarsPriorYTD,
			IsSystemGenerated) as (
		select
			DepartmentID,
			AccountID,
			FiscalYearID,
			FiscalMonthID,
			TimeClassID,
			Units,
			UnitsYTD,
			UnitsPriorYear,
			UnitsPriorYTD,
			Dollars,
			DollarsYTD,
			DollarsPriorYear,
			DollarsPriorYTD,
			IsSystemGenerated
		from	
			fw.FactGLStagingWithCalcs
		where
			(
				TimeClassID != 4
				or
				(TimeClassID = 4 and exists(select 1 from [mr].[SystemSetting] where Name = 'Is MR Flexing Manually Loaded' and Value = '1'))
			)
			AND (FiscalYearID = @fiscalYearID)
		)
			
	MERGE tgt as target
	USING src as source
	ON	(
			target.departmentid = source.departmentid
			and target.accountid = source.accountid
			and target.fiscalyearid = source.fiscalyearid
			and target.fiscalmonthid = source.fiscalmonthid
			and target.timeclassid = source.timeclassid
		)
	WHEN MATCHED AND (
					target.Units<> source.Units
					or target.UnitsYTD<> source.UnitsYTD
					or target.UnitsPriorYear<> source.UnitsPriorYear
					or target.UnitsPriorYTD<> source.UnitsPriorYTD
					or target.Dollars<> source.Dollars
					or target.DollarsYTD<> source.DollarsYTD
					or target.DollarsPriorYear<> source.DollarsPriorYear
					or target.DollarsPriorYTD<> source.DollarsPriorYTD
					or target.IsSystemGenerated <> source.IsSystemGenerated
					)  THEN
		UPDATE SET 
					target.Units = source.Units,
					target.UnitsYTD= source.UnitsYTD,
					target.UnitsPriorYear= source.UnitsPriorYear,
					target.UnitsPriorYTD= source.UnitsPriorYTD,
					target.Dollars= source.Dollars,
					target.DollarsYTD= source.DollarsYTD,
					target.DollarsPriorYear= source.DollarsPriorYear,
					target.DollarsPriorYTD= source.DollarsPriorYTD,
					target.IsSystemGenerated = source.IsSystemGenerated
	WHEN NOT MATCHED BY TARGET THEN 
		INSERT (DepartmentID,
			AccountID,
			FiscalYearID,
			FiscalMonthID,
			TimeClassID,
			Units,
			UnitsYTD,
			UnitsPriorYear,
			UnitsPriorYTD,
			Dollars,
			DollarsYTD,
			DollarsPriorYear,
			DollarsPriorYTD,
			IsDeleted,
			IsSystemGenerated) VALUES (
			source.DepartmentID,
			source.AccountID,
			source.FiscalYearID,
			source.FiscalMonthID,
			source.TimeClassID,
			source.Units,
			source.UnitsYTD,
			source.UnitsPriorYear,
			source.UnitsPriorYTD,
			source.Dollars,
			source.DollarsYTD,
			source.DollarsPriorYear,
			source.DollarsPriorYTD,
			0,
			source.IsSystemGenerated)
	WHEN NOT MATCHED BY SOURCE THEN
			DELETE
	OUTPUT $action, inserted.FiscalYearID, inserted.TimeClassID, inserted.isdeleted INTO #SummaryOfChanges;
	END
	
	EXEC dbo.procRollingDeleteOnTable
		'fw',
		'fw.FactGLSampled',
		'RowID',
		'fw.FactGLSampled',
		'isDeleted = 1',
		10000000,
		0.5,
		0

	DECLARE @nextRowID BIGINT
	SELECT @nextRowID = ISNULL((SELECT MAX(RowID) FROM fw.FactGLSampled), 1)
	DBCC CHECKIDENT('fw.FactGLSampled','RESEED', @nextRowID);

	--return summary of results
	if (@isDebug = 1) begin
		SELECT 'GL Sample' as SampleType, FiscalYearID, TimeClassID, Change, IsDeleted, COUNT(*) AS CountPerChange
		FROM #SummaryOfChanges
		GROUP BY Change,  FiscalYearID, TimeClassID, IsDeleted;
	end
	
	IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments
	IF OBJECT_ID('tempdb..#FactGLStaging') IS NOT NULL  DROP TABLE #FactGLStaging
	IF OBJECT_ID('tempdb..#StatisticSampledMonthlyStaging') IS NOT NULL DROP TABLE #StatisticSampledMonthlyStaging
	IF OBJECT_ID('fw.FactGLStagingWithCalcs') IS NOT NULL  DROP TABLE fw.FactGLStagingWithCalcs
	IF OBJECT_ID('tempdb..#SummaryOfChanges') IS NOT NULL DROP TABLE #SummaryOfChanges
GO


---------------------------------------------

-- fw.procGLSampledPerformFlexing
CREATE PROC [fw].[procGLSampledPerformFlexing] 
	@CostingResultID int,
	@CostingTimeClassID tinyint,
	@FiscalYearID int
AS
/* ************************************************************************************************************************
** Author: Nathan LeRoy
** Create Date: 2016-04-22
** Description: Runs GL flexing for MR
** Last Modified: 2016-05-23
**************************************************************************************************************************
** Change History
**************************************************************************************************************************
** CID		Date		Author	WI			Description
** 1		5/10/16		NL		B-11692		Changed flexing to work like new ABB flexing procs
** 2		5/20/16		NL		B-12055		Removed call to insert flexed data (handled in engine now)
** 3		8/05/16		NL					Added call to procABBMRTransferFlexedPayrollSampledMonthlyToFactGLSampled
** 4		9/23/16		NL					Adding copy from budget -> flex
** 5		1/30/16		NL		MANUAL		changing the way this handles NULL cost data
*************************************************************************************************************************/


-- reset all of the flex data to budget (only data that should be flexed like ABB)

SELECT DISTINCT DepartmentID
INTO #ABBDepts
FROM (
	SELECT DepartmentID FROM [dss].[FactCostingOutDetailGL] WHERE CostingResultID = @CostingResultID
	UNION ALL
	SELECT DepartmentID FROM [dss].[FactCostingOutDetailPayroll] WHERE CostingResultID = @CostingResultID) depts;

INSERT INTO [fw].[FactGLSampled]([DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID], [IsDeleted], [Units], [UnitsYTD], [UnitsPriorYear], [UnitsPriorYTD], [Dollars], [DollarsYTD], [DollarsPriorYear], [DollarsPriorYTD], [IsSystemGenerated])
SELECT [DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], 4, [IsDeleted], [Units], [UnitsYTD], [UnitsPriorYear], [UnitsPriorYTD], [Dollars], [DollarsYTD], [DollarsPriorYear], [DollarsPriorYTD], [IsSystemGenerated]
FROM [fw].[FactGLSampled]
WHERE TimeClassID = 2 and FiscalYearID = @FiscalYearID and DepartmentID in ( select DepartmentID from #ABBDepts );


-- perform the flexing
UPDATE
	ab
SET	
-- BEG CID 5 --
	ab.Dollars = CASE WHEN ISNULL(ab.Variability, 0) = 0 
		 		      THEN ab.Dollars
		 			  ELSE ISNULL(((ab.Dollars * (1 - (cost.TotalVariableDirectCost / NULLIF(cost.TotalCost, 0.0)))) + cost.TotalExtendedVariableDirectCost), 0)
    			 END
-- END CID 5 --
FROM
 	(SELECT gl.DepartmentID, gl.AccountID, gl.FiscalYearID, gl.FiscalMonthID, gl.TimeClassID, gl.Dollars, ISNULL(avo.Variability, av.Variability) as Variability
	 FROM [fw].[FactGLSampled] gl
	 	  LEFT JOIN (SELECT AccountID, Variability FROM [dss].[AccountVariability] WHERE CostingConfigGuid = (SELECT CostingConfigGuid FROM [dss].[CostingResult] WHERE CostingResultID = @CostingResultID)) av ON gl.AccountID = av.AccountID
		  LEFT JOIN (SELECT DepartmentID, AccountID, Variability FROM [dss].[AccountVariabilityOverride] WHERE CostingConfigGuid = (SELECT CostingConfigGuid FROM [dss].[CostingResult] WHERE CostingResultID = @CostingResultID)) avo on gl.DepartmentID = avo.DepartmentID and gl.AccountID = avo.AccountID
	 WHERE TimeClassID = 4 AND FiscalYearID = @FiscalYearID) ab
	INNER JOIN #ABBDepts abd on ab.DepartmentID = abd.DepartmentID
	LEFT JOIN
	(SELECT
		DepartmentID,
		AccountID,
		FiscalMonthID,
		FiscalYearID,
		SUM(cost.ExtendedVariableDirectCost) as TotalExtendedVariableDirectCost,
		SUM(cost.TotalVariableDirectCost) as TotalVariableDirectCost,
		SUM(cost.TotalCost) as TotalCost
	FROM
		[fw].[viewMRGLBudgetCostPerRVUbyMonth] cost
	WHERE
		cost.CostingResultID  = @CostingResultID
		AND
		cost.TimeClassID = @CostingTimeClassID
	GROUP BY
		DepartmentID, AccountID, FiscalMonthID, FiscalYearID
	) cost
	ON ab.DepartmentID = cost.DepartmentID 
		AND ab.AccountID = cost.AccountID
		AND ab.FiscalMonthID = cost.FiscalMonthID
		AND ab.FiscalYearID = cost.FiscalYearID;
		
DROP TABLE #ABBDepts;

EXEC [fw].[procABBMRTransferFlexedPayrollSampledMonthlyToFactGLSampled] @fiscalYearID = @FiscalYearID, @CostingResultID = @CostingResultID;
GO


---------------------------------------------

-- fw.procGetSQLObjectsRelatedToDimension
CREATE PROCEDURE [fw].[procGetSQLObjectsRelatedToDimension]
    @dimensionGlobalId NVARCHAR(50),
    @dimensionIdValue INT
AS
	--create temp table
	CREATE TABLE #related_objects (Id int IDENTITY(1,1), FK_Schema VARCHAR(500) not null default(''), FK_Table VARCHAR(500) not null default(''), FK_Column VARCHAR(500) not null default(''),FriendlyName VARCHAR(200) DEFAULT(''))

	--create temp table
	CREATE TABLE #result(FK_Schema VARCHAR(500) not null default(''), FK_Table VARCHAR(500) not null default(''), FK_Column VARCHAR(500) not null default(''),FriendlyName VARCHAR(200) DEFAULT(''))

	--fill table with related objects
	INSERT INTO #related_objects(FK_Schema, FK_Table, FK_Column, FriendlyName)
	SELECT g.SchemaName FK_Schema, g.ObjectName FK_Table, a.SQLColumnName FK_Column, d.FriendlyName FROM dbo.ScoreAttribute a
		INNER JOIN dbo.ScoreDimensionGroup g ON g.DimensionGroupGUID = a.DimensionGroupGUID
		INNER JOIN dbo.ScoreDimension d ON d.DimensionGUID = g.DimensionGUID
	WHERE a.ForeignKeyGUID = (SELECT DefaultKeyGUID FROM dbo.ScoreDimension WHERE GlobalID = @dimensionGlobalId)

	INSERT INTO #related_objects(FK_Schema, FK_Table, FK_Column, FriendlyName)
	SELECT dt.SQLSchemaName FK_Schema, dt.SQLObjectName FK_Table, a.SQLColumnName FK_Column ,dt.FriendlyName
			FROM ScoreDataTable dt 
			INNER JOIN ScoreDataTableKeyLink kl ON kl.DataTableGUID = dt.DataTableGUID 
			INNER JOIN dbo.ScoreAttribute a ON a.AttributeGUID = kl.KeyGUID 
			WHERE a.AttributeGUID = (SELECT DefaultKeyGUID FROM dbo.ScoreDimension WHERE GlobalID = @dimensionGlobalId)
	
	INSERT INTO #related_objects(FK_Schema, FK_Table, FK_Column, FriendlyName)
	SELECT fk.FK_Schema, fk.FK_Table, fk.FK_Column, fk.FK_Table
			FROM dbo.ScoreDimension d
			JOIN dbo.ScoreDimensionGroup dg ON d.DimensionGUID = dg.DimensionGUID
			JOIN dbo.viewSysForeignKeys fk ON dg.ObjectName = PK_Table
			LEFT JOIN #related_objects r ON r.FK_Schema = fk.FK_Schema AND r.FK_Table = fk.FK_Table AND r.FK_Column = fk.FK_Column
			WHERE d.GlobalID = @dimensionGlobalId
			AND r.FK_Schema IS NULL							

	DECLARE @count INT = 1, @total INT = 0, @table VARCHAR(150), @schema VARCHAR(50), @column VARCHAR(50), @friendlyName VARCHAR(500), @sql VARCHAR(MAX)

	SELECT @total = COUNT(0) FROM #related_objects

	WHILE(@count <= @total)
	BEGIN
			
			SELECT @schema = FK_Schema, @table = FK_Table, @column = FK_Column, @friendlyName = FriendlyName FROM #related_objects WHERE Id = @count

			SET @sql = 'IF EXISTS(SELECT TOP 1 1 FROM ['+@schema+'].['+@table+'] WHERE '+@column+'='''+CAST(@dimensionIdValue AS VARCHAR)+''')
			BEGIN
				INSERT INTO #result (FK_Schema, FK_Table, FK_Column,FriendlyName) VALUES ('''+@schema+''','''+@table+''','''+@column+''','''+@friendlyName+''')
			END'			
		EXEC(@sql)

	SET @count = @count + 1
	END

	SELECT FK_Schema, FK_Table, FriendlyName FROM #result 

	DROP TABLE #related_objects
	DROP TABLE #result
GO


---------------------------------------------

-- fw.procGetStatisticsDrillIn
CREATE PROCEDURE [fw].[procGetStatisticsDrillIn](
	@DepartmentIDs VARCHAR(max)
	,@AccountIDs VARCHAR(max)
	,@PayPeriodIDs VARCHAR(max)
	,@isYTD bit
	)
AS
/**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1       2017-12-18   IP      B-17582     created procedure
** 2       2018-05-08   KF      B-19364     MRPR - Set Global Weights for Charge Codes - System Center Page
** 3       2018-10-20   IH      D-07606     PR - Delete rounding charge code values
** 4       2019-04-19   OV      B-20579     filtered by new column 'TimeClassID' from int.FactSharedImportDailyStatistics
** 5       2019-05-01   KF      D-08230     [fw].[procGetStatisticsDrillIn] is not taking the actual weighted average
** 6       2022-05-11   HV      JAZZ-36796     PR - Volume charge code data doesn't populate if loaded with real time stamp
** 7       2022-07-01   HV      JAZZ-40032     Rollback to previous version
** 8       2022-07-19   HV      JAZZ-39414     procGetStatisticsDrillIn timing out after 3 minutes
  										JAZZ-36796     PR - Volume charge code data doesn't populate if loaded with real time stamp
** 9       2023-02-17   IS      JAZZ-49480     fw.procGetStatisticsDrillIn has excessive part looking at TimeClassID=2 data
*************************************************************/
BEGIN
	IF OBJECT_ID('tempdb..#filtering') IS NOT NULL DROP TABLE #filtering
	IF OBJECT_ID('tempdb..#SubSelect') IS NOT NULL DROP TABLE #SubSelect
	IF OBJECT_ID('tempdb..#FDPSD') IS NOT NULL DROP TABLE #FDPSD
	IF OBJECT_ID('tempdb..#ConsolidatedParams') IS NOT NULL DROP TABLE #ConsolidatedParams

	CREATE TABLE #FDPSD (DepartmentID int primary key)
	insert into #FDPSD
	select distinct DriverDepartmentID as DepartmentID
	from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache

	CREATE TABLE #ConsolidatedParams (DepartmentID int, AccountId int, PayPeriodID int)
	CREATE TABLE #filtering (
		DepartmentID INT
		,AccountID INT
		,PayPeriodID INT
		,TimeClassID INT
		,SelectTable TINYINT
		)

IF @isYTD = 1
	INSERT INTO #ConsolidatedParams (DepartmentID,AccountId,PayPeriodID)
	SELECT DISTINCT d.DepartmentID,A.val as AccountID,pp_a.PayPeriodID
	FROM ConvertCSValuesToTable(@departmentIDs, ',') csv
	inner join fw.DimDepartment d on d.DepartmentID = csv.val
	inner join fw.DimPayPeriod pp on pp.PayCycleID =d.PayCycleID
	inner join ConvertCSValuesToTable(@PayPeriodIDs, ',') p on p.val = pp.PayPeriodCode
	INNER JOIN fw.DimPayPeriod pp_a on pp_a.PeriodNumber <= pp.PeriodNumber and pp_a.FiscalYearIDSecond = pp.FiscalYearIDSecond and pp_a.PayCycleID = pp.PayCycleID
	inner join ConvertCSValuesToTable(@AccountIDs, ',') a on 1=1
ELSE 
	INSERT INTO #ConsolidatedParams (DepartmentID,AccountId,PayPeriodID)
	SELECT DISTINCT d.DepartmentID,A.val as AccountID,pp.PayPeriodID
	FROM ConvertCSValuesToTable(@departmentIDs, ',') csv
	inner join fw.DimDepartment d on d.DepartmentID = csv.val
	inner join fw.DimPayPeriod pp on pp.PayCycleID =d.PayCycleID
	inner join ConvertCSValuesToTable(@PayPeriodIDs, ',') p on p.val = pp.PayPeriodCode
	inner join ConvertCSValuesToTable(@AccountIDs, ',') a on 1=1

INSERT INTO #filtering (
		DepartmentID
		,AccountID
		,PayPeriodID
		,TimeClassID
		,SelectTable
		)

	SELECT STAT.DepartmentID
		,STAT.AccountID
		,STAT.PayPeriodID
		,STAT.TimeClassID
		,1 AS SelectTable
	FROM [int].[FactStatisticsbyPayPeriod] STAT
	INNER JOIN [fw].[DimDepartment] D ON D.Departmentid = STAT.Departmentid
	inner join #ConsolidatedParams cp on cp.AccountId = STAT.AccountID and cp.DepartmentID = STAT.DepartmentID and cp.PayPeriodID = STAT.PayPeriodID
	left join #FDPSD FDPSD ON FDPSD.DepartmentID = STAT.DepartmentID
	WHERE STAT.Value != 0
		AND STAT.Isdeleted = 0
		AND STAT.PayPeriodID != 0
        and (D.IsPR = 1 or FDPSD.DepartmentID is not null)
		AND STAT.TimeClassID = 1
		AND stat.DepartmentID <> 0
	
UNION
	
	SELECT stat.DepartmentID
		,stat.AccountID
		,PP.PayPeriodID
		,stat.TimeClassID
		,2 AS SelectTable
	FROM [int].[FactSharedImportDailyStatistics] stat
	INNER JOIN [fw].[DimDate] DATE ON stat.DateID = DATE.DateID
	INNER JOIN [fw].[DimDepartment] D ON D.Departmentid = STAT.Departmentid
	INNER JOIN [fw].[DimPayPeriod] PP ON D.PayCycleID = PP.PayCycleID
 		    AND DATE.CalendarDateTime BETWEEN PP.PeriodStartCalendarDate
			AND PP.PeriodEndCalendarDate
	inner join #ConsolidatedParams cp on cp.AccountId = STAT.AccountID and cp.DepartmentID = STAT.DepartmentID and cp.PayPeriodID = pp.PayPeriodID
	left join #FDPSD FDPSD ON FDPSD.DepartmentID = STAT.DepartmentID
	WHERE stat.Value <> 0
	    AND TimeClassID = 1
		AND STAT.Isdeleted = 0
		AND PP.PayPeriodID != 0
		and (D.IsPR = 1 or FDPSD.DepartmentID is not null)
		AND stat.DepartmentID <> 0
	GROUP BY stat.DepartmentID
		,stat.AccountID
		,PP.PayPeriodID
		,stat.TimeClassID
	
UNION
	
	SELECT STAT.DepartmentID
		,STAT.AccountID
		,PP.PayPeriodID
		,1 AS TimeClassID
		,3 AS SelectTable
	FROM [fw].[FactChargeBasedStatistics] STAT
	INNER JOIN [fw].[DimDate] DATE ON STAT.DateID = DATE.DateID
	INNER JOIN [fw].[DimDepartment] DEPT ON STAT.DepartmentID = DEPT.DepartmentID
	INNER JOIN [fw].[DimPayPeriod] PP ON DEPT.PayCycleID = PP.PayCycleID
		AND DATE.CalendarDateTime BETWEEN PP.PeriodStartCalendarDate
			AND PP.PeriodEndCalendarDate
	inner join #ConsolidatedParams cp on cp.AccountId = STAT.AccountID and cp.DepartmentID = STAT.DepartmentID and cp.PayPeriodID = pp.PayPeriodID
	left join #FDPSD FDPSD ON FDPSD.DepartmentID = STAT.DepartmentID
	WHERE STAT.Value != 0
		AND STAT.IsDeleted = 0
		AND PP.PayPeriodID != 0
		and (DEPT.IsPR = 1 or FDPSD.DepartmentID is not null)
	GROUP BY STAT.DepartmentID
		,STAT.AccountID
		,PP.PayPeriodID
	
	DELETE F FROM #filtering f
	inner join (
	SELECT DepartmentID
		,AccountID
		,PayPeriodID
		,TimeClassID
		,SelectTable
		,max(SelectTable) OVER(PARTITION BY DepartmentID,AccountID,TimeClassID,PayPeriodID ORDER BY DepartmentID,AccountID,TimeClassID,PayPeriodID) AS SelectTableMax
		,count(SelectTable) OVER(PARTITION BY DepartmentID,AccountID,TimeClassID,PayPeriodID ORDER BY DepartmentID,AccountID,TimeClassID,PayPeriodID) AS SelectTableCount
	FROM #filtering) d
	on f.DepartmentID = d.DepartmentID
	and f.AccountID = d.AccountID
	and f.TimeClassID = d.TimeClassID
	and f.PayPeriodID = d.PayPeriodID
	and NOT (d.SelectTableCount = 1 and d.SelectTableMax = 3)		
	
	SELECT 
		pt.PatientTypeRollupID,
		bl.DepartmentID,
		bl.FiscalYearID as FiscalYearID,
		bl.ChargeCodeID,
		sum(bl.UnitsOfService) AS ChargeCodeValue_UnitsOfService
	INTO #SubSelect
	FROM [dss].[FactPatientBillingLineItemDetail] bl
	INNER JOIN clientdss.FactPatientEncounterSummary es WITH (READUNCOMMITTED) ON bl.EncounterID = es.EncounterID
	INNER JOIN fw.DimPatientType pt WITH (READUNCOMMITTED) ON es.PatientTypeID = pt.PatientTypeID
	INNER JOIN (
      SELECT DISTINCT DepartmentID, dpp.PeriodStartCalendarDate, dateadd(millisecond, -1, convert(datetime2(3),dateadd(day, 1, convert(date, dpp.PeriodEndCalendarDate)))) as PeriodEndCalendarDate from #filtering f
      INNER JOIN fw.DimPayPeriod dpp on dpp.PayPeriodID = f.PayPeriodID
	) flt on flt.DepartmentID = bl.DepartmentID and bl.ServiceDateTime between flt.PeriodStartCalendarDate and flt.PeriodEndCalendarDate
	GROUP BY pt.PatientTypeRollupID,
		bl.ChargeCodeID,
		bl.DepartmentID,
		bl.FiscalYearID
	option (recompile)
			
    SELECT
      S.ChargeCode,
      S.PatientTypeRollup,
      round(S.ChargeCodeValue_UnitsOfService, 0) AS ChargeCodeValue_UnitsOfService,
      CAST(S.StatisticValue/S.ChargeCodeValue_UnitsOfService AS Numeric(19,4)) AS Weight,
      S.StatisticValue
    FROM
    ( SELECT 
		cc.NAME AS ChargeCode
		,ptr.NAME AS PatientTypeRollup
		,sum(subselect.ChargeCodeValue_UnitsOfService) as ChargeCodeValue_UnitsOfService
		,sum(subselect.ChargeCodeValue_UnitsOfService * map.Weight) AS StatisticValue
      FROM #SubSelect subselect
      INNER JOIN [fw].[viewDepartmentChargeCodeStatisticMapping] map WITH (READUNCOMMITTED) ON subselect.DepartmentID = map.DepartmentID
        AND subselect.ChargeCodeID = map.ChargeCodeID
        AND subselect.PatientTypeRollupID = map.PatientTypeRollupID
        AND map.FiscalYearID = subselect.FiscalYearID
      INNER JOIN fw.DimChargeCode cc ON cc.ChargeCodeID = map.ChargeCodeID
      INNER JOIN fw.DimPatientTypeRollup ptr WITH (READUNCOMMITTED) ON ptr.PatientTypeRollupID = subselect.PatientTypeRollupID
      INNER JOIN (select distinct AccountID from #filtering) flt ON flt.AccountID = map.AccountID
      WHERE map.Weight <> 0
      GROUP BY cc.NAME, ptr.NAME
      HAVING sum(subselect.ChargeCodeValue_UnitsOfService) <> 0
    ) S

	IF OBJECT_ID('tempdb..#filtering') IS NOT NULL DROP TABLE #filtering
	IF OBJECT_ID('tempdb..#SubSelect') IS NOT NULL DROP TABLE #SubSelect
	IF OBJECT_ID('tempdb..#FDPSD') IS NOT NULL DROP TABLE #FDPSD
	IF OBJECT_ID('tempdb..#ConsolidatedParams') IS NOT NULL DROP TABLE #ConsolidatedParams
END
GO


---------------------------------------------

-- fw.procInsertDimensionDefaults
--Author: gforeman
--Branch: GoldenManMigr
--Forward
CREATE PROCEDURE [fw].[procInsertDimensionDefaults]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	DECLARE @DEFAULTID int
	SET @DEFAULTID = 0

	DECLARE @DEFAULTNAME nvarchar(100)
	SET @DEFAULTNAME = 'Not Specified'

	IF NOT EXISTS (SELECT 1 FROM fw.DimAccount where AccountID = 0)
	BEGIN
		SET IDENTITY_INSERT fw.DimAccount ON
		INSERT INTO fw.DimAccount (AccountID) VALUES (@DEFAULTID)
		SET IDENTITY_INSERT fw.DimAccount OFF	
	END

	IF NOT EXISTS (SELECT 1 FROM fw.DimDepartment where DepartmentID = 0)
	BEGIN
		SET IDENTITY_INSERT fw.DimDepartment ON
		INSERT INTO fw.DimDepartment (DepartmentID, Description) VALUES (@DEFAULTID, @DEFAULTNAME)
		SET IDENTITY_INSERT fw.DimDepartment OFF	
	END
	
	IF NOT EXISTS (SELECT 1 FROM fw.DimEmployee where EmployeeID = 0)
	BEGIN
		SET IDENTITY_INSERT fw.DimEmployee ON
		INSERT INTO fw.DimEmployee (EmployeeID, NameLast, NameFirst) VALUES (@DEFAULTID, @DEFAULTNAME, @DEFAULTNAME)
		SET IDENTITY_INSERT fw.DimEmployee OFF
	END
	
	IF NOT EXISTS (SELECT 1 FROM fw.DimJobCode where JobCodeID = 0)
	BEGIN
		SET IDENTITY_INSERT fw.DimJobCode ON
		INSERT INTO fw.DimJobCode (JobCodeID) VALUES (@DEFAULTID)
		SET IDENTITY_INSERT fw.DimJobCode OFF
	END
	
END
GO


---------------------------------------------

-- fw.procInsertPayPeriodsForPayCycle
CREATE PROC fw.procInsertPayPeriodsForPayCycle
@payCycleId INT,
@numOfYearsToAdd INT 
AS 

----verify paycycle id exists if it does not exit out 
IF NOT EXISTS (SELECT 1 FROM fw.DimPayCycle WHERE PayCycleID=@payCycleId)
	BEGIN
	EXEC [migration].[LogMigrationDetail] @Name = 'fw.procInsertPayPeriodsForPayCycle',
		@Message = 'PayCycleId not found',
		@AffectedObject = 'fw.DimPayPeriod',
		@Status='Warning';
		Return
	END

	--limiting this to at most 20 years into the future from today and 20 years at a time
IF ((@numOfYearsToAdd>20) OR (DATEDIFF(YEAR, GETDATE(), (SELECT DATEADD(YEAR, @numOfYearsToAdd , MAX(PeriodEndCalendarDate)) FROM fw.dimpayperiod WHERE PayCycleID = @payCycleId)) > 20))
	BEGIN
	EXEC [migration].[LogMigrationDetail] @Name = 'fw.procInsertPayPeriodsForPayCycle',
		@Message = 'Over limit of 20 for number of years to add at once or over 20 years from today for pay periods',
		@AffectedObject = 'fw.DimPayPeriod',
		@Status='Warning';
		Return
	END

DECLARE @lastPayPeriod INT;
DECLARE @paygap INT;
DECLARE @newStart DATETIME;
DECLARE @fiscalYear INT;
DECLARE @previousFiscalYear INT;
DECLARE @previousPeriodNum INT;
DECLARE @payCycleName VARCHAR(200);

SELECT TOP 1 @lastPayPeriod = pp.PayPeriodID, @paygap = pp.PeriodDays, @newStart = DATEADD(DAY, 1, PeriodEndCalendarDate), 
	@FiscalYear = dbo.GetFiscalYearForDate(PeriodEndCalendarDate) + @numOfYearsToAdd,
	@previousFiscalYear = dbo.GetFiscalYearForDate(PeriodEndCalendarDate),
	@previousPeriodNum = pp.periodnumber, @payCycleName = pp.PayCycleName	
	FROM 
	fw.dimpayperiod pp 
	WHERE pp.PayCycleID = @payCycleId ORDER BY PayPeriodID desc

DECLARE @endDate DATETIME SET @endDate = DATEFROMPARTS(@fiscalYear, (DATEPART(MONTH, dbo.GetFiscalYearEndDate())), DATEPART(DAY, dbo.GetFiscalYearEndDate()))
DECLARE @numOfEntries INT SET @numOfEntries = (SELECT FLOOR(DATEDIFF(day, @newStart, @endDate )/@paygap))
DECLARE @historyItemGUID UNIQUEIDENTIFIER = (SELECT  NEWID());

IF OBJECT_ID('tempdb..#tempTablePayPeriods') IS NOT NULL DROP TABLE #tempTablePayPeriods;
CREATE TABLE #tempTablePayPeriods (PeriodDays TINYINT, RowNumberID INT, WorkingDays TINYINT, PayCycleId INT, PayCycleSortOrder INT,
							AccrualMethod NVARCHAR(100), PayCycleCode NVARCHAR(200), PeriodEndCalendarDate DATETIME,
							FiscalYearIDStart INT, FiscalYearIDSecond INT, PeriodNumber TINYINT, PayPeriodCode NVARCHAR(100),
							Code NVARCHAR(350), Name NVARCHAR(350), PayCycleName VARCHAR(200), HistoryItemGUID UNIQUEIDENTIFIER)

		INSERT into #tempTablePayPeriods 
		SELECT *,CONCAT(FiscalYearIdSecond, '-', PeriodNumber) PayPeriodCode, CONCAT(PayCycleCode, ' - ', finalCalculations.FiscalYearIdSecond,'-', PeriodNumber) Code,
		CONCAT(@payCycleName, ' - ',finalCalculations.FiscalYearIdSecond, '-', PeriodNumber) Name, @payCycleName PayCycleName, @historyItemGUID HistoryItemGuid
		FROM (
			SELECT PeriodDays, RowNumberID, WorkingDays, PayCycleId, PayCycleSortOrder, AccrualMethod,
			PayCycleCode, PeriodEndCalendarDate, FiscalYearIDStart, FiscalYearIDSecond, IIF(FiscalYearIdSecond = @previousFiscalYear, PeriodNumberCalc + @previousPeriodNum, PeriodNumberCalc) AS 'PeriodNumber' 
			FROM (
				SELECT *, ROW_NUMBER() OVER (PARTITION BY FiscalYearIdSecond ORDER BY RowNumberID) AS 'PeriodNumberCalc'
					FROM (
						SELECT *, dbo.GetFiscalYearForDate((dateadd(day,(1)-PeriodDays,PeriodEndCalendarDate))) FiscalYearIdStart,
						dbo.GetFiscalYearForDate(PeriodEndCalendarDate) FiscalYearIdSecond
						FROM
						(
							SELECT
								pp.PeriodDays, 
								rn.RowNumberID, 
								pp.WorkingDays,
								pc.PayCycleID,
								pc.SortOrder PayCycleSortOrder,
								pc.AccrualMethod,
								pc.Code PayCycleCode,
								DATEADD(DAY, (@paygap * rn.RowNumberID), pp.PeriodEndCalendarDate) PeriodEndCalendarDate
							FROM fw.DimPayPeriod pp
							INNER JOIN fw.DimRowNumber rn ON rn.RowNumberID BETWEEN 1 AND @numOfEntries -- however many new entries are required
							INNER JOIN fw.DimPayCycle pc ON pc.PayCycleID = pp.PayCycleID
							WHERE pp.PayCycleID =@payCycleId
							AND pp.PayPeriodID = @lastPayPeriod-- this whatever the last row in the current paycycle is
						) baseSelection
					) periodNumber
				)periodNumberFilter
		 ) finalCalculations ORDER BY finalCalculations.RowNumberID

		INSERT INTO fw.dimpayperiod (PeriodDays, WorkingDays, PayCycleId, PayCycleSortOrder, AccrualMethod, PayCycleCode, PeriodEndCalendarDate, FiscalYearIDStart,
							  FiscalYearIDSecond, PeriodNumber, PayPeriodCode, Code, Name, PayCycleName, HistoryItemGUID)
								SELECT PeriodDays, WorkingDays, PayCycleId, PayCycleSortOrder, AccrualMethod, PayCycleCode, PeriodEndCalendarDate, FiscalYearIDStart,
										FiscalYearIDSecond, PeriodNumber, PayPeriodCode, Code, Name, PayCycleName, HistoryItemGUID  
								FROM #tempTablePayPeriods
		
		--insert into history item table
		DECLARE @entityguid UNIQUEIDENTIFIER SET @entityguid = (SELECT DimensionGUID FROM dbo.ScoreDimension WHERE GlobalID='Pay Period')
		EXEC dbo.procLogObjectHistoryItemGUIDObjectType 'Strata.Score.Config.Dimension.ScoreDimension, Strata.Score, Version=2024.33.0.0, Culture=neutral, PublicKeyToken=null',
														 @entityguid,'Adding Pay Period Ids for Pay Cycle', 0, @historyItemGUID

		DROP TABLE #tempTablePayPeriods;
GO


---------------------------------------------

-- fw.procMergeEncounterBasedStatistics
CREATE   PROC fw.procMergeEncounterBasedStatistics
  @statisticID int
AS
BEGIN
  SET NOCOUNT ON

    CREATE TABLE #detailsToMerge
  (
  RowID bigint identity(1,1),
  DateID int,
  DepartmentID int,
  AccountID int,
  Value decimal(19, 4)
  )
  CREATE CLUSTERED INDEX CNU_RowId ON #detailsToMerge(RowId)

  INSERT #detailsToMerge (DepartmentID, AccountID, DateID, Value)
  SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, SUM(ebs.Value)
  FROM fw.FactEncounterBasedStatistics ebs
  WHERE ebs.StatisticID = @statisticID
  GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.DateID

  CREATE TABLE #batch
  (
  DateID int,
  DepartmentID int,
  AccountID int,
  Value decimal(19, 4)
  )

  DECLARE
  @startRowId bigint,
  @maxRowId bigint,
  @endRowId bigint

  SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId)
  FROM #detailsToMerge

  WHILE (@startRowId <= @maxRowId)
  BEGIN
    SELECT @endRowId = MAX(d.RowId)
    FROM (SELECT TOP 1000000 RowId
          FROM #detailsToMerge
          WHERE RowId >= @startRowId
          ORDER BY RowID) as d

    TRUNCATE TABLE #batch

    INSERT #batch (DepartmentID, AccountID, DateID, Value)
    SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, ebs.Value
    FROM #detailsToMerge ebs
    WHERE ebs.RowId >= @startRowId
      AND ebs.RowId <= @endRowId

    UPDATE fw.FactChargeBasedStatistics
    SET Value = ebs.Value
    FROM fw.FactChargeBasedStatistics cbs
      JOIN #batch ebs
        ON cbs.DepartmentID = ebs.DepartmentID
          AND cbs.AccountID = ebs.AccountID
          AND cbs.DateID = ebs.DateID

    INSERT fw.FactChargeBasedStatistics (DepartmentID, AccountID, DateID, Value)
    SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, ebs.Value
    FROM #batch ebs
    WHERE NOT EXISTS
      (
        SELECT cbs.RowID
        FROM fw.FactChargeBasedStatistics cbs
        WHERE ebs.DepartmentID = cbs.DepartmentID
          AND ebs.AccountID = cbs.AccountID
          AND ebs.DateID = cbs.DateID
      )

    SELECT @startRowId = MIN(d.RowId)
    FROM #detailsToMerge d
    WHERE RowId > @endRowId
  END

  DROP TABLE IF EXISTS #detailsToMerge
  DROP TABLE IF EXISTS #batch
END
GO


---------------------------------------------

-- fw.procMergeEncounterBasedStatisticsMonthly
CREATE   PROC fw.procMergeEncounterBasedStatisticsMonthly
  @statisticID int
AS
BEGIN
  SET NOCOUNT ON

  DROP TABLE IF EXISTS #detailsToMerge

  CREATE TABLE #detailsToMerge
  (
  FiscalYearID smallint,
  FiscalMonthID tinyint,
  DepartmentID int,
  AccountID int,
  Value decimal(19, 4)
  )

  INSERT #detailsToMerge (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value)
  SELECT ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID, ebs.Value
  FROM fw.FactEncounterBasedStatisticsMonthly ebs
  WHERE ebs.StatisticID = @statisticID

  UPDATE #detailsToMerge
  SET Value = aggr.AggregatedValue
  FROM
  (
    SELECT ebs.FiscalYearID, ebs.FiscalMonthID, ebs.DepartmentID, ebs.AccountID, SUM(ebs.Value) AS AggregatedValue
    FROM #detailsToMerge d
      JOIN fw.FactEncounterBasedStatisticsMonthly ebs
        ON ebs.DepartmentID = d.DepartmentID
          AND ebs.AccountID = d.AccountID
          AND ebs.FiscalYearID = d.FiscalYearID
          AND ebs.FiscalMonthID = d.FiscalMonthID
    GROUP BY ebs.FiscalYearID, ebs.FiscalMonthID, ebs.DepartmentID, ebs.AccountID
    ) aggr
    JOIN #detailsToMerge det
      ON aggr.DepartmentID = det.DepartmentID
          AND aggr.AccountID = det.AccountID
          AND aggr.FiscalYearID = det.FiscalYearID
          AND aggr.FiscalMonthID = det.FiscalMonthID

  UPDATE fw.FactChargeBasedStatisticsMonthly
  SET Value = ebs.Value
  FROM #detailsToMerge ebs
    JOIN fw.FactChargeBasedStatisticsMonthly cbs
      ON ebs.DepartmentID = cbs.DepartmentID
        AND ebs.AccountID = cbs.AccountID
        AND ebs.FiscalYearID = cbs.FiscalYearID
        AND ebs.FiscalMonthID = cbs.FiscalMonthID

  INSERT fw.FactChargeBasedStatisticsMonthly (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value)
  SELECT ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID, ebs.Value
  FROM #detailsToMerge ebs
  WHERE NOT EXISTS
    (
      SELECT cbs.RowID
      FROM fw.FactChargeBasedStatisticsMonthly cbs
      WHERE ebs.DepartmentID = cbs.DepartmentID
        AND ebs.AccountID = cbs.AccountID
        AND ebs.FiscalYearID = cbs.FiscalYearID
        AND ebs.FiscalMonthID = cbs.FiscalMonthID
    )
END
GO


---------------------------------------------

-- fw.procOptimizationRebuildIndexesAll
CREATE proc [fw].[procOptimizationRebuildIndexesAll] 
	@AreYouSureYouWantToTakeDownTheSQLServer bit = 0
as

/************************************************************
** Author: akowalski
** Create Date: 2015-12-08
** Description: Rebuilds indexs and updates statistics on all tables in the database.  Do not use unless you're sure you know what you're doing.  It could take days to complete on platform customers.
** Last Modified: 2015-12-08
** GM Release: 2015-12-08
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
**
*************************************************************/

if @AreYouSureYouWantToTakeDownTheSQLServer=1
begin

SET NOCOUNT ON;

	DECLARE @SCHEMA nvarchar(256)
	DECLARE @FactTableName nvarchar(256)
	DECLARE @SQL nvarchar(1024)
	DECLARE FactTableCursor CURSOR FOR 
	select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t
		where t.object_ID not in (
		select distinct t.object_id from sys.tables t
		inner join sys.indexes i on t.object_id=i.object_id
		inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id
		where p.data_compression<>0
		) order by t.name
	open FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		--=================== BEGIN CID 1 =====================
		set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD 
		update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN'
		--=================== END CID 1 =======================
	    --print @SQL
	    EXECUTE sp_executesql @SQL 
	    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor
	
	DECLARE FactTableCursor CURSOR FOR 
	select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t
		where t.object_ID not in (
		select distinct t.object_id from sys.tables t
		inner join sys.indexes i on t.object_id=i.object_id
		inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id
		where p.data_compression=0
		) order by t.name
	open FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		--=================== BEGIN CID 1 =====================
		set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD  WITH (DATA_COMPRESSION = PAGE)
		update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN'
		--=================== END CID 1 =======================
	    --print @SQL
	    EXECUTE sp_executesql @SQL 
	    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor
end


RETURN
GO


---------------------------------------------

-- fw.procOptimizationRebuildIndexesDimensions
CREATE proc [fw].[procOptimizationRebuildIndexesDimensions] as

/************************************************************
** Author: akowalski
** Create Date: 2013-02-18
** Description: Finds all dimension tables in the FW schemas and rebuilds indexes, for after dimension customization.
** Last Modified: 2013-02-18
** GM Release: 2013-03-12
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2013-02-19	DK		56588	Adding update statistics command
**
*************************************************************/


SET NOCOUNT ON;

	DECLARE @SCHEMA nvarchar(256)
	DECLARE @FactTableName nvarchar(256)
	DECLARE @SQL nvarchar(1024)
	DECLARE FactTableCursor CURSOR FOR 
	select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t 
	where t.schema_id in(select schema_id from sys.schemas where name in('fw', 'client')) and t.name like 'dim%' 
	and t.object_ID not in (
		select distinct t.object_id from sys.tables t
		inner join sys.indexes i on t.object_id=i.object_id
		inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id
		where p.data_compression<>0
		) order by t.name
	open FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		--=================== BEGIN CID 1 =====================
		set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD 
		update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN'
		--=================== END CID 1 =======================
	    --print @SQL
	    EXECUTE sp_executesql @SQL 
	    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor

	DECLARE FactTableCursor CURSOR FOR 
	select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t 
	where t.schema_id in(select schema_id from sys.schemas where name in('fw', 'client')) and t.name like 'dim%' 
	and t.object_ID not in (
		select distinct t.object_id from sys.tables t
		inner join sys.indexes i on t.object_id=i.object_id
		inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id
		where p.data_compression=0
		) order by t.name
	open FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		--=================== BEGIN CID 1 =====================
		set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD  WITH (DATA_COMPRESSION = PAGE)
		update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN'
		--=================== END CID 1 =======================
	    --print @SQL
	    EXECUTE sp_executesql @SQL 
	    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor
RETURN
GO


---------------------------------------------

-- fw.procOptimizationRebuildIndexesFillins
CREATE proc fw.procOptimizationRebuildIndexesFillins as

/************************************************************
** Author: akowalski
** Create Date: 2013-02-18
** Description: Finds all fillin tables rebuilds indexes, for after fillin refreshes.
** Last Modified: 2013-02-18
** GM Release: 2013-03-12
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/


SET NOCOUNT ON;

	DECLARE @SCHEMA nvarchar(256)
	DECLARE @FactTableName nvarchar(256)
	DECLARE @SQL nvarchar(1024)
	DECLARE FactTableCursor CURSOR FOR 
	select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in ('data', 'dbo')) and t.name like 'ScoreFillin%'
		and t.object_ID not in (
		select distinct t.object_id from sys.tables t
		inner join sys.indexes i on t.object_id=i.object_id
		inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id
		where p.data_compression<>0
		) order by t.name
	open FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD 
		update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN'
	    --print @SQL
	    EXECUTE sp_executesql @SQL 
	    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor

	DECLARE FactTableCursor CURSOR FOR 
	select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in ('data', 'dbo')) and t.name like 'ScoreFillin%'
		and t.object_ID not in (
		select distinct t.object_id from sys.tables t
		inner join sys.indexes i on t.object_id=i.object_id
		inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id
		where p.data_compression=0
		) order by t.name
	open FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD  WITH (DATA_COMPRESSION = PAGE)
		update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN'
	    --print @SQL
	    EXECUTE sp_executesql @SQL 
	    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor

RETURN
GO


---------------------------------------------

-- fw.procOptimizationRebuildIndexesSecurity
CREATE proc fw.procOptimizationRebuildIndexesSecurity as
/************************************************************
** Author: akowalski
** Create Date: 2014-04-23
** Description: Finds all security related tables, for after mass security assignments.
** Last Modified: 2014-04-23
** GM Release: 2014.3
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/


SET NOCOUNT ON;

	DECLARE @SCHEMA nvarchar(256)
	DECLARE @FactTableName nvarchar(256)
	DECLARE @SQL nvarchar(1024)
	DECLARE FactTableCursor CURSOR FOR 
	select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in ('dbo')) and t.name like 'S3%'
		and t.object_ID not in (
		select distinct t.object_id from sys.tables t
		inner join sys.indexes i on t.object_id=i.object_id
		inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id
		where p.data_compression<>0
		) order by t.name
	open FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD 
		update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN'
	    --print @SQL
	    EXECUTE sp_executesql @SQL 
	    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor
	
	DECLARE FactTableCursor CURSOR FOR 
	select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in ('dbo')) and t.name like 'S3%'
		and t.object_ID not in (
		select distinct t.object_id from sys.tables t
		inner join sys.indexes i on t.object_id=i.object_id
		inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id
		where p.data_compression=0
		) order by t.name
	open FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD  WITH (DATA_COMPRESSION = PAGE)
		update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN'
	    --print @SQL
	    EXECUTE sp_executesql @SQL 
	    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor

alter index all on dbo.xplan REBUILD 
update statistics dbo.xplan WITH FULLSCAN


RETURN
GO


---------------------------------------------

-- fw.procOptimizationRebuildIndexesWorkflow
CREATE proc fw.procOptimizationRebuildIndexesWorkflow as
/************************************************************
** Author: akowalski
** Create Date: 2014-04-23
** Description: Finds all workflow related tables, for during heavy capital budgeting.
** Last Modified: 2014-04-23
** GM Release: 2014.3
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/


SET NOCOUNT ON;

	DECLARE @SCHEMA nvarchar(256)
	DECLARE @FactTableName nvarchar(256)
	DECLARE @SQL nvarchar(1024)
	DECLARE FactTableCursor CURSOR FOR 
	select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in ('dbo')) and t.name like 'WF%'
		and t.object_ID not in (
		select distinct t.object_id from sys.tables t
		inner join sys.indexes i on t.object_id=i.object_id
		inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id
		where p.data_compression<>0
		) order by t.name
	open FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD
		update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN'
	    --print @SQL
	    EXECUTE sp_executesql @SQL 
	    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor
	
	DECLARE FactTableCursor CURSOR FOR 
	select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in ('dbo')) and t.name like 'WF%'
		and t.object_ID not in (
		select distinct t.object_id from sys.tables t
		inner join sys.indexes i on t.object_id=i.object_id
		inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id
		where p.data_compression=0
		) order by t.name
	open FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE)
		update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN'
	    --print @SQL
	    EXECUTE sp_executesql @SQL 
	    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor

RETURN
GO


---------------------------------------------

-- fw.procPayRollSampledAdjustedTargetMonthlyInsert
CREATE PROCEDURE [fw].[procPayRollSampledAdjustedTargetMonthlyInsert] (@FiscalYearID int = 0)
AS
BEGIN
/*
Proposal

If the client is not using flexing, this will be the target plus the efficiency factor
This should work regardless of the target basis (i.e. rolling avg or budget)
The factor will be applied after the inversion
If the factor type is percentage, the adjusted target will be the target*(1+factor)
i.e. if my target is 100 and my factor is 5%, the adjusted target will be 100*(1+0.05)=105
i.e. if my target is 100 and my factor is -5%, the adjusted target will be 100*(1+-0.05)=95
If the factor type is value, the adjusted value will be target + factor
i.e. if my target is 1000 and my factor is 200, the adjusted target will be will be 1000+200=1200
i.e. if my target is 1000 and my factor is -200, the adjusted target will be 1000-200=800
If there is more than one factor impacting a department and account or job code/pay code group combination, then the factors should layer on top of each other based on history order
If an efficiency factor does not exist for a particular account/job code, then the value in the new time class will be either flex or baseline target if flex is not used
This will happen after Flex is calculated
Include integration tests
*/
/*
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2018-04-18	IP		TK-57807	Fixed issue PR Statistic Sampling: 'Reallocate between departments' adjustment is calculated incorrectly
** 2		2019-01-17	GF		D-08031		Optimized PCG case
** 3        2019-06-14  OV      D-08158     Added join to JobCodeGroup
** 4        2019-10-22  KF      D-08819     FTE Baseline Calculation Issue
** 5        2022-08-23  BC      JAZZ-11498  Change Table Variable to Temporary Tables 
************************************************************
*/

DECLARE @IsFlexingEnabled INT = (
		SELECT value
		FROM [mr].[SystemSetting]
		WHERE NAME = 'Is Target Flexed'
		)

IF EXISTS (SELECT TOP 1 * FROM [mr].[EfficiencyFactor]) BEGIN
IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE #EfficiencyFactorScope	
CREATE TABLE  #EfficiencyFactorScope (
	EfficiencyFactorGUID [uniqueidentifier] NOT NULL
	,[DepartmentID] [int] NOT NULL
	,[JobCodeID] [int] NOT NULL
	,[FiscalYearID] [smallint] NOT NULL
	,[FiscalMonthID] [tinyint] NOT NULL
	,Value NUMERIC(25, 6) NOT NULL
	,Type TINYINT
	,PayCodeGroupID [int] not null
	,FactorType CHAR(1)
	,DateCreated DATETIME
	,UNIQUE CLUSTERED (
		FiscalYearID
		,FiscalMonthID
		,DepartmentID
		,JobCodeID
		,EfficiencyFactorGUID
		,PayCodeGroupID
		)
	);

WITH EfficiencyFactorScope
AS (
	SELECT *
		,rn = ROW_NUMBER() OVER (
			PARTITION BY FiscalYearID
			,FiscalMonthID
			,DepartmentID
			,JobCodeID
			,Type
			,PayCodeGroupID
			,EfficiencyFactorGUID ORDER BY FiscalYearID
				,FiscalMonthID
				,DepartmentID
				,JobCodeID
				,Type
				,PayCodeGroupID
				,EfficiencyFactorGUID
			)
	FROM (
		SELECT DISTINCT ef.EfficiencyFactorGUID
			,ef.FiscalYearID
			,efgd.FiscalMonthID
			,efd.DepartmentID
			,isnull(efgd.JobCodeID, djc.JobCodeID) AS JobCodeID
			,efgd.Value
			,ef.Type
			,efgd.PayCodeGroupID
			,ef.FactorType
			,ef.DateCreated
		FROM mr.EfficiencyFactor ef
		INNER JOIN mr.EfficiencyFactorDepartment efd ON ef.EfficiencyFactorGUID = efd.EfficiencyFactorGUID
		INNER JOIN mr.EfficiencyFactorPayrollDetails efgd ON efgd.EfficiencyFactorGUID = ef.EfficiencyFactorGUID
		left JOIN fw.DimJobCode djc ON efgd.JobCodeGroupID = djc.JobCodeGroupID and efgd.JobCodeID is null
		INNER JOIN (SELECT DISTINCT DepartmentID,JobCodeID FROM fw.FactPayRollSampledMonthly) scope on scope.JobCodeID = isnull(efgd.JobCodeID, djc.JobCodeID) and scope.DepartmentID = efd.DepartmentID
		left JOIN mr.EfficiencyFactorPayrollDetails efgd_exist ON efgd.EfficiencyFactorGUID = efgd_exist.EfficiencyFactorGUID and efgd.PayCodeGroupID = efgd_exist.PayCodeGroupID and efgd_exist.JobCodeID = djc.JobCodeID  and efgd_exist.FiscalMonthID = efgd.FiscalMonthID
		WHERE (@FiscalYearID = ef.FiscalYearID or @FiscalYearID = 0)  and (efgd_exist.JobCodeID is null or djc.JobCodeID is null) AND isnull(efgd.JobCodeID, djc.JobCodeID) IS NOT NULL
		AND ef.Type in (2,3) --Payroll Dollars&Hours
		) X
	)
INSERT INTO #EfficiencyFactorScope (
	EfficiencyFactorGUID
	,[DepartmentID]
	,[JobCodeID]
	,[FiscalYearID]
	,[FiscalMonthID]
	,Value
	,Type
	,PayCodeGroupID
	,FactorType
	,DateCreated
	)
SELECT EfficiencyFactorGUID
	,[DepartmentID]
	,[JobCodeID]
	,[FiscalYearID]
	,[FiscalMonthID]
	,Value
	,Type
	,PayCodeGroupID
	,FactorType
	,DateCreated
FROM EfficiencyFactorScope
WHERE RN = 1

DELETE FROM fw.FactPayRollSampledMonthly WHERE (@FiscalYearID = FiscalYearID or @FiscalYearID = 0) and TimeClassID = 22

INSERT INTO fw.FactPayRollSampledMonthly (DepartmentID,
JobCodeID,
FiscalYearID,
FiscalMonthID,
TimeClassID,
PayCodeGroupID,
IsDeleted,
Hours,
Dollars)
SELECT 
	DepartmentID
	,JobCodeID
	,FiscalYearID
	,FiscalMonthID
	,22 as TimeClassID
	,PayCodeGroupID
	,0 as IsDeleted
	,SUM(H) as Hours
	,SUM(D) as Dollars
FROM (
SELECT isnull(fact.DepartmentID,ToApply.DepartmentID) as DepartmentID
	,isnull(fact.JobCodeID,ToApply.JobCodeID) as JobCodeID
	,isnull(fact.FiscalYearID,ToApply.FiscalYearID) as FiscalYearID
	,isnull(fact.FiscalMonthID,ToApply.FiscalMonthID) as FiscalMonthID
	,isnull(fact.PayCodeGroupID,ToApply.PayCodeGroupID) as PayCodeGroupID
	,H = CASE WHEN Type = 3 and FactorType = 'P' THEN isnull(Hours,0.0)*isnull(Value,0.0)/100.00
			  WHEN Type = 3 and FactorType = 'V' THEN isnull(Value,0.0)
		 ELSE 0.0
		 END
	,D = CASE WHEN Type = 2 and FactorType = 'P' THEN isnull(Dollars,0.0)*isnull(Value,0.0)/100.00
			  WHEN Type = 2 and FactorType = 'V' THEN isnull(Value,0.0)
		 ELSE 0.0
		 END
FROM #EfficiencyFactorScope ToApply
INNER JOIN (SELECT DISTINCT DepartmentID,JobCodeID FROM fw.FactPayRollSampledMonthly) GenCand on 
	GenCand.DepartmentID = ToApply.DepartmentID
	AND GenCand.JobCodeID = ToApply.JobCodeID
FULL JOIN 
	(select DepartmentID
	,JobCodeID
	,FiscalYearID
	,FiscalMonthID
	,PayCodeGroupID
	,Hours
	,Dollars
	FROM
	fw.FactPayRollSampledMonthly
	
	WHERE (		(
			isnull(TimeClassID,0) = 4 			AND @IsFlexingEnabled = 1
			)
		OR (			isnull(TimeClassID,0) = 20			AND @IsFlexingEnabled = 0
			)
		)
	AND isnull(IsSystemGenerated,0) = 0	and (FiscalYearID = @FiscalYearID or @FiscalYearID = 0)
	) fact ON fact.DepartmentID = ToApply.DepartmentID
	AND fact.JobCodeID = ToApply.JobCodeID
	AND fact.FiscalYearID = ToApply.FiscalYearID
	AND fact.FiscalMonthID = ToApply.FiscalMonthID
	AND fact.PayCodeGroupID = ToApply.PayCodeGroupID
UNION ALL 
	select DepartmentID
	,JobCodeID
	,FiscalYearID
	,FiscalMonthID
	,PayCodeGroupID
	,Hours
	,Dollars
	FROM
	fw.FactPayRollSampledMonthly
	
	WHERE (		(
			isnull(TimeClassID,0) = 4 			AND @IsFlexingEnabled = 1
			)
		OR (			isnull(TimeClassID,0) = 20			AND @IsFlexingEnabled = 0
			)
		)
	AND isnull(IsSystemGenerated,0) = 0	and (FiscalYearID = @FiscalYearID or @FiscalYearID = 0)
) X
GROUP BY 
DepartmentID
	,JobCodeID
	,FiscalYearID
	,FiscalMonthID
	,PayCodeGroupID

exec [fw].[procFactMonthlyYTDPriorYearUpdate] @factTableName = 'fw.FactPayRollSampledMonthly',@keyNameCSV = 'JobCodeID,PayCodeGroupID,PayCodeID',@measureNameCSV = 'Dollars,Hours',@fiscalYearID  = 0,@timeClassID = 22,@isDebugOnly = 0
exec [fw].[procFactPayrollSampledMonthlyUpdateFTEs] @fiscalYearID = @FiscalYearID, @timeClassID = 22

END
END
IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE  #EfficiencyFactorScope
GO


---------------------------------------------

-- fw.procPayrollSampledDailyDetailedInsert
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2017-02-16  GF      B-14308		Created
** 2    2017-02-20  GF      D-05613		Add tests for zero rows, FTEs
** 3	2017-03-06  GF		B-14693		Ensure daily enabled
** 4	2017-04-04	IP		TK-40663	Added test to compare general sums
** 5	2017-05-10	IP		D-05913		Added testcase from rolling baseline target values
** 6	2017-06-07	IP					Commented out baseline test 
** 7	2017-06-15	IP		B-15086 	Modify SP to use unique temp table
** 8 	2017-06-19  IP				 	Modify SP to use unique temp table procPayrollSampledDailyDetailedInsert
** 9 	2017-06-23	IP					Fixed issue with transaction log out of memory procPayrollSampledDailyDetailedInsert
** 10	2017-09-08 	IP					Adding Budget Adjustments to fw_procPayrollSampledDailyDetailedInsert
** 11	2017-09-23 	IP					Adding Budget Adjustments to fw_procPayrollSampledDailyDetailedInsert
** 12 	2018-02-15 	IP					Add react to archived FTE Adjutments in fw_procPayrollSampledDailyDetailedInsert
** 13	2018-02-22	IP	 	D-06786		add department calculation for TC = 2 if dept is not in PR , Dept is in Budget Allocation
** 14	2018-03-08 	ip		B-18793		PR - Daily processing post action 2 week run
** 15	2018-05-17	IP 		D-07329		Returning fuctionality to include stats for departments using non-PR driver departments
** 16	2018-05-21	KF		D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 17	2018-05-17	IP 		TK-58509	reverting functionality of ignoring 0s
** 18	2018-05-17	IP 		TK-58523    reaplying changes for D-06786
** 19   2018-08-27  OV      D-07628		Fixed issu: PR Payroll Files Not Displaying in Data Sets
** 20   2018-08-28  IP      D-07628		Fixed issu: PR Payroll Files Not Displaying in Data Sets (add ignoring @fiscalYearID if @isCalcDaily is set)
** 21	2018-09-11	kzhuk	D-07649		PR Daily custom action calls procedures for wrong year
** 22  2018-10-05   OV     D-07728      fix: PR Payroll Daily Sampling: isPR=0 departments and Job Codes are not filtered out during sampling for one year
** 23  2019-02-25   OV     D-07697      fix: Daily custom action: FTEs are not calculated in case there was no data in the table before
** 24  2019-03-05   OV     D-08020      table variables @departments converted to temp tables #departmentIDs
** 25  2019-03-29   OV     D-07650      Payroll data are sampled for all Pay Period including after yesterday
** 26  2019-04-18   OV     B-20571      Allow clients to input daily budget Payroll data
** 27  2019-04-23   OV     B-20571      Take Dollars and Hours separately from different tables as Value, grouped by IDs and UnitType in the end
** 28  2019-05-14   OV     B-22955      Filtered procedure by new 'isDaily' column from DimJobCode
** 29  2019-07-24   OV     D-08629      FTEs are set to 0 for first Pay Period days belonging to previous year
** 30  2019-10-15   WR     D-08686      Run PR Process Task is filling transaction log
** 31  2019-11-25   IH     TK-80619     Rollback transaction log changes
** 32  2020-01-08	HV	    B-25788   	procPayrollSampledDailyInsert DBA Enhancements
** 33  2021-12-10	HV	    JAZZ-23990   procPayrollSampledDailyDetailedInsert Filling Up Temp DB
** 34  2021-12-16	HV	    JAZZ-23990   procPayrollSampledDailyDetailedInsert Filling Up Temp DB
** 35  2022-01-20	HV	    JAZZ-32256   PR Department Productivity Daily Page Performance Improvements
** 36  2022-02-15	HV	    JAZZ-33795   PR Department Productivity Daily Page: Compress view index
** 37  2022-03-21	HV	    JAZZ-31812   PR - Daily budget hours doubled in certain pay periods
							    JAZZ-22706   Year Changeover In Daily Staffing is inflating Prior Year Days from Transfer Proc Update
** 38  2022-10-27	ishah	 JAZZ-45100   Reuse split by batches functionality in existing procedure
** 39  2022-11-22	HV	 	JAZZ-44508   Automated Daily PR processing doesn't calculate future target, when system center processing does
** 40  2023-10-09	HV	 	JAZZ-61830   PR - Index and department filter changes - fw.procPayrollSampledDailyDetailedInsert and client.procFactPayrollSampledDailyDetailedFTEsInsert_Staging
** 41  2023-11-09	BS		JAZZ-62716	 PR -Transaction Log is filled out: fw.procPayrollSampledDailyDetailedInsert and client.procFactPayrollSampledDailyDetailedFTEsInsert_Staging (insert by batches)
** 42  2024-06-14   SM      JAZZ-71536  change JobCodeID from smallint to int
*************************************************************/
CREATE proc [fw].[procPayrollSampledDailyDetailedInsert] 
	@fiscalYearID int = 0,
	@isCalcDaily bit = 0,
	@isFeatureFlagOn bit = 0
with recompile
as	
	declare @yearOfSampling int = [fw].[GetPayPeriodSamplingYear] (@fiscalYearID, @isCalcDaily)
	
	DECLARE @currentDateOverride nvarchar(max) = (SELECT Value FROM [pi].[SystemSetting] WHERE Name = 'Current Date Override')
	DECLARE @currentDate date =  CASE 
								WHEN @currentDateOverride = '' THEN CAST(GETDATE() AS DATE)
								ELSE CAST (@currentDateOverride AS DATE) 
								END
	DECLARE @yesterday_date date = DATEADD(DAY, - 1, @currentDate)
	
	IF OBJECT_ID('tempdb..#PayrollSampledDailyDetailedStaging') IS NOT NULL  DROP TABLE #PayrollSampledDailyDetailedStaging
	declare @IterationFiscalYearID int
   
	IF OBJECT_ID('tempdb..#departmentsBudgetAllocations') IS NOT NULL DROP TABLE #departmentsBudgetAllocations
	create table #departmentsBudgetAllocations (val int primary key)
	insert into #departmentsBudgetAllocations (val)
	select 
		SourceDepartmentID as DepartmentID 
	from mr.BudgetReallocationAdjustment a
	inner join mr.BudgetReallocation r on r.BudgetReallocationGUID=a.BudgetReallocationGUID
	inner join FW.DimDepartment d on d.DepartmentID = r.TargetDepartmentID and d.IsPR = 1
	where SourceDepartmentID <> 0
		union  -- unique
	select 
		TargetDepartmentID as DepartmentID
	from mr.BudgetReallocationAdjustment a
	inner join mr.BudgetReallocation r on r.BudgetReallocationGUID=a.BudgetReallocationGUID
	inner join FW.DimDepartment d on d.DepartmentID = r.SourceDepartmentID and d.IsPR = 1 -- Filtering all departments that move data FROM selected
	where TargetDepartmentID <> 0

    IF OBJECT_ID('tempdb..#DailyCalcPeriodsScope') IS NOT NULL DROP TABLE #DailyCalcPeriodsScope
	
	select PayPeriodID,PayCycleID,PeriodStartCalendarDate,PeriodEndCalendarDate into #DailyCalcPeriodsScope
	from fw.DimPayPeriod 
	where 
		(@isCalcDaily = 1 and @yesterday_date BETWEEN PeriodStartCalendarDate and PeriodEndCalendarDate)  -- if @isCalcDaily = 1 is present we ignore what @yearOfSampling is passed to stored procedure (based on B-18793)
			or 
		(@isCalcDaily = 0 AND (@fiscalYearID = FiscalYearIDSecond or @fiscalYearID = 0)) -- if @isCalcDaily = 0 we should react to what @fiscalYearID is set 

	--cancel if not using daily
	if (not exists(select 1 from pi.SystemSetting where Name = 'PR Daily Enabled' and Value = '1')) begin return end
	
    --pull new data - actuals
	create table #PayrollSampledDailyDetailedStaging (DepartmentID int, JobCodeID int, PayCodeID int, PayCodeGroupID int, EmployeeID int, PayPeriodID int, DateID int, TimeClassID int, Hours  decimal(18,4), Dollars  decimal(18,4), FTEs decimal(18,4))
	
	-- Split by batches
	DECLARE @batchSize INT

	EXEC mr.procGetIntBatchSize
			@DefaultBatchSize = 120000000,
			@ResultBatchSize = @batchSize OUTPUT

	IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments
	CREATE TABLE #inputDepartments (DepartmentID INT, RecordsCount INT, BatchID INT)

	DECLARE
		@fromClause nvarchar(max) = '
	(
	select
			data.DepartmentID,
			data.JobCodeID,
			data.PayCodeID,
			pc.PayCodeGroupID,
			data.EmployeeID,
			pp.PayPeriodID,
			data.DateID,
			data.TimeClassID,
			sum(case when data.UnitTypeID = 51 and pc.IsHoursIgnored = 0 then data.Value else 0 end) as Hours,
			sum(case when data.UnitTypeID = 34 and pc.IsDollarsIgnored = 0 then data.Value else 0 end) as Dollars,
			0 AS FTEs
		from
			int.FactStaffingDaily data
			inner join [fw].[DimPayCode] pc on data.PayCodeID = pc.PayCodeID
			inner join fw.DimDepartment d on d.DepartmentID = data.DepartmentID
			inner join fw.DimDate dt on dt.DateID = data.DateID
			inner join fw.DimPayPeriod pp on pp.PayCycleID = d.PayCycleID and dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate
			inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID
		where
			pp.PayPeriodID != 0
			and data.IsDeleted = 0
			and data.Value != 0
			and d.IsPR = 1
			and TimeClassID = 1
		group by
			data.DepartmentID,
			data.JobCodeID,
			data.PayCodeID,
			pc.PayCodeGroupID,
			data.EmployeeID,
			pp.PayPeriodID,
			data.DateID,
			data.TimeClassID) X'
		
	INSERT INTO #inputDepartments
	EXEC dbo.procGetInputDataByBatches
	  	@batchSize = @batchSize,
		@columnName = 'DepartmentID',
		@tableAlias = 'X',
		@fromClause = @fromClause,
		@whereClause = '',
		@isDebug = 0

	DECLARE @BatchID INT, @MaxBatchID INT
	SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

	-- Loop thru batches and insert data
	SET @BatchID = 1
	WHILE @BatchID <= @MaxBatchID
	BEGIN
	    insert into #PayrollSampledDailyDetailedStaging (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, DateID, TimeClassID, Hours, Dollars, FTEs)
		select
			data.DepartmentID,
			data.JobCodeID,
			data.PayCodeID,
			pc.PayCodeGroupID,
			data.EmployeeID,
			pp.PayPeriodID,
			data.DateID,
			data.TimeClassID,
			sum(case when data.UnitTypeID = 51 and pc.IsHoursIgnored = 0 then data.Value else 0 end) as Hours,
			sum(case when data.UnitTypeID = 34 and pc.IsDollarsIgnored = 0 then data.Value else 0 end) as Dollars,
			0 AS FTEs
		from
			int.FactStaffingDaily data
			inner join [fw].[DimPayCode] pc on data.PayCodeID = pc.PayCodeID
			inner join fw.DimDepartment d on d.DepartmentID = data.DepartmentID
			inner join fw.DimDate dt on dt.DateID = data.DateID
			inner join fw.DimPayPeriod pp on pp.PayCycleID = d.PayCycleID and dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate
			inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID
			inner join #inputDepartments ID ON ID.DepartmentID = data.DepartmentID
		where
			pp.PayPeriodID != 0
			and data.IsDeleted = 0
			and data.Value != 0
			and d.IsPR = 1
			and TimeClassID = 1
			and ID.BatchID = @BatchID
--			and (@fiscalYearID = 0 or dt.FiscalYear = @fiscalYearID) -- #DailyCalcPeriodsScope already contains all Pay Periods that should be recalculated, so filtering by year could bring destructive effect in case @fisclaYearID <> 'calendar year' (conflict @FiscalYearID and @isCalcDaily)
		group by
			data.DepartmentID,
			data.JobCodeID,
			data.PayCodeID,
			pc.PayCodeGroupID,
			data.EmployeeID,
			pp.PayPeriodID,
			data.DateID,
			data.TimeClassID
				
		SET @BatchID = @BatchID + 1
	END
    --pull new data - budget from daily, payperiod, monthly data
	IF OBJECT_ID('tempdb..#StaffingDaily') IS NOT NULL  DROP TABLE #StaffingDaily
	 CREATE TABLE #StaffingDaily (
                DepartmentID INT,
                JobCodeID int,
                PayCodeID SMALLINT,
                PayCodeGroupID INT,
                DateID INT,
                TimeClassID TINYINT,
                PayPeriodID SMALLINT,
                UnitTypeID TINYINT,
                IsHoursIgnored BIT,
                IsDollarsIgnored BIT,
                Value DECIMAL(19,4))

	-- Split by batches
	TRUNCATE TABLE #inputDepartments

	SET @fromClause = '
	(
	SELECT 
			FACT.DepartmentID,
			FACT.JobCodeID,
			FACT.PayCodeID,
			PC.PayCodeGroupID,
			DT.DateID,
			FACT.TimeClassID,
			PP.PayPeriodID,
			FACT.UnitTypeID,
			pc.IsHoursIgnored,
		    pc.IsDollarsIgnored
	FROM int.FactStaffingDaily FACT
			inner join [fw].[DimPayCode] PC on PC.PayCodeID = FACT.PayCodeID
			inner join [fw].[DimDepartment] D on D.Departmentid = FACT.DepartmentID
			inner join [fw].[DimDate] DT on DT.DateID = FACT.dateID
			inner join fw.dimpayPeriod PP on pp.PayCycleID = d.PayCycleID and dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate
			inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID
			left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID

		where
			 DT.FiscalMonth != 0 
			and FACT.FiscalYearID != 0
			and FACT.IsDeleted = 0
			and (D.IsPR = 1 or dba.val IS NOT NULL)
			and FACT.TimeClassID = 2
			and FACT.DepartmentID != 0
     	group by 
			FACT.DepartmentID,
			FACT.JobCodeID,
			FACT.PayCodeID,
			PC.PayCodeGroupID,
			DT.DateID,
			FACT.TimeClassID,
			PP.PayPeriodID,
			FACT.UnitTypeID,
	   	    pc.IsHoursIgnored,
		    pc.IsDollarsIgnored) X'
		
	INSERT INTO #inputDepartments
	EXEC dbo.procGetInputDataByBatches
	  	@batchSize = @batchSize,
		@columnName = 'DepartmentID',
		@tableAlias = 'X',
		@fromClause = @fromClause,
		@whereClause = '',
		@isDebug = 0

	SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

	-- Loop thru batches and insert data
	SET @BatchID = 1
	WHILE @BatchID <= @MaxBatchID
	BEGIN
	   insert into #StaffingDaily(DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, DateID, TimeClassID, PayPeriodID, UnitTypeID, IsHoursIgnored, IsDollarsIgnored, Value)
	   select
			FACT.DepartmentID,
			FACT.JobCodeID,
			FACT.PayCodeID,
			PC.PayCodeGroupID,
			DT.DateID,
			FACT.TimeClassID,
			PP.PayPeriodID,
			FACT.UnitTypeID,
	   	    pc.IsHoursIgnored,
		    pc.IsDollarsIgnored,
			sum(FACT.Value) AS Value
       from
			int.FactStaffingDaily FACT
			inner join [fw].[DimPayCode] PC on PC.PayCodeID = FACT.PayCodeID
			inner join [fw].[DimDepartment] D on D.Departmentid = FACT.DepartmentID	           
			inner join [fw].[DimDate] DT on DT.DateID = FACT.dateID
			inner join fw.dimpayPeriod PP on pp.PayCycleID = d.PayCycleID and dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate
			inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID
			inner join #inputDepartments ID ON ID.DepartmentID = FACT.DepartmentID
			left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID

		where
			 DT.FiscalMonth != 0 
			and FACT.FiscalYearID != 0
			and FACT.IsDeleted = 0
			and (D.IsPR = 1 or dba.val IS NOT NULL)
			and FACT.TimeClassID = 2
			and FACT.DepartmentID != 0
			and ID.BatchID = @BatchID

     	group by 
			FACT.DepartmentID,
			FACT.JobCodeID,
			FACT.PayCodeID,
			PC.PayCodeGroupID,
			DT.DateID,
			FACT.TimeClassID,
			PP.PayPeriodID,
			FACT.UnitTypeID,
	   	    pc.IsHoursIgnored,
		    pc.IsDollarsIgnored
				
		SET @BatchID = @BatchID + 1
	END
-------------------------------------------------------------------------------------------------------------------------------------
-- Split by batches

	TRUNCATE TABLE #inputDepartments

	SET @fromClause = '
	( 
	SELECT 
			FACT.DepartmentID,
			FACT.JobCodeID,
			FACT.PayCodeID,
			PC.PayCodeGroupID,
			DT.DateID,
			FACT.TimeClassID,
			PP.PayPeriodID,
			FACT.UnitTypeID,
	   	    pc.IsHoursIgnored,
		    pc.IsDollarsIgnored
	FROM int.FactStaffingByPayPeriod FACT 
			inner join [fw].[DimPayCode] PC on PC.PayCodeID = FACT.PayCodeID
			inner join [fw].[DimDepartment] D on D.Departmentid = FACT.DepartmentID
			inner join fw.DimPayPeriod pp on pp.PayPeriodID = FACT.PayPeriodID
			inner join [fw].[DimDate] DT on dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate
			left join #StaffingDaily spp on SPP.PayPeriodID = FACT.PayPeriodID and
											SPP.DepartmentID = FACT.DepartmentID and
											SPP.JobCodeID = FACT.JobCodeID  and
											SPP.PayCodeID = FACT.PayCodeID and
											SPP.TimeClassID = FACT.TimeClassID and
											SPP.UnitTypeID = FACT.UnitTypeID
			inner join fw.DimPayCycle PCC on PCC.PayCycleID = PP.PayCycleID
			inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID
			left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID
         where
			spp.DepartmentID IS NULL
			and DT.FiscalMonth != 0 
			and FACT.FiscalYearID != 0
			and FACT.IsDeleted = 0
			and (D.IsPR = 1 or dba.val IS NOT NULL)
			and FACT.TimeClassID = 2
			and FACT.DepartmentID != 0
	     group by 
			FACT.DepartmentID,
			FACT.JobCodeID,
			FACT.PayCodeID,
			PC.PayCodeGroupID,
			DT.DateID,
			FACT.TimeClassID,
			PP.PayPeriodID,
			FACT.UnitTypeID,
	   	    pc.IsHoursIgnored,
		    pc.IsDollarsIgnored ) X'
		
	INSERT INTO #inputDepartments
	EXEC dbo.procGetInputDataByBatches
	  	@batchSize = @batchSize,
		@columnName = 'DepartmentID',
		@tableAlias = 'X',
		@fromClause = @fromClause,
		@whereClause = '',
		@isDebug = 0

	SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

	-- Loop thru batches and insert data
	SET @BatchID = 1
	WHILE @BatchID <= @MaxBatchID
	BEGIN
	   insert into #StaffingDaily(DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, DateID, TimeClassID, PayPeriodID, UnitTypeID, IsHoursIgnored, IsDollarsIgnored, Value)
	   select
			FACT.DepartmentID,
			FACT.JobCodeID,
			FACT.PayCodeID,
			PC.PayCodeGroupID,
			DT.DateID,
			FACT.TimeClassID,
			PP.PayPeriodID,
			FACT.UnitTypeID,
	   	    pc.IsHoursIgnored,
		    pc.IsDollarsIgnored,
			sum(FACT.Value/PCC.PeriodDays) AS Value
		from
			int.FactStaffingByPayPeriod FACT 
			inner join [fw].[DimPayCode] PC on PC.PayCodeID = FACT.PayCodeID
			inner join [fw].[DimDepartment] D on D.Departmentid = FACT.DepartmentID	       
			inner join fw.DimPayPeriod pp on pp.PayPeriodID = FACT.PayPeriodID    
			inner join [fw].[DimDate] DT on dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate
			left join #StaffingDaily spp on SPP.PayPeriodID = FACT.PayPeriodID and
											SPP.DepartmentID = FACT.DepartmentID and
											SPP.JobCodeID = FACT.JobCodeID  and
											SPP.PayCodeID = FACT.PayCodeID and
											SPP.TimeClassID = FACT.TimeClassID and
											SPP.UnitTypeID = FACT.UnitTypeID
			inner join fw.DimPayCycle PCC on PCC.PayCycleID = PP.PayCycleID
			inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID
			left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID
			inner join #inputDepartments ID ON ID.DepartmentID = FACT.DepartmentID
         where
			spp.DepartmentID IS NULL
			and DT.FiscalMonth != 0 
			and FACT.FiscalYearID != 0
			and FACT.IsDeleted = 0
			and (D.IsPR = 1 or dba.val IS NOT NULL)
			and FACT.TimeClassID = 2
			and FACT.DepartmentID != 0
			and ID.BatchID = @BatchID
	     group by 
			FACT.DepartmentID,
			FACT.JobCodeID,
			FACT.PayCodeID,
			PC.PayCodeGroupID,
			DT.DateID,
			FACT.TimeClassID,
			PP.PayPeriodID,
			FACT.UnitTypeID,
	   	    pc.IsHoursIgnored,
		    pc.IsDollarsIgnored
				
		SET @BatchID = @BatchID + 1
	END
--------------------------------------------------------------------------------------------------------------------
TRUNCATE TABLE #inputDepartments

	SET @fromClause = '
	int.FactStaffing FACT
	INNER JOIN fw.DimDepartment d ON d.DepartmentID = FACT.DepartmentID'
		
	INSERT INTO #inputDepartments
	EXEC dbo.procGetInputDataByBatches
	  	@batchSize = @batchSize,
		@columnName = 'DepartmentID',
		@tableAlias = 'FACT',
		@fromClause = @fromClause,
		@whereClause = '',
		@isDebug = 0

	SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

	-- Loop thru batches and insert data
	SET @BatchID = 1
	WHILE @BatchID <= @MaxBatchID
	BEGIN
		insert into #StaffingDaily(DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, DateID, TimeClassID, PayPeriodID, UnitTypeID, IsHoursIgnored, IsDollarsIgnored, Value)
		select
			FACT.DepartmentID,
			FACT.JobCodeID,
			FACT.PayCodeID,
			PC.PayCodeGroupID,
			DT.DateID,
			FACT.TimeClassID,
			PP.PayPeriodID,
			FACT.UnitTypeID,
	   	    pc.IsHoursIgnored,
		    pc.IsDollarsIgnored,
			sum(FACT.Value/ dbo.GetDaysInMonth(DT.CalendarDateTime)) as Value 
		from
			[int].[FactStaffing] FACT
			inner join [fw].[DimPayCode] PC on PC.PayCodeID = FACT.PayCodeID
			inner join [fw].[DimDepartment] D on D.Departmentid = FACT.DepartmentID	           
			inner join [fw].[DimDate] DT on DT.CalendarMonth = FACT.FiscalMonthID and DT.FiscalYear = FACT.FiscalYearID
			inner join fw.DimPayperiod pp on pp.PayCycleID = d.PayCycleID and dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate
			left join #StaffingDaily spp on SPP.PayPeriodID = PP.PayPeriodID and
											SPP.DepartmentID = FACT.DepartmentID and
											SPP.JobCodeID = FACT.JobCodeID  and
											SPP.PayCodeID = FACT.PayCodeID and
											SPP.TimeClassID = FACT.TimeClassID and
											SPP.UnitTypeID = FACT.UnitTypeID
			inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID
			left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID
			inner join #inputDepartments ID ON ID.DepartmentID = FACT.DepartmentID
		where
		    spp.DepartmentID is null
			and FACT.FiscalMonthID != 0 
			and FACT.FiscalYearID != 0
			and FACT.IsDeleted = 0
			and (D.IsPR = 1 or dba.val IS NOT NULL)
			and FACT.TimeClassID = 2
			and FACT.DepartmentID != 0
			and ID.BatchID = @BatchID
		group by 
			FACT.DepartmentID,
			FACT.JobCodeID,
			FACT.PayCodeID,
			PC.PayCodeGroupID,
			DT.DateID,
			FACT.TimeClassID,
			PP.PayPeriodID,
			FACT.UnitTypeID,
	   	    pc.IsHoursIgnored,
		    pc.IsDollarsIgnored
				
		SET @BatchID = @BatchID + 1
	END


	TRUNCATE TABLE #inputDepartments

	SET @fromClause = '
	(SELECT G.DepartmentID, G.JobCodeID, G.PayCodeID, G.PayCodeGroupID, G.PayPeriodID, G.DateID, G.TimeClassID FROM #StaffingDaily G
	INNER JOIN fw.DimJobCode jc on G.jobCodeID = jc.JobCodeID
	WHERE jc.IsPR = 1 and jc.IsDaily = 1
	GROUP BY G.DepartmentID, G.JobCodeID, G.PayCodeID, G.PayCodeGroupID, G.PayPeriodID, G.DateID, G.TimeClassID) X'

	INSERT INTO #inputDepartments
	EXEC dbo.procGetInputDataByBatches
	  	@batchSize = @batchSize,
		@columnName = 'DepartmentID',
		@tableAlias = 'X',
		@fromClause = @fromClause,
		@whereClause = '',
		@isDebug = 0

	SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

	-- Loop thru batches and insert data
	SET @BatchID = 1
	WHILE @BatchID <= @MaxBatchID
	BEGIN
		insert into #PayrollSampledDailyDetailedStaging (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, DateID, TimeClassID, Hours, Dollars, FTEs)
		select G.DepartmentID, G.JobCodeID, G.PayCodeID, G.PayCodeGroupID, 0 as EmployeeID, G.PayPeriodID, G.DateID, G.TimeClassID, 
		SUM(case when G.UnitTypeID = 51 and G.IsHoursIgnored = 0 then G.Value else 0 end) as Hours, 
		SUM(case when G.UnitTypeID = 34 and G.IsDollarsIgnored = 0 then G.Value else 0 end) as Dollars,
		0
		from #StaffingDaily G
		inner join #inputDepartments ID ON ID.DepartmentID = G.DepartmentID
		inner join fw.DimJobCode jc on G.jobCodeID = jc.JobCodeID
		WHERE jc.IsPR = 1 and jc.IsDaily = 1 and ID.BatchID = @BatchID
		GROUP BY G.DepartmentID, G.JobCodeID, G.PayCodeID, G.PayCodeGroupID, G.PayPeriodID, G.DateID, G.TimeClassID
				
		SET @BatchID = @BatchID + 1
	END
	
	/*Budget adjustments FTE start*/
		--pull new data - adjustments
	DECLARE @NonProdGroupID INT = (
		SELECT TOP 1 pcg.PayCodeGroupID
		FROM fw.DimProductiveClass pc
		INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID
		WHERE pc.Name = 'Non-Productive' AND pcg.PayCodeGroupID != 0
		ORDER BY pcg.SortOrder)

	DECLARE @ProdGroupID INT = (
		SELECT TOP 1 pcg.PayCodeGroupID
		FROM fw.DimProductiveClass pc
		INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID
		WHERE pc.Name = 'Productive' AND pcg.PayCodeGroupID != 0
		ORDER BY pcg.SortOrder)

	DECLARE @NonProdPayCodeID INT = (
		SELECT TOP 1 pcg.DefaultPayCodeID
		FROM fw.DimProductiveClass pc
		INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID
		WHERE pc.Name = 'Non-Productive' AND pcg.PayCodeGroupID != 0
		ORDER BY pcg.SortOrder)

	DECLARE @ProdPayCodeID INT = (
		SELECT TOP 1 pcg.DefaultPayCodeID
		FROM fw.DimProductiveClass pc
		INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID
		WHERE pc.Name = 'Productive' AND pcg.PayCodeGroupID != 0
		ORDER BY pcg.SortOrder)
		
	insert into #PayrollSampledDailyDetailedStaging (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, DateID, TimeClassID, Hours, Dollars)
	SELECT 
		Adj.DepartmentID,
		Adj.JobCodeID,
		Adj.PayCodeId,
		Adj.PayCodeGroupID,
		0 as EmployeeID,
		PP.PayPeriodID,
		dt.DateID,
		2 AS TimeClassID, -- always Budgeted
		sum(Adj.Hours / dbo.GetDaysInMonth(DT.CalendarDateTime)) AS Hours, 
		0 AS Dollars
	FROM (
		SELECT 
			b.DepartmentID,
			b.JobCodeID,
			@ProdPayCodeID as PayCodeID,
			@ProdGroupID AS PayCodeGroupID,
			b.FiscalYearID,
			ba.FiscalMonthID,
			ba.ProductiveChange AS Hours
		FROM mr.BudgetPayrollReallocationAdjustment ba
		INNER JOIN mr.BudgetPayrollReallocation b ON b.BudgetPayrollReallocationGUID = ba.BudgetPayrollReallocationGUID
		LEFT JOIN 
		(select SourceDepartmentID as DepartmentID,
			 SourceJobCodeID as JobCodeID,
			 FiscalYearID,
			 FiscalMonthID
		FROM [mr].[BudgetReallocation] b
		INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		WHERE DataType = 1
		UNION ALL
		select TargetDepartmentID as DepartmentID,
			 TargetJobCodeID as JobCodeID,
			 FiscalYearID,
			 FiscalMonthID
		FROM [mr].[BudgetReallocation] b
		INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		WHERE DataType = 1
		) fact on fact.DepartmentID = b.DepartmentID and fact.JobCodeID = b.JobCodeID and fact.FiscalYearID = b.FiscalYearID and fact.FiscalMonthID = ba.FiscalMonthID
		WHERE (@yearOfSampling = 0 or b.FiscalYearID = @yearOfSampling) -- if @isCalcDaily = 1 we'll take calndar year, else - @FiscalYearId
		and fact.DepartmentID is null and b.Archived = 0
		UNION ALL
		SELECT b.DepartmentID,
			b.JobCodeID,
			@NonProdPayCodeID as PayCodeID,
			@NonProdGroupID AS PayCodeGroupID,
			b.FiscalYearID,
			ba.FiscalMonthID,
			ba.NonProductiveChange AS Hours
		FROM mr.BudgetPayrollReallocationAdjustment ba
		INNER JOIN mr.BudgetPayrollReallocation b ON b.BudgetPayrollReallocationGUID = ba.BudgetPayrollReallocationGUID
		LEFT JOIN 
		(select SourceDepartmentID as DepartmentID,
			 SourceJobCodeID as JobCodeID,
			 FiscalYearID,
			 FiscalMonthID
		FROM [mr].[BudgetReallocation] b
		INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		WHERE DataType = 1
		UNION ALL
		select TargetDepartmentID as DepartmentID,
			 TargetJobCodeID as JobCodeID,
			 FiscalYearID,
			 FiscalMonthID
		FROM [mr].[BudgetReallocation] b
		INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		WHERE DataType = 1
		) fact on fact.DepartmentID = b.DepartmentID and fact.JobCodeID = b.JobCodeID and fact.FiscalYearID = b.FiscalYearID and fact.FiscalMonthID = ba.FiscalMonthID
		WHERE (@yearOfSampling = 0 or b.FiscalYearID = @yearOfSampling) -- if @isCalcDaily = 1 we'll take calndar year, else - @FiscalYearId
		and fact.DepartmentID is null and b.Archived = 0
		) AS Adj
	INNER JOIN fw.DimDepartment dd on adj.DepartmentID = dd.DepartmentID
	INNER JOIN (
		SELECT 
			p.[PayPeriodID],
			p.PayCycleID,
			p.[PeriodNumber],
			p.[FiscalMonthIDStart] AS FiscalMonthID,
			p.[FiscalYearIDStart] AS FiscalYearID,
			p.[PeriodWeightStart] AS PreriodWeight,
			p.PeriodStartCalendarDate,
			p.PeriodEndCalendarDate
		FROM [fw].[DimPayPeriod] p inner join #DailyCalcPeriodsScope cp on cp.PayPeriodID = p.PayPeriodID
		UNION ALL
		SELECT 
			p.[PayPeriodID],
			p.PayCycleID,
			p.[PeriodNumber],
			p.FiscalMonthIDSecond AS FiscalMonthID,
			p.FiscalYearIDSecond AS FiscalYearID,
			p.PeriodWeightSecond AS PreriodWeight,
			p.PeriodStartCalendarDate,
			p.PeriodEndCalendarDate
		FROM [fw].[DimPayPeriod] p inner join #DailyCalcPeriodsScope cp on cp.PayPeriodID = p.PayPeriodID
				) PP ON PP.FiscalYearID = Adj.FiscalYearID
		AND pp.FiscalMonthID = adj.FiscalMonthID
		and pp.PayCycleID = dd.PayCycleID
	inner join [fw].[DimDate] DT on DT.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate and dt.FiscalYear = pp.FiscalYearID
	inner join #DailyCalcPeriodsScope dpc on dpc.PayPeriodID = pp.PayPeriodID
	WHERE PP.PreriodWeight <> 0
	GROUP BY Adj.DepartmentID,
		Adj.JobCodeID,
		dt.dateID,
		Adj.PayCodeID,
		Adj.PayCodeGroupID,
		PP.PayPeriodID
	HAVING sum(Adj.Hours * PP.PreriodWeight) <> 0


	/*Budget adjustments FTE end*/
	
	-- BudgetAdjustments Start
	declare @iteration int = 1 
	DECLARE @BudgetReallocationGUID uniqueidentifier,@date datetime,@BudgetReallocationType varchar(50)

	DECLARE BRA_cursor CURSOR FOR   
	SELECT distinct BudgetReallocationGUID,date,BudgetReallocationType from fw.BudgetReallocationWithDefinedType
	WHERE (@yearOfSampling = 0 or FiscalYearID = @yearOfSampling) -- if @isCalcDaily = 1 we'll take calndar year, else - @FiscalYearId
	and DataType = 1
	ORDER BY date;  

	OPEN BRA_cursor  

	FETCH NEXT FROM BRA_cursor
	INTO @BudgetReallocationGUID,@date,@BudgetReallocationType   

	WHILE @@FETCH_STATUS = 0  
	BEGIN  
		BEGIN
			INSERT INTO #PayrollSampledDailyDetailedStaging (DepartmentID, JobCodeID, EmployeeID, PayPeriodID, PayCodeID, PayCodeGroupID, DateID, TimeClassID, Hours, Dollars, FTEs)
			SELECT TargetDepartmentID as DepartmentID,TargetJobCodeID as JobCodeID, stt.EmployeeID, PayPeriodID, stt.PayCodeID, stt.PayCodeGroupID, stt.DateID, stt.TimeClassID, stt.Hours, stt.Dollars, stt.FTEs
			FROM #PayrollSampledDailyDetailedStaging STT
			INNER JOIN fw.DimDate dt on dt.DateID = stt.DateID
			INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceJobCodeID = stt.JobCodeID and b.FiscalYearID = dt.FiscalYear
			INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and dt.CalendarMonth = ba.FiscalMonthID
			where 
				b.BudgetReallocationGUID = @BudgetReallocationGUID
				and TimeClassID = 2
				and DataType = 1


			UPDATE STT
			SET Dollars = 0,
				Hours = 0,
				FTEs = 0
			FROM #PayrollSampledDailyDetailedStaging STT
			INNER JOIN fw.DimDate dt on dt.DateID = stt.DateID
			INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID  = stt.DepartmentID and b.SourceJobCodeID = stt.JobCodeID and b.FiscalYearID = dt.FiscalYear
			INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and dt.CalendarMonth = ba.FiscalMonthID
			where 
				b.BudgetReallocationGUID = @BudgetReallocationGUID
				and TimeClassID = 2
				and DataType = 1
		END

		set @iteration  = @iteration +1

		FETCH NEXT FROM BRA_cursor   
		INTO @BudgetReallocationGUID,@date,@BudgetReallocationType   
	END   
	CLOSE BRA_cursor;  
	DEALLOCATE BRA_cursor;  
	-- BudgetAdjustments END

    --calculate baseline target
    declare @targetType int = (select Value from pi.SystemSetting where Name = 'Target Basis')
    if (@targetType = 2) begin
	    --baseline target is based on budget, pull from monthly data
		TRUNCATE TABLE #inputDepartments

		SET @fromClause = '
		#PayrollSampledDailyDetailedStaging X
		WHERE X.TimeClassID = 2'

		INSERT INTO #inputDepartments
		EXEC dbo.procGetInputDataByBatches
		  	@batchSize = @batchSize,
			@columnName = 'DepartmentID',
			@tableAlias = 'X',
			@fromClause = @fromClause,
			@whereClause = '',
			@isDebug = 0

		SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

		-- Loop thru batches and insert data
		SET @BatchID = 1
		WHILE @BatchID <= @MaxBatchID
		BEGIN
			insert into #PayrollSampledDailyDetailedStaging (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, DateID, TimeClassID, Hours, Dollars, FTEs)
		    select PS.DepartmentID, PS.JobCodeID, PS.PayCodeID, PS.PayCodeGroupID, PS.EmployeeID, PS.PayPeriodID, PS.DateID, 20, PS.Hours, PS.Dollars, PS.FTEs
		    from #PayrollSampledDailyDetailedStaging PS
			inner join #inputDepartments ID ON ID.DepartmentID = PS.DepartmentID
		    where PS.TimeClassID = 2 and ID.BatchID = @BatchID

			SET @BatchID = @BatchID + 1
		END
    end else if(@targetType = 10) begin
		--baseline target is based on rolling period average, pull from pay period data

		TRUNCATE TABLE #inputDepartments

		SET @fromClause = '
		(
		select
		    FACT.DepartmentID,
		    FACT.JobCodeID,
		    FACT.PayCodeID,
		    FACT.PayCodeGroupID,
		    FACT.EmployeeID,
		    FACT.PayPeriodID,
		    DT.DateID,
		    FACT.TimeClassID,
		    SUM(FACT.Hours) as Hours,
            SUM(FACT.Dollars) as Dollars
	    from
		    fw.FactPayrollSampledPayPeriodDetailed FACT
		    inner join [fw].[DimPayPeriod] PP on PP.PayPeriodID = FACT.PayPeriodID
		    inner join [fw].[DimDate] DT on DT.CalendarDateTime between PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate
			inner join [fw].[DimDepartment] D on D.DepartmentID = FACT.DepartmentID
			inner join #DailyCalcPeriodsScope dpc on FACT.PayPeriodID = dpc.PayPeriodID
	    where
		    FACT.PayPeriodID != 0
			and FACT.IsDeleted = 0
			and (FACT.Hours != 0 or FACT.Dollars != 0)     
			and D.IsPR = 1
		    and FACT.TimeClassID = 20
		    and FACT.DepartmentID <> 0
			--and (@fiscalYearID = 0 or DT.FiscalYear = @fiscalYearID)
	    group by 
		    FACT.DepartmentID,
		    FACT.JobCodeID,
		    FACT.PayCodeID,
		    FACT.PayCodeGroupID,
		    FACT.EmployeeID,
		    FACT.PayPeriodID,
		    DT.DateID,
		    FACT.TimeClassID) X'

		INSERT INTO #inputDepartments
		EXEC dbo.procGetInputDataByBatches
		  	@batchSize = @batchSize,
			@columnName = 'DepartmentID',
			@tableAlias = 'X',
			@fromClause = @fromClause,
			@whereClause = '',
			@isDebug = 0

		SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

		-- Loop thru batches and insert data
		SET @BatchID = 1
		WHILE @BatchID <= @MaxBatchID
		BEGIN
			;with groupedBaselineTargetPayroll as(
			select
			    FACT.DepartmentID,
			    FACT.JobCodeID,
			    FACT.PayCodeID,
			    FACT.PayCodeGroupID,
			    FACT.EmployeeID,
			    FACT.PayPeriodID,
			    DT.DateID,
			    FACT.TimeClassID,
			    SUM(FACT.Hours) as Hours,
			    SUM(FACT.Dollars) as Dollars
			from
			    fw.FactPayrollSampledPayPeriodDetailed FACT
			    inner join [fw].[DimPayPeriod] PP on PP.PayPeriodID = FACT.PayPeriodID
			    inner join [fw].[DimDate] DT on DT.CalendarDateTime between PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate
				inner join [fw].[DimDepartment] D on D.DepartmentID = FACT.DepartmentID
				inner join #DailyCalcPeriodsScope dpc on FACT.PayPeriodID = dpc.PayPeriodID
			where
			    FACT.PayPeriodID != 0
				and FACT.IsDeleted = 0
				and (FACT.Hours != 0 or FACT.Dollars != 0)     
				and D.IsPR = 1
			    and FACT.TimeClassID = 20
			    and FACT.DepartmentID <> 0
				--and (@fiscalYearID = 0 or DT.FiscalYear = @fiscalYearID)
			group by 
			    FACT.DepartmentID,
			    FACT.JobCodeID,
			    FACT.PayCodeID,
			    FACT.PayCodeGroupID,
			    FACT.EmployeeID,
			    FACT.PayPeriodID,
			    DT.DateID,
			    FACT.TimeClassID)
			insert into #PayrollSampledDailyDetailedStaging (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, DateID, TimeClassID, Hours, Dollars, FTEs)
			select G.DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, G.PayPeriodID, DateID, TimeClassID, Hours / PP.PeriodDays, Dollars / PP.PeriodDays, 0
			from groupedBaselineTargetPayroll G
			inner join fw.DimPayPeriod PP on PP.PayPeriodID = G.PayPeriodID
			inner join #inputDepartments ID ON ID.DepartmentID = G.DepartmentID
			where ID.BatchID = @BatchID

			SET @BatchID = @BatchID + 1
		END
    end

 	--calculate FTEs		

	IF @fiscalYearID = 0 and @isCalcDaily = 0 and @isFeatureFlagOn = 1
	BEGIN
		IF OBJECT_ID('tempdb..#PayrollSampledDailyDetailedFTEs') IS NOT NULL  DROP TABLE #PayrollSampledDailyDetailedFTEs
		create table #PayrollSampledDailyDetailedFTEs (DepartmentID int, JobCodeID int, PayCodeID int, PayCodeGroupID int, EmployeeID int, PayPeriodID int, DateID int, TimeClassID int, FTEs decimal(18,4))
		exec client.procFactPayrollSampledDailyDetailedFTEsInsert_Staging @fiscalYearID =  @yearOfSampling, @isFeatureFlagOn = @isFeatureFlagOn
	END
	ELSE 
	BEGIN
		exec client.procFactPayrollSampledDailyDetailedFTEsInsert_Staging @fiscalYearID =  @yearOfSampling
	END
	
	--!!!Removing all records where Department is not PR
	delete fact
	from #PayrollSampledDailyDetailedStaging fact
	inner join fw.dimDepartment d on d.DepartmentID = fact.DepartmentID and d.isPR = 0
	  
	
	IF @fiscalYearID = 0 and @isCalcDaily = 0 -- if all parameters shows that we are recalculating everything 
	BEGIN
	EXEC dbo.procSysDropIndex @schema = 'fw', @table = 'viewFactPayrollSampledDailyDetailedHours', @indexName = 'CU_viewFactPayrollSampledDailyDetailedHours', @isView = 1
	truncate table [fw].[FactPayrollSampledDailyDetailed]
	DBCC CHECKIDENT('[fw].[FactPayrollSampledDailyDetailed]', RESEED, 0);
	
	CREATE CLUSTERED INDEX CORE_DepartmentID on #PayrollSampledDailyDetailedStaging (DepartmentID) with (data_compression = page)
			
	IF @isFeatureFlagOn = 1
	BEGIN
		CREATE CLUSTERED INDEX CORE_DepartmentID on #PayrollSampledDailyDetailedFTEs (DepartmentID) with (data_compression = page)

	    -- Drop Indexes
		EXEC dbo.procSysDropIndex @schema = 'fw', @table = 'FactPayrollSampledDailyDetailed', @indexName = 'IDX_FactPayrollSampledDailyDetailed'
		EXEC dbo.procSysDropIndex @schema = 'fw', @table = 'FactPayrollSampledDailyDetailed', @indexName = 'NCNU_IsDeleted'

		EXEC mr.procGetIntBatchSize
			@DefaultBatchSize = 60000000,
			@ResultBatchSize = @batchSize OUTPUT


		SET @fromClause = '
		(
			select
				f.DepartmentID,
				f.JobCodeID,
				f.PayCodeID,
				f.PayCodeGroupID,
				f.EmployeeID,
				f.PayPeriodID,
				f.DateID,
				f.TimeClassID,
				SUM(f.Hours) as Hours,
				SUM(f.Dollars) as Dollars,
				SUM(isnull(fte.FTEs,0)) as FTEs,
				0 as isDeleted
			from
			#PayrollSampledDailyDetailedStaging f
			inner join fw.DimJobCode jc on f.JobCodeID = jc.JobCodeID
			left join #PayrollSampledDailyDetailedFTEs fte on f.DepartmentID = fte.DepartmentID AND f.JobCodeID = fte.JobCodeID AND f.PayCodeID = fte.PayCodeID AND f.PayCodeGroupID = fte.PayCodeGroupID AND f.EmployeeID = fte.EmployeeID AND f.PayPeriodID = fte.PayPeriodID AND f.DateID = fte.DateID AND f.TimeClassID = fte.TimeClassID
			where jc.IsPR = 1 and jc.IsDaily = 1
			group by 
				f.DepartmentID,
				f.JobCodeID,
				f.PayCodeID,
				f.PayCodeGroupID,
				f.EmployeeID,
				f.PayPeriodID,
				f.DateID,
				f.TimeClassID) X'
		-- Split data into batches
		IF OBJECT_ID('tempdb..#inputPayPeriods') IS NOT NULL DROP TABLE #inputPayPeriods
		
		CREATE TABLE #inputPayPeriods (PayPeriodID INT, RecordsCount INT, BatchID INT)
		INSERT INTO #inputPayPeriods
		EXEC dbo.procGetInputDataByBatches
	  		@batchSize = @batchSize,
			@columnName = 'PayPeriodID',
			@tableAlias = 'X',
			@fromClause = @fromClause,
			@whereClause = '',
			@isDebug = 0

		SELECT @MaxBatchID = MAX(BatchID) FROM #inputPayPeriods

		-- Loop thru batches and insert data
		SET @BatchID = 1
		WHILE @BatchID <= @MaxBatchID
		BEGIN  
			INSERT INTO [fw].[FactPayrollSampledDailyDetailed] With (TABLOCKX) (
				DepartmentID,
				JobCodeID,
				PayCodeID,
				PayCodeGroupID,
				EmployeeID,
				PayPeriodID,
				DateID,
				TimeClassID,
				Hours,
				Dollars,
				FTEs,
				IsDeleted
			)
			select
				f.DepartmentID,		
				f.JobCodeID,
				f.PayCodeID,
				f.PayCodeGroupID,
				f.EmployeeID,
				f.PayPeriodID,
				f.DateID,
				f.TimeClassID,
				SUM(f.Hours) as Hours,
				SUM(f.Dollars) as Dollars,
				SUM(isnull(fte.FTEs,0)) as FTEs,
				0 as isDeleted
			from
			#PayrollSampledDailyDetailedStaging f
			INNER JOIN #inputPayPeriods IPP ON IPP.PayPeriodID = f.PayPeriodID and IPP.BatchID = @BatchID 
			inner join fw.DimJobCode jc on f.JobCodeID = jc.JobCodeID
			left join #PayrollSampledDailyDetailedFTEs fte on f.DepartmentID = fte.DepartmentID AND f.JobCodeID = fte.JobCodeID AND	f.PayCodeID = fte.PayCodeID AND f.PayCodeGroupID = fte.PayCodeGroupID AND f.EmployeeID = fte.EmployeeID AND f.PayPeriodID = fte.PayPeriodID AND f.DateID = fte.DateID AND f.TimeClassID = fte.TimeClassID
			where jc.IsPR = 1 and jc.IsDaily = 1
			group by 
				f.DepartmentID,		
				f.JobCodeID,
				f.PayCodeID,
				f.PayCodeGroupID,
				f.EmployeeID,
				f.PayPeriodID,
				f.DateID,
				f.TimeClassID      
			SET @BatchID = @BatchID + 1
		END

		CREATE NONCLUSTERED INDEX [IDX_FactPayrollSampledDailyDetailed] ON [fw].[FactPayrollSampledDailyDetailed]
		(
			[DepartmentID] ASC,
			[JobCodeID] ASC,
			[PayCodeID] ASC,
			[PayCodeGroupID] ASC,
			[EmployeeID] ASC,
			[DateID] ASC,
			[TimeClassID] ASC
		)
		WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]

		CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactPayrollSampledDailyDetailed]
		(
			[IsDeleted] ASC
		)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
	END
	ELSE -- IF @isFeatureFlagOn = 0
	BEGIN
	set @IterationFiscalYearID = (select min(dd.FiscalYear) from #PayrollSampledDailyDetailedStaging f
															 inner join fw.DimDate dd on dd.DateID = f.DateID)
	WHILE @IterationFiscalYearID <= (select max(dd.FiscalYear) from #PayrollSampledDailyDetailedStaging f
															 inner join fw.DimDate dd on dd.DateID = f.DateID )
	BEGIN
	INSERT INTO [fw].[FactPayrollSampledDailyDetailed] With (TABLOCKX) (
			DepartmentID,
			JobCodeID,
			PayCodeID,
			PayCodeGroupID,
			EmployeeID,
			PayPeriodID,
			DateID,
			TimeClassID,
			Hours,
			Dollars,
			FTEs,
			IsDeleted
		)
	select
		f.DepartmentID,		
		f.JobCodeID,
		f.PayCodeID,
		f.PayCodeGroupID,
		f.EmployeeID,
		f.PayPeriodID,
		f.DateID,
		f.TimeClassID,
		SUM(f.Hours) as Hours,
		SUM(f.Dollars) as Dollars,
		SUM(f.FTEs) as FTEs,
		0 as isDeleted
	from
	#PayrollSampledDailyDetailedStaging f
	inner join fw.DimDate dd on dd.DateID = f.DateID
    inner join fw.DimJobCode jc on f.JobCodeID = jc.JobCodeID
	where dd.FiscalYear = @IterationFiscalYearID and jc.IsPR = 1 and jc.IsDaily = 1
	group by 
		f.DepartmentID,		
		f.JobCodeID,
		f.PayCodeID,
		f.PayCodeGroupID,
		f.EmployeeID,
		f.PayPeriodID,
		f.DateID,
		f.TimeClassID      
	set @iterationFiscalYearId = @iterationFiscalYearId + 1
	END
	END
	
	CREATE UNIQUE CLUSTERED INDEX CU_viewFactPayrollSampledDailyDetailedHours
	ON fw.viewFactPayrollSampledDailyDetailedHours (PayPeriodID, DepartmentID, EmployeeID, TimeClassID, RowID)
	WITH (DATA_COMPRESSION = PAGE)

	END
ELSE 
	BEGIN
		;WITH TGT AS (SELECT t.* FROM 
		[fw].[FactPayrollSampledDailyDetailed] t With (TABLOCKX)
		inner join #DailyCalcPeriodsScope dcps on dcps.PayPeriodID = t.PayPeriodID
		--where (@fiscalYearID = 0 or pd.FiscalYear = @fiscalYearID)  -- #DailyCalcPeriodsScope already contains all Pay Periods that should be recalculated, so filtering by year could bring destructive effect in case @fisclaYearID <> 'calendar year' (conflict @FiscalYearID and @isCalcDaily)
		) 
		MERGE 
		TGT AS target
		USING (
			select DepartmentID,f.JobCodeID,PayCodeID,PayCodeGroupID,EmployeeID,PayPeriodID,DateID,TimeClassID,
					SUM(Hours) as Hours,
					SUM(Dollars) as Dollars,
					SUM(FTEs) as FTEs
			from
				#PayrollSampledDailyDetailedStaging f
				inner join fw.DimJobCode jc on f.JobCodeID = jc.JobCodeID
				where jc.isPR = 1 and jc.IsDaily = 1
			group by DepartmentID,f.JobCodeID,PayCodeID,PayCodeGroupID,EmployeeID,PayPeriodID,DateID,TimeClassID
		) AS source
			ON 
			SOURCE.DepartmentID=TARGET.DepartmentID
			AND SOURCE.JobCodeID=TARGET.JobCodeID
			AND SOURCE.PayCodeID = TARGET.PayCodeID
			AND SOURCE.PayCodeGroupID=TARGET.PayCodeGroupID
			AND SOURCE.EmployeeID=TARGET.EmployeeID
			AND SOURCE.PayPeriodID=TARGET.PayPeriodID
			AND SOURCE.TimeClassID=TARGET.TimeClassID
			AND SOURCE.DateID=TARGET.DateID
		WHEN MATCHED AND 
			(target.Hours <> source.Hours
			or target.Dollars <> source.Dollars
			or target.FTEs <> source.FTEs
			)
			THEN
				UPDATE
				SET target.Hours = source.Hours,
					target.Dollars = source.Dollars,
					target.FTEs	= source.FTEs
		WHEN NOT MATCHED BY TARGET
			THEN
		INSERT (
			DepartmentID,
			JobCodeID,
			PayCodeID,
			PayCodeGroupID,
			EmployeeID,
			PayPeriodID,
			DateID,
			TimeClassID,
			Hours,
			Dollars,
			FTEs,
			IsDeleted
		)
		VALUES (
		
		DepartmentID,		
		JobCodeID,
		PayCodeID,
		PayCodeGroupID,
		EmployeeID,
		PayPeriodID,
		DateID,
		TimeClassID,
		Hours,
		Dollars,
		FTEs,
		0)
		WHEN NOT MATCHED BY SOURCE
		THEN
				DELETE;
	END
	
	 IF @isCalcDaily = 1 
     begin 
	      delete from [fw].[FactPayrollSampledDailyDetailed] where dateID > (select MIN(dateID) from fw.dimDate where CalendarDateTime >= @yesterday_date )and TimeClassID = 1
	 end
	 delete from [fw].[FactPayrollSampledDailyDetailed] where Hours = 0 and Dollars = 0 and TimeClassID = 1
	   
	IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments
	IF OBJECT_ID('tempdb..#PayrollSampledDailyDetailedStaging') IS NOT NULL  DROP TABLE #PayrollSampledDailyDetailedStaging
	IF OBJECT_ID('tempdb..#departmentsBudgetAllocations') IS NOT NULL DROP TABLE #departmentsBudgetAllocations
	IF OBJECT_ID('tempdb..#DailyCalcPeriodsScope') IS NOT NULL DROP TABLE #DailyCalcPeriodsScope
	IF OBJECT_ID('tempdb..#StaffingDaily') IS NOT NULL  DROP TABLE #StaffingDaily
	IF OBJECT_ID('tempdb..#PayrollSampledDailyDetailedFTEs') IS NOT NULL  DROP TABLE #PayrollSampledDailyDetailedFTEs
	
	
	-- UPDATE STATISTICS 
	UPDATE STATISTICS fw.FactPayrollSampledDailyDetailed;
GO


---------------------------------------------

-- fw.procPayrollSampledDailyInsert
/***************************************************************
** CID		Date		Author		WI			Description
** 1		2016-12-17	mholov		B-13509		Pull Budgeted amounts from monthly table
** 2		2017-01-11	akozlov		D-05410		Minor fix
** 3		2017-01-31	akozlov		B-13926		Added department filter
** 4		2017-02-08  gforeman	B-14308		Added year filter
** 5		2017-02-20  gforeman	D-05613		Prevent zero rows
** 6		2017-03-06  gforeman	B-14693		Cancel sampling if daily disabled
** 7		2017-05-16	ipetriv		D-05915		Added statistics recalculating to FactPayrollSampledDailyDetailed
** 8		2017-05-29 	ipetriv		B-15994		Refactored sampling process and implemented using of staging tables
** 9		2017-06-15	IP			B-15086 	Modify SP to use unique temp table
** 10		2017-06-20	IP			B-15086 	fixing issues: FTEs = 0 after recalculation for one year / duplicates appers for one year recalculation
** 11		2018-09-12	ipetriv		B-16737		Allow job codes in PR to use 70-hour work weeks - Sampling Updates
** 12		2018-09-11	kzhuk		D-07649		PR Daily custom action calls procedures for wrong year
** 13       2019-04-24  OV          B-22924     Allow 0 data (except actual) in procPayrollSampledDailyInsert (B-20571)
** 14       2019-05-14  OV          B-22955     Filtered by new 'isDaily' column from DimjobCode
** 15     2019-07-23    OV          D-08628     Sampled data for first PayPeriod from previous year
** 16		2019-10-31	KF			D-08926		PR Payroll Daily sampling: process fails due to full DB Transaction log
** 17		2019-11-25	IH			TK-80619	Rollback transaction log changes
** 18		2020-01-08	HV			B-25788  	procPayrollSampledDailyInsert DBA Enhancements
** 19		2020-01-14	HV			D-09150  	Inflated 'Target FTE Daily' values caused by duplicates in FactPayrollSampledDaily
** 20		2021-12-21	HV			JAZZ-31105  	procPayrollSampledDailyInsert Filling Up DB For All Years Run (Rolling Average Target Basis)
** 21		2022-10-28	ishah		JAZZ-45100  	Reuse split by batches functionality in existing procedure
** 22		2024-06-14  SM      	JAZZ-71536  change JobCodeID from smallint to int
**************************************************************/
CREATE PROCEDURE [fw].[procPayrollSampledDailyInsert] 
    @departmentIDs NVARCHAR(max) = NULL,
	@fiscalYearID INT = 0,
	@isCalcDaily bit = 0,
	@isFeatureFlagOn bit = 0
	WITH RECOMPILE
AS

 IF OBJECT_ID('tempdb..#departments') IS NOT NULL DROP TABLE #departments
SELECT val  INTO #departments
FROM ConvertCSValuesToTable(@departmentIDs, ',')

SELECT DepartmentID,
	JobCodeID,
	WorkingHoursCoef = cast(dww.Hours AS NUMERIC(20, 6)) / 7
INTO #WorkWeekHours
FROM (
	SELECT DepartmentID,
		JobCodeID,
		WorkWeekID = COALESCE(jc.WorkWeekID, de.WorkWeekID, - 1)
	FROM (
		SELECT dp.DepartmentID,
			WorkWeekID = CASE 
				WHEN e.WorkWeekID > - 1
					THEN e.WorkWeekID
				ELSE NULL
				END
		FROM fw.DimEntity e
		INNER JOIN fw.DimDepartment dp on e.EntityID = dp.EntityID
		) DE
	CROSS JOIN (
		SELECT djc.JobCodeID,
			djcg.JobCodeGroupID,
			WorkWeekID = CASE 
				WHEN djc.WorkWeekOverrideID > - 1
					THEN djc.WorkWeekOverrideID
				WHEN djc.WorkWeekOverrideID = - 1
					AND djcg.WorkWeekOverrideID > - 1
					THEN djcg.WorkWeekOverrideID
				ELSE NULL
				END
		FROM fw.DimJobCode djc
		INNER JOIN fw.DimJobCodeGroup djcg
			ON djc.JobCodeGroupID = djcg.JobCodeGroupID
		WHERE djc.IsDaily = 1 and djc.IsPR = 1
		) JC
	) DeptJobCode
LEFT JOIN fw.DimWorkWeek dww
	ON DeptJobCode.WorkWeekID = dww.WorkWeekID

IF OBJECT_ID('tempdb..#dates') IS NOT NULL DROP TABLE #dates		
SELECT DISTINCT DateID INTO #dates
FROM fw.DimDate dt
INNER JOIN fw.DimPayPeriod pp on dt.CalendarDateTime BETWEEN pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate
	where 
		(@isCalcDaily = 1 and DATEADD(DAY,-1,CAST(GETDATE() as DATE)) BETWEEN pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate)  -- if @isCalcDaily = 1 is present we ignore what @yearOfSampling is passed to stored procedure (based on B-18793)
			or 
		(@isCalcDaily = 0 and (@fiscalYearID = pp.FiscalYearIDSecond or @fiscalYearID = 0))

--cancel if not using daily
IF (
		NOT EXISTS (
			SELECT 1
			FROM pi.SystemSetting
			WHERE NAME = 'PR Daily Enabled'
				AND Value = '1'
			)
		)
BEGIN
	RETURN
END

/*If target basis is rolling average then we can't calculate baseline as simple sum of detailed table.
 in his case we should
	1)insert summed values for all timeclasses except baseline (TimeClassId  = 20)
	2)recalculate baseline (including FTE for baseline records)
*/
IF (
		SELECT Value
		FROM pi.SystemSetting
		WHERE NAME = 'Target Basis'
		) = 10 -- rolling average
BEGIN
	IF @fiscalYearID = 0 AND @isCalcDaily = 0
		AND @departmentIDs IS NULL
	BEGIN
		TRUNCATE TABLE [fw].[FactPayrollSampledDaily]
		IF @isFeatureFlagOn = 0
		BEGIN
			/*recalculate baseline for just inserted values*/
			;

		WITH groupedBaselineTargetPayroll
		AS (
			SELECT FACT.DepartmentID,
				FACT.JobCodeID,
				FACT.PayCodeGroupID,
				FACT.PayPeriodID,
				DT.DateID,
				FACT.TimeClassID,
				SUM(FACT.Hours) AS Hours,
				SUM(FACT.Dollars) AS Dollars
			FROM fw.FactPayrollSampledPayPeriod FACT
			INNER JOIN [fw].[DimPayPeriod] PP
				ON PP.PayPeriodID = FACT.PayPeriodID
			INNER JOIN [fw].[DimDate] DT
				ON DT.CalendarDateTime BETWEEN PP.PeriodStartCalendarDate AND PP.PeriodEndCalendarDate
			INNER JOIN [fw].[DimDepartment] D
				ON D.DepartmentID = FACT.DepartmentID
			WHERE FACT.PayPeriodID != 0
				AND FACT.IsDeleted = 0
				AND D.IsPR = 1
				AND FACT.TimeClassID = 20
				AND FACT.DepartmentID != 0
			GROUP BY FACT.DepartmentID,
				FACT.JobCodeID,
				FACT.PayCodeGroupID,
				FACT.PayPeriodID,
				DT.DateID,
				FACT.TimeClassID
			)
		INSERT INTO fw.FactPayrollSampledDaily (
			DepartmentID,
			JobCodeID,
			PayCodeGroupID,
			PayPeriodID,
			DateID,
			TimeClassID,
			Hours,
			Dollars,
			FTEs
			)
		SELECT fact.DepartmentID,
			fact.JobCodeID,
			fact.PayCodeGroupID,
			fact.PayPeriodID,
			fact.DateID,
			fact.TimeClassID,
			SUM(fact.Hours),
			SUM(fact.Dollars),
			FTEs = SUM(isnull(CASE WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0	and ww.WorkingHoursCoef is null     THEN fact.Hours / (WorkingDays * 8.0 / PeriodDays)
								   WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0	and ww.WorkingHoursCoef is not null THEN (fact.Hours) / WorkingHoursCoef
						END, 0))
		FROM (
			SELECT DepartmentID,
				JobCodeID,
				PayCodeGroupID,
				G.PayPeriodID,
				DateID,
				TimeClassID,
				Hours / PP.PeriodDays AS Hours,
				Dollars / PP.PeriodDays AS Dollars
			FROM groupedBaselineTargetPayroll G
			INNER JOIN fw.DimPayPeriod PP
				ON PP.PayPeriodID = G.PayPeriodID
			) fact
		INNER JOIN fw.DimPayPeriod pp
			ON pp.PayPeriodID = fact.PayPeriodID
		INNER JOIN [fw].[viewDimPayCodeGroup] pcg
			ON fact.PayCodeGroupID = pcg.PayCodeGroupID
		INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID and fact.JobCodeID = ww.JobCodeID
		GROUP BY fact.DepartmentID,
			fact.JobCodeID,
			fact.PayCodeGroupID,
			fact.PayPeriodID,
			fact.DateID,
			fact.TimeClassID
		UNION ALL
		SELECT fact.DepartmentID,
			fact.JobCodeID,
			fact.PayCodeGroupID,
			fact.PayPeriodID,
			fact.DateID,
			fact.TimeClassID,
			fact.Hours,
			fact.Dollars,
			FTEs = isnull(CASE WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0	and ww.WorkingHoursCoef is null     THEN fact.Hours / (WorkingDays * 8.0 / PeriodDays)
								   WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0	and ww.WorkingHoursCoef is not null THEN (fact.Hours) / WorkingHoursCoef
						END, 0)
		FROM (
			SELECT fact.[DepartmentID],
				fact.[JobCodeID],
				fact.[PayCodeGroupID],
				fact.[PayPeriodID],
				fact.[DateID],
				fact.[TimeClassID],
				sum(fact.[Dollars]) AS Dollars,
				sum(fact.[Hours]) AS Hours
			FROM [fw].[FactPayrollSampledDailyDetailed] fact
			INNER JOIN fw.DimDate dt
				ON dt.DateID = fact.DateID
			WHERE TimeClassID <> 20 -- all timeclasses except baseline (TimeClassId  = 20)
			GROUP BY fact.[DepartmentID],
				fact.[JobCodeID],
				fact.[PayCodeGroupID],
				fact.[PayPeriodID],
				fact.[DateID],
				fact.[TimeClassID]
			) FACT
		INNER JOIN fw.DimPayPeriod pp
			ON pp.PayPeriodID = fact.PayPeriodID
		INNER JOIN [fw].[viewDimPayCodeGroup] pcg
			ON fact.PayCodeGroupID = pcg.PayCodeGroupID
		INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID and fact.JobCodeID = ww.JobCodeID
		END
		ELSE --IF @isFeatureFlagOn = 1
		BEGIN
			IF OBJECT_ID('tempdb..#groupedBaselineTargetPayroll') IS NOT NULL DROP TABLE #groupedBaselineTargetPayroll
 			CREATE TABLE #groupedBaselineTargetPayroll (DepartmentID int, JobCodeID int, PayCodeGroupID int, PayPeriodID int, DateID int, TimeClassID int, Hours  decimal(19,4), Dollars  decimal(19,4))
			
			INSERT INTO #groupedBaselineTargetPayroll(
				DepartmentID,
				JobCodeID,
				PayCodeGroupID,
				PayPeriodID,
				DateID,
				TimeClassID,
				Hours,
				Dollars)
			SELECT FACT.DepartmentID,
				FACT.JobCodeID,
				FACT.PayCodeGroupID,
				FACT.PayPeriodID,
				DT.DateID,
				FACT.TimeClassID,
				SUM(FACT.Hours) AS Hours,
				SUM(FACT.Dollars) AS Dollars
			FROM fw.FactPayrollSampledPayPeriod FACT
			INNER JOIN [fw].[DimPayPeriod] PP
				ON PP.PayPeriodID = FACT.PayPeriodID
			INNER JOIN [fw].[DimDate] DT
				ON DT.CalendarDateTime BETWEEN PP.PeriodStartCalendarDate AND PP.PeriodEndCalendarDate
			INNER JOIN [fw].[DimDepartment] D
				ON D.DepartmentID = FACT.DepartmentID
			WHERE FACT.PayPeriodID != 0
				AND FACT.IsDeleted = 0
				AND D.IsPR = 1
				AND FACT.TimeClassID = 20
				AND FACT.DepartmentID != 0
			GROUP BY FACT.DepartmentID,
				FACT.JobCodeID,
				FACT.PayCodeGroupID,
				FACT.PayPeriodID,
				DT.DateID,
				FACT.TimeClassID

			DECLARE @BatchSize INT = 30000000
			print 'By Batch'+convert(varchar(20),GETDATE(),113)

			-- Split data into batches
			IF OBJECT_ID('tempdb..#inputPayPeriods') IS NOT NULL DROP TABLE #inputPayPeriods
			
			CREATE TABLE #inputPayPeriods (PayPeriodID INT, RecordsCount INT, BatchID INT)
			INSERT INTO #inputPayPeriods
			EXEC dbo.procGetInputDataByBatches
	  			@batchSize = @BatchSize,
				@columnName = 'PayPeriodID',
				@tableAlias = 'gp',
				@fromClause = '#groupedBaselineTargetPayroll gp',
				@whereClause = '',
				@isDebug = 0

			DECLARE @BatchID INT, @MaxBatchID INT
			SELECT @MaxBatchID = MAX(BatchID) FROM #inputPayPeriods
						
			-- Drop Indexes
			EXEC dbo.procSysDropIndex @schema = 'fw', @table = 'FactPayrollSampledDaily', @indexName = 'IDX_FactPayrollSampledDaily'
			EXEC dbo.procSysDropIndex @schema = 'fw', @table = 'FactPayrollSampledDaily', @indexName = 'NCNU_IsDeleted'		    

			-- Loop thru batches and insert data
			SET @BatchID = 1
			WHILE @BatchID <= @MaxBatchID
			BEGIN  	
			INSERT INTO fw.FactPayrollSampledDaily (
				DepartmentID,
				JobCodeID,
				PayCodeGroupID,
				PayPeriodID,
				DateID,
				TimeClassID,
				Hours,
				Dollars,
				FTEs
				)
			SELECT fact.DepartmentID,
				fact.JobCodeID,
				fact.PayCodeGroupID,
				fact.PayPeriodID,
				fact.DateID,
				fact.TimeClassID,
				SUM(fact.Hours),
				SUM(fact.Dollars),
				FTEs = SUM(isnull(CASE WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0	and ww.WorkingHoursCoef is null     THEN fact.Hours / (WorkingDays * 8.0 / PeriodDays)
									   WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0	and ww.WorkingHoursCoef is not null THEN (fact.Hours) / WorkingHoursCoef
							END, 0))
			FROM (
				SELECT DepartmentID,
					JobCodeID,
					PayCodeGroupID,
					G.PayPeriodID,
					DateID,
					TimeClassID,
					Hours / PP.PeriodDays AS Hours,
					Dollars / PP.PeriodDays AS Dollars
				FROM #groupedBaselineTargetPayroll G
				INNER JOIN #inputPayPeriods IPP ON IPP.PayPeriodID = G.PayPeriodID and IPP.BatchID = @BatchID
				INNER JOIN fw.DimPayPeriod PP
					ON PP.PayPeriodID = G.PayPeriodID
				) fact
			INNER JOIN fw.DimPayPeriod pp
				ON pp.PayPeriodID = fact.PayPeriodID
			INNER JOIN [fw].[viewDimPayCodeGroup] pcg
				ON fact.PayCodeGroupID = pcg.PayCodeGroupID
			INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID and fact.JobCodeID = ww.JobCodeID
			GROUP BY fact.DepartmentID,
				fact.JobCodeID,
				fact.PayCodeGroupID,
				fact.PayPeriodID,
				fact.DateID,
				fact.TimeClassID
			SET @BatchID = @BatchID + 1
			END

			INSERT INTO fw.FactPayrollSampledDaily (
				DepartmentID,
				JobCodeID,
				PayCodeGroupID,
				PayPeriodID,
				DateID,
				TimeClassID,
				Hours,
				Dollars,
				FTEs
				)
			SELECT fact.DepartmentID,
				fact.JobCodeID,
				fact.PayCodeGroupID,
				fact.PayPeriodID,
				fact.DateID,
				fact.TimeClassID,
				fact.Hours,
				fact.Dollars,
				FTEs = isnull(CASE WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0	and ww.WorkingHoursCoef is null     THEN fact.Hours / (WorkingDays * 8.0 / PeriodDays)
									   WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0	and ww.WorkingHoursCoef is not null THEN (fact.Hours) / WorkingHoursCoef
							END, 0)
			FROM (
				SELECT fact.[DepartmentID],
					fact.[JobCodeID],
					fact.[PayCodeGroupID],
					fact.[PayPeriodID],
					fact.[DateID],
					fact.[TimeClassID],
					sum(fact.[Dollars]) AS Dollars,
					sum(fact.[Hours]) AS Hours
				FROM [fw].[FactPayrollSampledDailyDetailed] fact
				INNER JOIN fw.DimDate dt
					ON dt.DateID = fact.DateID
				WHERE TimeClassID <> 20 -- all timeclasses except baseline (TimeClassId  = 20)
				GROUP BY fact.[DepartmentID],
					fact.[JobCodeID],
					fact.[PayCodeGroupID],
					fact.[PayPeriodID],
					fact.[DateID],
					fact.[TimeClassID]
				) FACT
			INNER JOIN fw.DimPayPeriod pp
				ON pp.PayPeriodID = fact.PayPeriodID
			INNER JOIN [fw].[viewDimPayCodeGroup] pcg
				ON fact.PayCodeGroupID = pcg.PayCodeGroupID
			INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID and fact.JobCodeID = ww.JobCodeID


            CREATE NONCLUSTERED INDEX [IDX_FactPayrollSampledDaily] ON [fw].[FactPayrollSampledDaily]
            (
                [DepartmentID] ASC,
                [JobCodeID] ASC,
                [PayCodeGroupID] ASC,
                [PayPeriodID] ASC,
                [DateID] ASC,
                [TimeClassID] ASC
            )
            INCLUDE ([Dollars],	[FTEs],	[Hours])
			WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 100) ON [PRIMARY]

            CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactPayrollSampledDaily]
            (
			    [IsDeleted] ASC
			)
			WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 100) ON [PRIMARY]

			IF OBJECT_ID('tempdb..#groupedBaselineTargetPayroll') IS NOT NULL DROP TABLE #groupedBaselineTargetPayroll
		END
	END
	ELSE
	BEGIN
		WITH TGT
		AS (
			SELECT t.*
			FROM [fw].[FactPayrollSampledDaily] t WITH (TABLOCKX)
			INNER JOIN #dates pp on t.DateID = pp.DateID 
			WHERE (
					@departmentIDs IS NULL
					OR t.DepartmentID IN (
						SELECT val 
						FROM #departments
						)
					)
			),

		groupedBaselineTargetPayrollFilteredByDates
		AS (
			SELECT FACT.DepartmentID,
				FACT.JobCodeID,
				FACT.PayCodeGroupID,
				FACT.PayPeriodID,
				DT.DateID,
				FACT.TimeClassID,
				SUM(FACT.Hours) AS Hours,
				SUM(FACT.Dollars) AS Dollars
			FROM fw.FactPayrollSampledPayPeriod FACT
			INNER JOIN [fw].[DimPayPeriod] PP
				ON PP.PayPeriodID = FACT.PayPeriodID
			INNER JOIN fw.DimDate DT
				ON DT.CalendarDateTime BETWEEN PP.PeriodStartCalendarDate AND PP.PeriodEndCalendarDate
			INNER JOIN #dates FD
				ON FD.DateID = DT.DateID
			INNER JOIN [fw].[DimDepartment] D
				ON D.DepartmentID = FACT.DepartmentID
			WHERE FACT.PayPeriodID != 0
				AND FACT.IsDeleted = 0
				AND D.IsPR = 1
				AND FACT.TimeClassID = 20
				AND FACT.DepartmentID != 0
				AND (
					@departmentIDs IS NULL
					OR FACT.DepartmentID IN (
						SELECT val
						FROM #departments
						)
					)
			GROUP BY FACT.DepartmentID,
				FACT.JobCodeID,
				FACT.PayCodeGroupID,
				FACT.PayPeriodID,
				DT.DateID,
				FACT.TimeClassID
			)
		MERGE TGT AS target
		USING (
			SELECT fact.DepartmentID,
				fact.JobCodeID,
				fact.PayCodeGroupID,
				fact.PayPeriodID,
				fact.DateID,
				fact.TimeClassID,
				fact.Hours,
				fact.Dollars,
				FTEs = isnull(CASE WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0	and ww.WorkingHoursCoef is null     THEN fact.Hours / (WorkingDays * 8.0 / PeriodDays)
									   WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0	and ww.WorkingHoursCoef is not null THEN (fact.Hours) / WorkingHoursCoef
						END, 0)

			FROM (
				SELECT fact.[DepartmentID],
					fact.[JobCodeID],
					fact.[PayCodeGroupID],
					fact.[PayPeriodID],
					fact.[DateID],
					fact.[TimeClassID],
					sum(fact.[Dollars]) AS Dollars,
					sum(fact.[Hours]) AS Hours
				FROM [fw].[FactPayrollSampledDailyDetailed] fact
				INNER JOIN #dates dt
					ON dt.DateID = fact.DateID
				WHERE (
						@departmentIDs IS NULL
						OR DepartmentID IN (
							SELECT val
							FROM #departments
							)
						)
					
					AND TimeClassID <> 20 -- all timeclasses except baseline (TimeClassId  = 20)
				GROUP BY fact.[DepartmentID],
					fact.[JobCodeID],
					fact.[PayCodeGroupID],
					fact.[PayPeriodID],
					fact.[DateID],
					fact.[TimeClassID]
				) FACT
			INNER JOIN fw.DimPayPeriod pp
				ON pp.PayPeriodID = fact.PayPeriodID
			INNER JOIN [fw].[viewDimPayCodeGroup] pcg
				ON fact.PayCodeGroupID = pcg.PayCodeGroupID
			INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID and fact.JobCodeID = ww.JobCodeID

			UNION ALL
			
			SELECT fact.DepartmentID,
				fact.JobCodeID,
				fact.PayCodeGroupID,
				fact.PayPeriodID,
				fact.DateID,
				fact.TimeClassID,
				SUM(fact.Hours),
				SUM(fact.Dollars),
				FTEs = SUM(isnull(CASE WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0	and ww.WorkingHoursCoef is null     THEN fact.Hours / (WorkingDays * 8.0 / PeriodDays)
									   WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0	and ww.WorkingHoursCoef is not null THEN (fact.Hours) / WorkingHoursCoef
						END, 0))

			FROM (
				SELECT DepartmentID,
					JobCodeID,
					PayCodeGroupID,
					G.PayPeriodID,
					DateID,
					TimeClassID,
					Hours / PP.PeriodDays AS Hours,
					Dollars / PP.PeriodDays AS Dollars
				FROM groupedBaselineTargetPayrollFilteredByDates G
				INNER JOIN fw.DimPayPeriod PP
					ON PP.PayPeriodID = G.PayPeriodID
				) fact
			INNER JOIN fw.DimPayPeriod pp
				ON pp.PayPeriodID = fact.PayPeriodID
			INNER JOIN [fw].[viewDimPayCodeGroup] pcg
				ON fact.PayCodeGroupID = pcg.PayCodeGroupID
			INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID and fact.JobCodeID = ww.JobCodeID
			GROUP BY fact.DepartmentID,
				fact.JobCodeID,
				fact.PayCodeGroupID,
				fact.PayPeriodID,
				fact.DateID,
				fact.TimeClassID
			) AS source
			ON SOURCE.DepartmentID = TARGET.DepartmentID
				AND SOURCE.JobCodeID = TARGET.JobCodeID
				--AND SOURCE.PayCodeID = TARGET.PayCodeID
				AND SOURCE.PayCodeGroupID = TARGET.PayCodeGroupID
				--AND SOURCE.EmployeeID = TARGET.EmployeeID
				AND SOURCE.PayPeriodID = TARGET.PayPeriodID
				AND SOURCE.TimeClassID = TARGET.TimeClassID
				AND SOURCE.DateID = TARGET.DateID
		WHEN MATCHED
				AND (
				target.Hours <> source.Hours
				OR target.Dollars <> source.Dollars
				OR target.FTEs <> source.FTEs
				)
			THEN
				UPDATE
				SET target.Hours = source.Hours,
					target.Dollars = source.Dollars,
					target.FTEs = source.FTEs
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					DepartmentID,
					JobCodeID,
				--	PayCodeID,
					PayCodeGroupID,
				--	EmployeeID,
					PayPeriodID,
					DateID,
					TimeClassID,
					Hours,
					Dollars,
					FTEs,
					IsDeleted
					)
				VALUES (
					DepartmentID,
					JobCodeID,
					--PayCodeID,
					PayCodeGroupID,
					--EmployeeID,
					PayPeriodID,
					DateID,
					TimeClassID,
					Hours,
					Dollars,
					FTEs,
					0
					)
		WHEN NOT MATCHED BY SOURCE
			THEN
				DELETE;
	
	END
END
  ELSE /*Here is  inserting aggregated rows in case when "Target Basis" is not rolling average*/
BEGIN
IF @fiscalYearID = 0 AND @departmentIDs IS NULL AND @isCalcDaily = 0
BEGIN 
TRUNCATE TABLE [fw].[FactPayrollSampledDaily]
INSERT INTO [fw].[FactPayrollSampledDaily] (
	[DepartmentID],
	[JobCodeID],
	[PayPeriodID],
	[TimeClassID],
	[DateID],
	[PayCodeGroupID],
	[Hours],
	[Dollars],
	[FTEs]
	)
SELECT fact.[DepartmentID],
	fact.[JobCodeID],
	fact.[PayPeriodID],
	fact.[TimeClassID],
	fact.[DateID],
	fact.[PayCodeGroupID],
	fact.Hours,
	fact.Dollars,
	FTEs = isnull(CASE WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0	and ww.WorkingHoursCoef is null     THEN fact.Hours / (WorkingDays * 8.0 / PeriodDays)
						   WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0	and ww.WorkingHoursCoef is not null THEN (fact.Hours) / WorkingHoursCoef
					END, 0)

FROM (
	SELECT fact.[DepartmentID],
		fact.[JobCodeID],
		fact.[PayCodeGroupID],
		fact.[PayPeriodID],
		fact.[DateID],
		fact.[TimeClassID],
		sum(fact.[Dollars]) AS Dollars,
		sum(fact.[Hours]) AS Hours
	FROM [fw].[FactPayrollSampledDailyDetailed] fact
	WHERE (
			@departmentIDs IS NULL
			OR DepartmentID IN (
				SELECT val
				FROM #departments
				)
			)

	GROUP BY fact.[DepartmentID],
		fact.[JobCodeID],
		fact.[PayCodeGroupID],
		fact.[PayPeriodID],
		fact.[DateID],
		fact.[TimeClassID]
	) FACT
INNER JOIN fw.DimPayPeriod pp
	ON pp.PayPeriodID = fact.PayPeriodID
INNER JOIN [fw].[viewDimPayCodeGroup] pcg
	ON fact.PayCodeGroupID = pcg.PayCodeGroupID
INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID and fact.JobCodeID = ww.JobCodeID

END
ELSE 
WITH TGT
		AS (
			SELECT t.*
			FROM [fw].[FactPayrollSampledDaily] t WITH (TABLOCKX)
			INNER JOIN #dates pp
				ON t.DateId = pp.DateID
			WHERE (
					@departmentIDs IS NULL
					OR t.DepartmentID IN (
						SELECT val
						FROM #departments
						)
					)
			)
		MERGE TGT AS target
		USING (
			SELECT fact.[DepartmentID],
	fact.[JobCodeID],
	fact.[PayPeriodID],
	fact.[TimeClassID],
	fact.[DateID],
	fact.[PayCodeGroupID],
	fact.Hours,
	fact.Dollars,
	FTEs = isnull(CASE WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0	and ww.WorkingHoursCoef is null     THEN fact.Hours / (WorkingDays * 8.0 / PeriodDays)
								   WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0	and ww.WorkingHoursCoef is not null THEN (fact.Hours) / WorkingHoursCoef
			END, 0)

FROM (
	SELECT fact.[DepartmentID],
		fact.[JobCodeID],
		fact.[PayCodeGroupID],
		fact.[PayPeriodID],
		fact.[DateID],
		fact.[TimeClassID],
		sum(fact.[Dollars]) AS Dollars,
		sum(fact.[Hours]) AS Hours
	FROM [fw].[FactPayrollSampledDailyDetailed] fact
	INNER JOIN #dates dt
		ON dt.DateID = fact.DateID
	WHERE (
			@departmentIDs IS NULL
			OR DepartmentID IN (
				SELECT val
				FROM #departments
				)
			)

	GROUP BY fact.[DepartmentID],
		fact.[JobCodeID],
		fact.[PayCodeGroupID],
		fact.[PayPeriodID],
		fact.[DateID],
		fact.[TimeClassID]
	) FACT
INNER JOIN fw.DimPayPeriod pp
	ON pp.PayPeriodID = fact.PayPeriodID
INNER JOIN [fw].[viewDimPayCodeGroup] pcg
	ON fact.PayCodeGroupID = pcg.PayCodeGroupID
INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID and fact.JobCodeID = ww.JobCodeID
			) AS source
			ON SOURCE.DepartmentID = TARGET.DepartmentID
				AND SOURCE.JobCodeID = TARGET.JobCodeID
				--AND SOURCE.PayCodeID = TARGET.PayCodeID
				AND SOURCE.PayCodeGroupID = TARGET.PayCodeGroupID
				--AND SOURCE.EmployeeID = TARGET.EmployeeID
				AND SOURCE.PayPeriodID = TARGET.PayPeriodID
				AND SOURCE.TimeClassID = TARGET.TimeClassID
				AND SOURCE.DateID = TARGET.DateID
		WHEN MATCHED AND 
			(target.Hours <> source.Hours
			or target.Dollars <> source.Dollars
			or target.FTEs <> source.FTEs
			)
			THEN
				UPDATE
				SET target.Hours = source.Hours,
					target.Dollars = source.Dollars,
					target.FTEs	= source.FTEs
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					DepartmentID,
					JobCodeID,
				--	PayCodeID,
					PayCodeGroupID,
				--	EmployeeID,
					PayPeriodID,
					DateID,
					TimeClassID,
					Hours,
					Dollars,
					FTEs,
					IsDeleted
					)
				VALUES (
					DepartmentID,
					JobCodeID,
					--PayCodeID,
					PayCodeGroupID,
					--EmployeeID,
					PayPeriodID,
					DateID,
					TimeClassID,
					Hours,
					Dollars,
					FTEs,
					0
					)
		WHEN NOT MATCHED BY SOURCE
			THEN
				DELETE;

DELETE FROM [fw].[FactPayrollSampledDaily] where TimeClassID = 1 and Dollars = 0 and Hours = 0

END

 IF OBJECT_ID('tempdb..#departments') IS NOT NULL DROP TABLE #departments
 IF OBJECT_ID('tempdb..#dates') IS NOT NULL DROP TABLE #dates;
GO


---------------------------------------------

-- fw.procPayrollSampledMonthlyDetailedInsert
/************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		9.19.14		MJS		B-02788	Excluding Budget data from the detailed sample since budgeting at Pay Code level is not supported
** 2		2015-10-28	MJS		D-03587	Added logic to exclude ignored hours and dollars
** 3		2016-09-22	AK		B-11845	Added procFactPayrollSampledDetailedBaselineTargetUpdate
** 4		2016-12-13	NL		B-13759	Added fiscalYearID param and filtering
** 5		2017-02-22	GF		D-05545	Move duplicate record handling from YTD into sampling + general cleanup
** 6		2017-02-22	IP		B-14098 MR - Adjust Budgeted FTEs (Sampling). Added part that adds adjusted values to temp table #TEMPPAYROLL
** 7		2017-03-06	GF		B-14693	Added baseline target year filter
** 8		2017-03-08	GF		B-14693	Fix adjustment records year filter handling
** 9		2017-04-11	IP		B-15086	Sampling Performance Improvements. Using temp tables insead of fw.FactPayrollSampledMonthlyDetailed.
** 10		2017-06-12	IP				Changed type of hours/dollars fields to numeric instead of "money"
** 11		2017-06-15	IP		B-15086 Modify SP to use unique temp table
** 12		2017-07-11	IP		D-06150 Fixed conditions of merge statement (update part)
** 13		2017-07-13	IP		TK-45395 Fixed conditions of merge statement (include isSystemGenerated column)
** 14		2017-08-29	ip		B-16798		Add using of Budget Adjustment.
** 15		2018-01-17	IP		B-16703 Omit archived budget adjustments
** 16		2018-02-07	IP		B-18725 MR - Provider sampling from payroll
** 17		2018-02-09	IP 		B-18724	Omit archived Budgeted FTE Adjustments
** 18		2019-06-26	OV 		D-08576 FTEs are not calculated for first FY, deleted transaction
** 19		2023-09-13	KF 		JAZZ-55750 Remove filter to allow other time classes in MR reporting
*************************************************************/
CREATE proc [fw].[procPayrollSampledMonthlyDetailedInsert]
	@fiscalYearID smallint = 0
as	
	print 'Starting calculating staging table --- '+convert(varchar(20),GETDATE(),113) 
	IF OBJECT_ID('tempdb..#PayrollSampledMonthlyDetailedStaging') IS NOT NULL  DROP TABLE #PayrollSampledMonthlyDetailedStaging
	IF OBJECT_ID('fw.PayrollSampledMonthlyDetailedStagingWithCalcs') IS NOT NULL  DROP TABLE fw.PayrollSampledMonthlyDetailedStagingWithCalcs
	
	DECLARE
		@fromClause nvarchar(max),
		@whereClause nvarchar(max),
		@MaxBatchID INT,
		@BatchID INT,
		@batchSize INT

	--pull new data - data integration
	CREATE TABLE #PayrollSampledMonthlyDetailedStaging (RowID bigint identity(1,1), DepartmentID int, JobCodeID int, EmployeeID int, PayCodeID int, PayCodeGroupID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Hours decimal(18,6), Dollars decimal(18,6), FTEs decimal(18,6),isDeleted bit, isSystemGenerated bit)
	INSERT INTO #PayrollSampledMonthlyDetailedStaging(DepartmentID, JobCodeID, EmployeeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, TimeClassID, Hours, Dollars, FTEs)
	SELECT
		pr.DepartmentID,
		pr.JobCodeID,
		pr.EmployeeID,
		pr.PayCodeID,
		pc.PayCodeGroupID,
		PR.FiscalYearID,
		pr.FiscalMonthID,
		pr.TimeClassID,
		SUM(CASE WHEN pr.unittypeID=51 and pc.IsHoursIgnored=0 then value ELSE 0 END) AS Hours,
		SUM(CASE WHEN pr.unittypeID=34 and pc.IsDollarsIgnored=0 then value ELSE 0 END) AS Dollars,
		0 as FTEs
	FROM
		int.FactStaffing pr
		INNER JOIN fw.DimPayCode pc on pc.PayCodeID = PR.PayCodeID
		left join mr.viewFactProviderBasedOnPayroll vw on vw.RowID = pr.RowID
	WHERE 
		pr.FiscalMonthCode not in('', '0')		
		and pr.IsDeleted = 0
		and pr.Value != 0
		AND (pr.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0)
		and isnull(IsProvider,0) = 0
    GROUP BY
		pr.DepartmentID,
		pr.JobCodeID,
		pr.EmployeeID,
		pr.PayCodeID,
		pc.PayCodeGroupID,
		PR.FiscalYearID,
		pr.FiscalMonthID,
		pr.TimeClassID,
		pr.PayCodeID
	-- BudgetAdjustments Start
	declare @iteration int = 1 
	DECLARE @BudgetReallocationGUID uniqueidentifier,@date datetime,@BudgetReallocationType varchar(50)

	DECLARE BRA_cursor CURSOR FOR   
	SELECT distinct BudgetReallocationGUID,date,BudgetReallocationType from fw.BudgetReallocationWithDefinedType
	WHERE (FiscalYearID = @FiscalYearID or @FiscalYearID = 0) and DataType = 1
	ORDER BY date;  

	OPEN BRA_cursor  

	FETCH NEXT FROM BRA_cursor   
	INTO @BudgetReallocationGUID,@date,@BudgetReallocationType   

	WHILE @@FETCH_STATUS = 0  
	BEGIN  

		INSERT INTO #PayrollSampledMonthlyDetailedStaging(DepartmentID, JobCodeID, EmployeeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, TimeClassID, Hours, Dollars, FTEs)
			SELECT TargetDepartmentID as DepartmentID,TargetJobCodeID as JobCodeID, stt.EmployeeID, stt.PayCodeID, stt.PayCodeGroupID, stt.FiscalYearID, stt.FiscalMonthID, stt.TimeClassID, stt.Hours, stt.Dollars, stt.FTEs
			FROM #PayrollSampledMonthlyDetailedStaging STT
			INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceJobCodeID = stt.JobCodeID and b.FiscalYearID = stt.FiscalYearID
			INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID
			where 
				b.BudgetReallocationGUID = @BudgetReallocationGUID
				and TimeClassID = 2
				and DataType = 1
				and Archived = 0

			UPDATE STT
			SET Dollars = 0,
				Hours = 0,
				FTEs = 0
			FROM #PayrollSampledMonthlyDetailedStaging STT
			INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceJobCodeID = stt.JobCodeID and b.FiscalYearID = stt.FiscalYearID
			INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID
			where 
				b.BudgetReallocationGUID = @BudgetReallocationGUID
				and TimeClassID = 2
				and DataType = 1
				and Archived = 0

		set @iteration  = @iteration +1

		FETCH NEXT FROM BRA_cursor   
		INTO @BudgetReallocationGUID,@date,@BudgetReallocationType   
	END
	CLOSE BRA_cursor;  
	DEALLOCATE BRA_cursor;  
	-- BudgetAdjustments END


	--pull new data - adjustments
	DECLARE @NonProdGroupID INT = (
		SELECT TOP 1 pcg.PayCodeGroupID
		FROM fw.DimProductiveClass pc
		INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID
		WHERE pc.Name = 'Non-Productive' AND pcg.PayCodeGroupID != 0
		ORDER BY pcg.SortOrder)

	DECLARE @ProdGroupID INT = (
		SELECT TOP 1 pcg.PayCodeGroupID
		FROM fw.DimProductiveClass pc
		INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID
		WHERE pc.Name = 'Productive' AND pcg.PayCodeGroupID != 0
		ORDER BY pcg.SortOrder)

	DECLARE @NonProdPayCodeID INT = (
		SELECT TOP 1 pcg.DefaultPayCodeID
		FROM fw.DimProductiveClass pc
		INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID
		WHERE pc.Name = 'Non-Productive' AND pcg.PayCodeGroupID != 0
		ORDER BY pcg.SortOrder)

	DECLARE @ProdPayCodeID INT = (
		SELECT TOP 1 pcg.DefaultPayCodeID
		FROM fw.DimProductiveClass pc
		INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID
		WHERE pc.Name = 'Productive' AND pcg.PayCodeGroupID != 0
		ORDER BY pcg.SortOrder)
		
	INSERT INTO #PayrollSampledMonthlyDetailedStaging(DepartmentID, JobCodeID, EmployeeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, TimeClassID, Hours, Dollars, FTEs)

	SELECT b.DepartmentID,
		b.JobCodeID,
		0 as EmployeeID,
		@NonProdPayCodeID AS PayCodeID,
		@NonProdGroupID AS PayCodeGroupID,
		b.FiscalYearID,
		ba.FiscalMonthID,
		2 AS TimeClassID, -- always Budgeted
		ba.NonProductiveChange AS Hours,
		0 AS Dollars,
		0 AS FTEs
	FROM mr.BudgetPayrollReallocationAdjustment ba
	INNER JOIN mr.BudgetPayrollReallocation b ON b.BudgetPayrollReallocationGUID = ba.BudgetPayrollReallocationGUID
			LEFT JOIN 
		(select SourceDepartmentID as DepartmentID,
			 SourceJobCodeID as JobCodeID,
			 FiscalYearID,
			 FiscalMonthID
		FROM [mr].[BudgetReallocation] b
		INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		WHERE DataType = 1
		UNION ALL
		select TargetDepartmentID as DepartmentID,
			 TargetJobCodeID as JobCodeID,
			 FiscalYearID,
			 FiscalMonthID
		FROM [mr].[BudgetReallocation] b
		INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		WHERE DataType = 1
		) fact on fact.DepartmentID = b.DepartmentID and fact.JobCodeID = b.JobCodeID and fact.FiscalYearID = b.FiscalYearID and fact.FiscalMonthID = ba.FiscalMonthID
	WHERE (@fiscalYearID = 0 or b.FiscalYearID = @fiscalYearID) and fact.DepartmentID is null and b.Archived = 0
	UNION ALL
	SELECT b.DepartmentID,
		b.JobCodeID,
		0 as EmployeeID,
		@ProdPayCodeID AS PayCodeID,
		@ProdGroupID AS PayCodeGroupID,
		b.FiscalYearID,
		ba.FiscalMonthID,
		2 AS TimeClassID, -- always Budgeted
		ba.ProductiveChange AS Hours,
		0 AS Dollars,
		0 AS FTEs
	FROM mr.BudgetPayrollReallocationAdjustment ba
	INNER JOIN mr.BudgetPayrollReallocation b ON b.BudgetPayrollReallocationGUID = ba.BudgetPayrollReallocationGUID		
			LEFT JOIN 
		(select SourceDepartmentID as DepartmentID,
			 SourceJobCodeID as JobCodeID,
			 FiscalYearID,
			 FiscalMonthID
		FROM [mr].[BudgetReallocation] b
		INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		WHERE DataType = 1
		UNION ALL
		select TargetDepartmentID as DepartmentID,
			 TargetJobCodeID as JobCodeID,
			 FiscalYearID,
			 FiscalMonthID
		FROM [mr].[BudgetReallocation] b
		INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		WHERE DataType = 1
		) fact on fact.DepartmentID = b.DepartmentID and fact.JobCodeID = b.JobCodeID and fact.FiscalYearID = b.FiscalYearID and fact.FiscalMonthID = ba.FiscalMonthID
	WHERE (@fiscalYearID = 0 or b.FiscalYearID = @fiscalYearID) and fact.DepartmentID is null and b.Archived = 0

	--run calculations
	exec fw.procFactMonthlyMergeDuplicates '#PayrollSampledMonthlyDetailedStaging', 'JobCodeID,EmployeeID,PayCodeGroupID,PayCodeID', 'Dollars,Hours', @fiscalYearID, 0, 0
	--exec client.procPayrollMonthlyPostSampleAccrual --custom accrual process: customize it for different accruals, by default does nothing
    exec fw.procFactPayrollSampledDetailedBaselineTargetUpdate @fiscalYearID = @fiscalYearID
	exec fw.procFactMonthlyYTDPriorYearUpdateStaging 'fw.FactPayrollSampledMonthlyDetailed','#PayrollSampledMonthlyDetailedStaging','JobCodeID,EmployeeID,PayCodeGroupID,PayCodeID', 'Dollars,Hours', @fiscalYearID, 0, 0
	exec client.procFactPayrollSampledMonthlyDetailedFTEsInsertStaging

	print 'finish staging calculations  --- '+convert(varchar(20),GETDATE(),113)	

	-- insert result
	IF @fiscalYearID = 0 
	BEGIN
		truncate table fw.FactPayrollSampledMonthlyDetailed

		-- split by batches
		IF OBJECT_ID('tempdb..#inputDetails') IS NOT NULL DROP TABLE #inputDetails
		SELECT
			@fromClause = 'fw.PayrollSampledMonthlyDetailedStagingWithCalcs s',
			@whereClause = ''

		EXEC mr.procGetIntBatchSize
			@DefaultBatchSize = 60000000,
			@ResultBatchSize = @batchSize OUTPUT
 
		CREATE TABLE #inputDetails (DepartmentID INT, RecordsCount INT, BatchID INT)
		INSERT INTO #inputDetails
		EXEC dbo.procGetInputDataByBatches
	  		@batchSize = @batchSize,
			@columnName = 'DepartmentID',
			@tableAlias = 's',
			@fromClause = @fromClause,
			@whereClause = @whereClause,
			@isDebug = 0

		SELECT @MaxBatchID = MAX(BatchID) FROM #inputDetails

		SET @BatchID = 1
		WHILE @BatchID <= @MaxBatchID
		BEGIN
			INSERT INTO fw.FactPayrollSampledMonthlyDetailed With (TABLOCKX) (
				DepartmentID,
				FiscalMonthID,
				FiscalYearID,
				JobCodeID,
				PayCodeID,
				PayCodeGroupID,
				EmployeeID,
				TimeClassID,
				Dollars,
				DollarsYTD,
				DollarsPriorYear,
				DollarsPriorYTD,
				Hours,
				HoursYTD,
				HoursPriorYear,
				HoursPriorYTD,
				FTEs,
				FTEsYTD,
				FTEsPriorYear,
				FTEsPriorYTD,
				IsDeleted,
				IsSystemGenerated
			)
			SELECT
				S.DepartmentID,
				S.FiscalMonthID,
				S.FiscalYearID,
				S.JobCodeID,
				S.PayCodeID,
				S.PayCodeGroupID,
				S.EmployeeID,
				S.TimeClassID,
				S.Dollars,
				S.DollarsYTD,
				COALESCE(S.DollarsPriorYear,0),
				S.DollarsPriorYTD,
				S.Hours,
				S.HoursYTD,
				COALESCE(S.HoursPriorYear,0),
				S.HoursPriorYTD,
				S.FTEs,
				S.FTEsYTD,
				COALESCE(S.FTEsPriorYear,0),
				COALESCE(S.FTEsPriorYTD,0),
				0 as IsDeleted,
				isnull(S.IsSystemGenerated,0) as IsSystemGenerated
			FROM fw.PayrollSampledMonthlyDetailedStagingWithCalcs S
			INNER JOIN #inputDetails ISD ON ISD.DepartmentID = S.DepartmentID
			WHERE ISD.BatchID = @BatchID

			SET @BatchID = @BatchID + 1
		END
	END
ELSE 
	BEGIN

		print 'Starting creating index --- '+convert(varchar(20),GETDATE(),113) 
		CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.PayrollSampledMonthlyDetailedStagingWithCalcs (DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID,FiscalYearID,FiscalMonthID,TimeClassID)
		print 'Starting transaction --- '+convert(varchar(20),GETDATE(),113) 
	
	    MERGE fw.FactPayrollSampledMonthlyDetailed With (TABLOCKX) AS target
		USING fw.PayrollSampledMonthlyDetailedStagingWithCalcs AS source
			ON source.DepartmentID = target.DepartmentID
				AND source.JobCodeID = target.JobCodeID
				AND source.EmployeeID = target.EmployeeID
				AND source.PayCodeID = target.PayCodeID
				AND source.PayCodeGroupID = target.PayCodeGroupID
				AND source.FiscalYearID = target.FiscalYearID
				AND source.FiscalMonthID = target.FiscalMonthID
				AND source.TimeClassID = target.TimeClassID
				AND source.PayCodeID = target.PayCodeID
		WHEN MATCHED AND 
			(target.Dollars <> source.Dollars
			or target.DollarsYTD <> source.DollarsYTD
			or target.DollarsPriorYear <> COALESCE(source.DollarsPriorYear,0)
			or target.DollarsPriorYTD <> COALESCE(source.DollarsPriorYTD,0)
			or target.Hours <> source.Hours
			or target.HoursYTD <> source.HoursYTD
			or target.HoursPriorYear <> COALESCE(source.HoursPriorYear,0)
			or target.HoursPriorYTD <> COALESCE(source.HoursPriorYTD,0)
			or target.FTEs <> source.FTEs
			or target.FTEsYTD <> source.FTEsYTD
			or target.FTEsPriorYear <> COALESCE(source.FTEsPriorYear,0)
			or target.FTEsPriorYTD <> COALESCE(source.FTEsPriorYTD,0)
			or target.isSystemGenerated <> source.isSystemGenerated)
			THEN
				UPDATE
				SET target.Dollars = source.Dollars,
					target.DollarsYTD = source.DollarsYTD,
					target.DollarsPriorYear = COALESCE(source.DollarsPriorYear,0),
					target.DollarsPriorYTD = COALESCE(source.DollarsPriorYTD,0),
					target.Hours = source.Hours,
					target.HoursYTD = source.HoursYTD,
					target.HoursPriorYear = COALESCE(source.HoursPriorYear,0),
					target.HoursPriorYTD = COALESCE(source.HoursPriorYTD,0),
					target.FTEs = source.FTEs,
					target.FTEsYTD = source.FTEsYTD,
					target.FTEsPriorYear = COALESCE(source.FTEsPriorYear,0),
					target.FTEsPriorYTD = COALESCE(source.FTEsPriorYTD,0),
					target.isSystemGenerated = source.isSystemGenerated
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					DepartmentID,
					FiscalMonthID,
					FiscalYearID,
					JobCodeID,
					PayCodeID,
					PayCodeGroupID,
					EmployeeID,
					TimeClassID,
					Dollars,
					DollarsYTD,
					DollarsPriorYear,
					DollarsPriorYTD,
					Hours,
					HoursYTD,
					HoursPriorYear,
					HoursPriorYTD,
					FTEs,
					FTEsYTD,
					FTEsPriorYear,
					FTEsPriorYTD,
					IsDeleted,
					IsSystemGenerated
					)
				VALUES (
					source.DepartmentID,
					source.FiscalMonthID,
					source.FiscalYearID,
					source.JobCodeID,
					source.PayCodeID,
					source.PayCodeGroupID,
					source.EmployeeID,
					source.TimeClassID,
					source.Dollars,
					source.DollarsYTD,
					COALESCE(source.DollarsPriorYear,0),
					COALESCE(source.DollarsPriorYTD,0),
					source.Hours,
					source.HoursYTD,
					COALESCE(source.HoursPriorYear,0),
					COALESCE(source.HoursPriorYTD,0),
					source.FTEs,
					source.FTEsYTD,
					COALESCE(source.FTEsPriorYear,0),
					COALESCE(source.FTEsPriorYTD,0),
					0,
					isnull(IsSystemGenerated,0)
					)
		WHEN NOT MATCHED BY SOURCE
			AND Target.FiscalYearID = @fiscalYearID		
			THEN
				DELETE;

	END
	
	IF OBJECT_ID('tempdb..#PayrollSampledMonthlyDetailedStaging') IS NOT NULL  DROP TABLE #PayrollSampledMonthlyDetailedStaging
	IF OBJECT_ID('fw.PayrollSampledMonthlyDetailedStagingWithCalcs') IS NOT NULL  DROP TABLE fw.PayrollSampledMonthlyDetailedStagingWithCalcs
	IF OBJECT_ID('tempdb..#PayrollSampledMonthlyDetailedStaging') IS NOT NULL  DROP TABLE #PayrollSampledMonthlyDetailedStaging
GO


---------------------------------------------

-- fw.procPayrollSampledMonthlyFlexInsert
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI			Description
** 1		5/10/16		NL			B-11692		Including FiscalYearID in delete
** 2		02/20/2017	GF			D-05545		Move duplicate record handling from YTD into sampling + general cleanup
*************************************************************/
CREATE proc [fw].[procPayrollSampledMonthlyFlexInsert]
	@fiscalyearid smallint
with recompile
AS
	--delete existing data
	WHILE EXISTS(SELECT NULL FROM fw.FactPayrollSampledMonthly (nolock) WHERE FiscalYearID = @fiscalYearID and TimeClassID = 4) BEGIN
		DELETE TOP (10000) fw.FactPayrollSampledMonthly WHERE FiscalYearID = @fiscalYearID and TimeClassID = 4
	END

	--pull new data	
	CREATE TABLE #TEMPPAYROLL (DepartmentID int, JobCodeID int, PayCodeID int, PayCodeGroupID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Hours money, Dollars money, FTEs decimal(18,6));
	INSERT INTO #TEMPPAYROLL(DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, TimeClassID, Hours, Dollars, FTEs)
	SELECT
		pr.DepartmentID,
		pr.JobCodeID,
		'0' as PayCodeID,
		pc.PayCodeGroupID,
		PR.FiscalYearID,
		pr.FiscalMonthID,
		pr.TimeClassID,
		SUM(CASE WHEN pr.unittypeID = 51 and pc.IsHoursIgnored=0 then value ELSE 0 END) AS Hours,
		SUM(CASE WHEN pr.unittypeID = 34 and pc.IsDollarsIgnored=0 then value ELSE 0 END) AS Dollars,
		0 as FTEs
	FROM
		int.FactStaffing pr
		INNER JOIN fw.DimPayCode pc on pc.PayCodeID = PR.PayCodeID
	WHERE 
		PR.FiscalMonthCode not in('', '0')		
		and pr.IsDeleted = 0
		and pr.Value != 0
		AND	TimeClassID = 2
		AND FiscalYearID = @fiscalyearid
    GROUP BY
		pr.DepartmentID,
		pr.JobCodeID,
		pc.PayCodeGroupID,
		PR.FiscalYearID,
		pr.FiscalMonthID,
		pr.TimeClassID

	--push to fact table
	INSERT INTO fw.FactPayrollSampledMonthly(DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, TimeClassID, Hours, Dollars, FTEs)		
	SELECT
		DepartmentID,		
		JobCodeID,
		PayCodeID,
		PayCodeGroupID,
		FiscalYearID,
		FiscalMonthID,
		4,
		SUM(Hours),
		SUM(Dollars),
		0 as FTEs
	FROM #TEMPPAYROLL
	GROUP BY 
		DepartmentID,		
		JobCodeID,
		PayCodeID,
		PayCodeGroupID,
		FiscalYearID,
		FiscalMonthID,
		TimeClassID
	HAVING
		SUM(Hours) != 0
		or SUM(Dollars) != 0

	--run calculations
	exec fw.procFactMonthlyMergeDuplicates 'fw.FactPayrollSampledMonthly', 'JobCodeID,PayCodeID,PayCodeGroupID', 'Dollars,Hours', @fiscalYearID, 4, 0
	exec fw.procFactMonthlyYTDPriorYearUpdate 'fw.FactPayrollSampledMonthly', 'JobCodeID,PayCodeID,PayCodeGroupID', 'Dollars,Hours', @fiscalYearID, 4, 0
GO


---------------------------------------------

-- fw.procPayrollSampledMonthlyInsert
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2014-03-03	akk		D-01526	Removing payroll import from sampling proc because it's redundant
** 2		2014-08-05	MJS		B-02684	Updating sampling to include PayCodeGroupID
** 3		2014-09-03	MJS		B-02863	Removing the parameter from the YTD proc call
** 4		2014-09-19	MJS		B-02788	Setting PayCodeID to 0; Pay Code level data to be sourced from the PayrollSampledMonthlyDetailed data table
** 5		2015-10-28	MJS		D-03587	Added logic to exclude ignored hours and dollars
** 6		2016-09-22	AK		B-11845	Added procFactPayrollSampledBaselineTargetUpdate
** 7		2016-12-13	NL		B-13759	Added fiscalYearID param and filtering
** 8		2017-02-20	GF		D-05545	Move duplicate record handling from YTD into sampling + general cleanup
** 9		2017-02-22	IP		B-14098 MR - Adjust Budgeted FTEs (Sampling). Added part that adds adjusted values to temp table #TEMPPAYROLL
** 10		2017-03-06	GF		B-14693	Added baseline target year filter
** 11		2017-03-08	GF		B-14693	Fix adjustment records year filter handling
** 12		2017-03-30	IP		B-15085     Performace optimization by aggregating "detailed" data
** 13		2017-07-11	IP		D-06150 Fixed conditions of merge statement (update part)
** 14		2017-07-25	IP		B-17618 Applied logic for TimeClassID=20 when Target basis = "Prior Year" for FTE. Now it is equal to Prior Year hours divided by Prior Year FTE denominator.
** 15		2019-06-13	OV		D-08158 Added join to jobcodegroup for Override
** 16		2019-06-19	OV		TK-75157 FTEsPriorYear, FTEsPriorYTD are calculated incorrectly
** 17		2019-10-21	KF		D-08819 FTE Baseline Calculation Issue
** 18		2023-09-14	KF		JAZZ-55750 Remove filter to allow other time classes in MR reporting
*************************************************************/
CREATE PROCEDURE [fw].[procPayrollSampledMonthlyInsert] @fiscalYearID SMALLINT = 0
AS
	--run custom scripts
	exec [client].[procPayrollSampledInsertPreprocess]

	--delete existing data
	IF(@fiscalYearID = 0) BEGIN
		TRUNCATE TABLE fw.FactPayrollSampledMonthly
	END ELSE BEGIN
		DECLARE @batchSize INT
		EXEC mr.procGetIntBatchSize
			@DefaultBatchSize = 10000000,
			@ResultBatchSize = @batchSize OUTPUT

	  	WHILE EXISTS(SELECT NULL FROM fw.FactPayrollSampledMonthly (nolock) WHERE FiscalYearID = @fiscalYearID) BEGIN
			DELETE TOP (@batchSize) fw.FactPayrollSampledMonthly WHERE FiscalYearID = @fiscalYearID
		END
	END
/*If Target basis is rolling average then we can't calculate baseline as simple sum of detailed table.
 in his case we should
	1)insert summed values for all timeclasses except baseline (TimeClassId  = 20)
	2)recalculate baseline 
	3)run stored procedure to update columns YTD, priorYear etc.
*/
declare @TargetBasis int = (select Value from mr.SystemSetting where Name = 'Target Basis')
IF @TargetBasis = 10 -- rolling average
BEGIN
insert into fw.FactPayrollSampledMonthly (
	DepartmentID,
	JobCodeID,
	PayCodeID,
	FiscalYearID,
	FiscalMonthID,
	TimeClassID,
	PayCodeGroupID,
	IsSystemGenerated,
	Hours,
	HoursYTD,
	HoursPriorYear,
	HoursPriorYTD,
	Dollars,
	DollarsYTD,
	DollarsPriorYear,
	DollarsPriorYTD,
	FTEs,
	FTEsYTD,
	FTEsPriorYear,
	FTEsPriorYTD
)
SELECT fact.DepartmentID,
	fact.JobCodeID,
	fact.PayCodeID,
	fact.FiscalYearID,
	fact.FiscalMonthID,
	fact.TimeClassID,
	fact.PayCodeGroupID,
	IsSystemGenerated = case when fact.Hours = 0 and fact.Dollars = 0 then 1 else 0 end,
	fact.Hours,
	fact.HoursYTD,
	fact.HoursPriorYear,
	fact.HoursPriorYTD,
	fact.Dollars,
	fact.DollarsYTD,
	fact.DollarsPriorYear,
	fact.DollarsPriorYTD,
	FTEs = isnull(case when pcg.ProductiveClassID in ('3','2') then fact.Hours /wpmCY.Hours end,0),
	FTEsYTD = isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursYTD /wpmCY.YTDHours end,0),
	FTEsPriorYear = isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursPriorYear / wpmPY.Hours end,0),
	FTEsPriorYTD = isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursPriorYTD / wpmPY.YTDHours end,0)
FROM (
	SELECT DepartmentID,
		JobCodeID,
		PayCodeID,
		FiscalYearID,
		FiscalMonthID,
		TimeClassID,
		sum(Hours) AS Hours,
		sum(HoursYTD) AS HoursYTD,
		sum(HoursPriorYear) AS HoursPriorYear,
		sum(HoursPriorYTD) AS HoursPriorYTD,
		sum(Dollars) AS Dollars,
		sum(DollarsYTD) AS DollarsYTD,
		sum(DollarsPriorYear) AS DollarsPriorYear,
		sum(DollarsPriorYTD) AS DollarsPriorYTD,
		PayCodeGroupID,
		IsSystemGenerated = min(cast(IsSystemGenerated as tinyint))
	FROM fw.FactPayrollSampledMonthlyDetailed
	WHERE (	FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) 
		and TimeClassID <> 20  -- all timeclasses except baseline (TimeClassId  = 20)
	GROUP BY DepartmentID,
		JobCodeID,
		PayCodeID,
		FiscalYearID,
		FiscalMonthID,
		TimeClassID,
		PayCodeGroupID
	) fact
	LEFT JOIN [fw].[DimDepartment] D
		ON fact.DepartmentID = D.DepartmentID
	LEFT JOIN [fw].[DimJobCode] JC
		ON fact.JobCodeID = JC.JobCodeID
    LEFT JOIN fw.DimJobCodeGroup JCG 
	    ON JCG.JobCodeGroupID = JC.JobCodeGroupID
	LEFT JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY
		ON fact.FiscalMonthID = wpmCY.FiscalMonthID
			AND fact.FiscalYearID = wpmCY.FiscalYearID
			AND wpmCY.WorkWeekID = CASE WHEN jc.WorkWeekOverrideID = - 1 and jcg.WorkWeekOverrideID = - 1 THEN D.WorkWeekID ELSE 
			                       CASE WHEN jc.WorkWeekOverrideID = - 1 and jcg.WorkWeekOverrideID <> - 1 THEN  jcg.WorkWeekOverrideID 
								   ELSE jc.WorkWeekOverrideID END END
	LEFT JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmPY
		ON fact.FiscalMonthID = wpmPY.FiscalMonthID
			AND (fact.FiscalYearID - 1) = wpmPY.FiscalYearID
			AND wpmPY.WorkWeekID = CASE WHEN jc.WorkWeekOverrideID = - 1 and jcg.WorkWeekOverrideID = - 1 THEN D.WorkWeekID ELSE 
			                       CASE WHEN jc.WorkWeekOverrideID = - 1 and jcg.WorkWeekOverrideID <> - 1 THEN  jcg.WorkWeekOverrideID 
								   ELSE jc.WorkWeekOverrideID END END
	LEFT JOIN fw.DimFiscalMonth fm
		ON fact.FiscalMonthID = fm.FiscalMonthID
	LEFT JOIN [fw].[DimPayCodeGroup] pcg
		ON fact.PayCodeGroupID = pcg.PayCodeGroupID
	WHERE 	fact.Hours <> 0
	or fact.HoursYTD <> 0
	or fact.HoursPriorYear <> 0
	or fact.HoursPriorYTD <> 0
	or fact.Dollars <> 0
	or fact.DollarsYTD <> 0
	or fact.DollarsPriorYear <> 0
	or fact.DollarsPriorYTD <> 0
	or isnull(case when pcg.ProductiveClassID in ('3','2') then fact.Hours /wpmCY.Hours end,0) <> 0
	or isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursYTD /wpmCY.YTDHours end,0)  <> 0
	or isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursPriorYear / wpmPY.Hours end,0)  <> 0
	or isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursPriorYTD / wpmPY.YTDHours end,0)  <> 0

	exec fw.procFactPayrollSampledBaselineTargetUpdate @fiscalYearID = @fiscalYearID  -- recalculate baseline for just inserted values
	exec fw.procFactMonthlyYTDPriorYearUpdate 'fw.FactPayrollSampledMonthly', 'JobCodeID,PayCodeGroupID,PayCodeID', 'Dollars,Hours', @fiscalYearID, 20, 0 -- update baseline records columns
	
	exec fw.procFactPayrollSampledMonthlyUpdateFTEs @fiscalYearID = @fiscalYearID, @timeClassID = 20

END
ELSE  /*Here is  inserting aggregated rows in case when "Target Basis" is not rolling average*/
BEGIN
insert into fw.FactPayrollSampledMonthly (
	DepartmentID,
	JobCodeID,
	PayCodeID,
	FiscalYearID,
	FiscalMonthID,
	TimeClassID,
	PayCodeGroupID,
	IsSystemGenerated,
	Hours,
	HoursYTD,
	HoursPriorYear,
	HoursPriorYTD,
	Dollars,
	DollarsYTD,
	DollarsPriorYear,
	DollarsPriorYTD,
	FTEs,
	FTEsYTD,
	FTEsPriorYear,
	FTEsPriorYTD
)
SELECT fact.DepartmentID,
	fact.JobCodeID,
	fact.PayCodeID,
	fact.FiscalYearID,
	fact.FiscalMonthID,
	fact.TimeClassID,
	fact.PayCodeGroupID,
	IsSystemGenerated = case when fact.Hours = 0 and fact.Dollars = 0 then 1 else 0 end,
	fact.Hours,
	fact.HoursYTD,
	fact.HoursPriorYear,
	fact.HoursPriorYTD,
	fact.Dollars,
	fact.DollarsYTD,
	fact.DollarsPriorYear,
	fact.DollarsPriorYTD,
	FTEs = isnull(case when pcg.ProductiveClassID in ('3','2') then fact.Hours /wpmCY.Hours end,0),
	FTEsYTD = isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursYTD /wpmCY.YTDHours end,0),
	FTEsPriorYear = isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursPriorYear / wpmPY.Hours end,0),
	FTEsPriorYTD = isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursPriorYTD / wpmPY.YTDHours end,0)
FROM (
	SELECT DepartmentID,
		JobCodeID,
		PayCodeID,
		FiscalYearID,
		FiscalMonthID,
		TimeClassID,
		sum(Hours) AS Hours,
		sum(HoursYTD) AS HoursYTD,
		sum(HoursPriorYear) AS HoursPriorYear,
		sum(HoursPriorYTD) AS HoursPriorYTD,
		sum(Dollars) AS Dollars,
		sum(DollarsYTD) AS DollarsYTD,
		sum(DollarsPriorYear) AS DollarsPriorYear,
		sum(DollarsPriorYTD) AS DollarsPriorYTD,
		PayCodeGroupID,
		IsSystemGenerated = min(cast(IsSystemGenerated as tinyint))
	FROM fw.FactPayrollSampledMonthlyDetailed
	WHERE (	FiscalYearID = @fiscalYearID OR @fiscalYearID = 0)
	GROUP BY DepartmentID,
		JobCodeID,
		PayCodeID,
		FiscalYearID,
		FiscalMonthID,
		TimeClassID,
		PayCodeGroupID
	) fact
	LEFT JOIN [fw].[DimDepartment] D
		ON fact.DepartmentID = D.DepartmentID
	LEFT JOIN [fw].[DimJobCode] JC
		ON fact.JobCodeID = JC.JobCodeID
	LEFT JOIN fw.DimJobCodeGroup JCG 
	    ON JCG.JobCodeGroupID = JC.JobCodeGroupID
	LEFT JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY
		ON fact.FiscalMonthID = wpmCY.FiscalMonthID
			AND (
					(@TargetBasis = 1 AND
						(
						  (fact.FiscalYearID-1	=wpmCY.FiscalYearID and TimeClassID = 20)
							OR
						  (fact.FiscalYearID	=wpmCY.FiscalYearID and TimeClassID <> 20)
						)
					 )
				OR
					(@TargetBasis !=1 AND fact.FiscalYearID=wpmCY.FiscalYearID)
				)
			AND wpmCY.WorkWeekID = CASE WHEN jc.WorkWeekOverrideID = - 1 and jcg.WorkWeekOverrideID = - 1 THEN D.WorkWeekID ELSE 
			                       CASE WHEN jc.WorkWeekOverrideID = - 1 and jcg.WorkWeekOverrideID <> - 1 THEN  jcg.WorkWeekOverrideID 
								   ELSE jc.WorkWeekOverrideID END END
	LEFT JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmPY
		ON fact.FiscalMonthID = wpmPY.FiscalMonthID
			AND (
					(@TargetBasis = 1 AND
						(
						  (fact.FiscalYearID-2	=wpmPY.FiscalYearID and TimeClassID = 20)
							OR
						  (fact.FiscalYearID-1	=wpmPY.FiscalYearID and TimeClassID <> 20)
						)
					 )
				OR
					(@TargetBasis !=1 AND fact.FiscalYearID-1 = wpmPY.FiscalYearID)
				)
			AND wpmPY.WorkWeekID = CASE WHEN jc.WorkWeekOverrideID = - 1 and jcg.WorkWeekOverrideID = - 1 THEN D.WorkWeekID ELSE 
			                       CASE WHEN jc.WorkWeekOverrideID = - 1 and jcg.WorkWeekOverrideID <> - 1 THEN  jcg.WorkWeekOverrideID 
								   ELSE jc.WorkWeekOverrideID END END
	LEFT JOIN fw.DimFiscalMonth fm
		ON fact.FiscalMonthID = fm.FiscalMonthID
	LEFT JOIN [fw].[DimPayCodeGroup] pcg
		ON fact.PayCodeGroupID = pcg.PayCodeGroupID
	WHERE 	fact.Hours <> 0
	or fact.HoursYTD <> 0
	or fact.HoursPriorYear <> 0
	or fact.HoursPriorYTD <> 0
	or fact.Dollars <> 0
	or fact.DollarsYTD <> 0
	or fact.DollarsPriorYear <> 0
	or fact.DollarsPriorYTD <> 0
	or isnull(case when pcg.ProductiveClassID in ('3','2') then fact.Hours /wpmCY.Hours end,0) <> 0
	or isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursYTD /wpmCY.YTDHours end,0)  <> 0
	or isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursPriorYear / wpmPY.Hours end,0)  <> 0
	or isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursPriorYTD / wpmPY.YTDHours end,0)  <> 0
END
GO


---------------------------------------------

-- fw.procPayrollSampledMonthlyPerformFlexing
/*************************************************************************************************************************
** Change History
**************************************************************************************************************************
** CID		Date			Author	WI			Description
** 1		5/10/2016		NL		B-11692		Changed flexing to work like new ABB flexing procs
** 2		5/20/2016		NL		B-12055		Removed call to insert flexed data (handled in engine now)
** 3		2/20/2017		GF		D-05545		Move duplicate record handling from YTD into sampling + general cleanup
** 4		10/4/2017		NL		D-06487		Fix some stuff that got lost including ABB dept join
** 5        10/22/2019		KF		D-08819		FTE Baseline Calculation Issue
*************************************************************************************************************************/
CREATE proc [fw].[procPayrollSampledMonthlyPerformFlexing]
	@CostingResultID int,
	@CostingTimeClassID tinyint,
	@FiscalYearID int
with recompile
AS

	--reset all of the flex data to budget (only data that should be flexed like ABB)
	SELECT DISTINCT DepartmentID
	INTO #ABBDepts
	from (
		SELECT DepartmentID FROM [dss].[FactCostingOutDetailGL] WHERE CostingResultID = @CostingResultID
		UNION ALL
		SELECT DepartmentID FROM [dss].[FactCostingOutDetailPayroll] WHERE CostingResultID = @CostingResultID) depts;
	INSERT INTO [fw].[FactPayrollSampledMonthly]([DepartmentID], [JobCodeID], [PayCodeID], [FiscalYearID], [FiscalMonthID], [TimeClassID], [Hours], [HoursYTD], [HoursPriorYear], [HoursPriorYTD], [Dollars], [DollarsYTD], [DollarsPriorYear], [DollarsPriorYTD], [FTEs], [FTEsYTD], [FTEsPriorYear], [FTEsPriorYTD], [IsDeleted], [TransactionID], [PayCodeGroupID], [IsSystemGenerated])
	SELECT [DepartmentID], [JobCodeID], [PayCodeID], [FiscalYearID], [FiscalMonthID], 4, [Hours], [HoursYTD], [HoursPriorYear], [HoursPriorYTD], [Dollars], [DollarsYTD], [DollarsPriorYear], [DollarsPriorYTD], [FTEs], [FTEsYTD], [FTEsPriorYear], [FTEsPriorYTD], [IsDeleted], 12345, [PayCodeGroupID], [IsSystemGenerated]
	FROM [fw].[FactPayrollSampledMonthly]
	WHERE TimeClassID = 2 and FiscalYearID = @FiscalYearID and DepartmentID in ( select DepartmentID from #ABBDepts );

	-- BEGIN CID 4 -- (this used to be right after the "run calculations" comment, before the other procs were called
	exec [fw].[procFactMonthlyMergeDuplicates] 'fw.FactPayrollSampledMonthly', 'JobCodeID,PayCodeGroupID', 'Dollars,Hours', @fiscalYearID, 4, 0
	-- END CID 4 --

	--perform flexing
	UPDATE
		pay
	SET
		pay.Dollars = CASE WHEN ISNULL(pay.Variability, 0) = 0
            			THEN pay.Dollars
			            ELSE ISNULL(((pay.Dollars * (1 - (TotalVariableDirectCost / NULLIF(TotalCost, 0.0)))) + TotalExtendedVariableDirectCost), 0)
         			  END
	FROM
		(SELECT pr.DepartmentID, pr.JobCodeID, pr.PayCodeGroupID, pr.FiscalYearID, pr.FiscalMonthID, pr.TimeClassID, pr.Dollars, ISNULL(jco.Variability, jc.Variability) as Variability
		 FROM [fw].[FactPayrollSampledMonthly] pr
		     LEFT JOIN (SELECT JobCodeID, Variability FROM [dss].[JobCodeVariability] WHERE CostingConfigGuid = (SELECT CostingConfigGuid FROM [dss].[CostingResult] WHERE CostingResultID = @CostingResultID)) jc ON pr.JobCodeID = jc.JobCodeID
		     LEFT JOIN (SELECT DepartmentID, JobCodeID, Variability FROM [dss].[PayCodeJobCodeVariabilityOverride] WHERE CostingConfigGuid = (SELECT CostingConfigGuid FROM [dss].[CostingResult] WHERE CostingResultID = @CostingResultID)) jco ON pr.DepartmentID = jco.DepartmentID AND pr.JobCodeID = jco.JobCodeID
		 WHERE TimeClassID = 4 AND FiscalYearID = @FiscalYearID) pay
		INNER JOIN #ABBDepts abd on pay.DepartmentID = abd.DepartmentID
		LEFT JOIN 
		(SELECT
			DepartmentID,
			JobCodeID,
			PayCodeGroupID,
			FiscalMonthID,
			FiscalYearID,
			SUM(cost.ExtendedVariableDirectCost) as TotalExtendedVariableDirectCost,
			SUM(cost.TotalVariableDirectCost) as TotalVariableDirectCost,
			SUM(cost.TotalCost) as TotalCost
		FROM
			[fw].[viewMRPayrollBudgetCostPerRVUbyMonth] cost
		WHERE
			cost.CostingResultID  = @CostingResultID
			AND
			cost.TimeClassID = @CostingTimeClassID
		GROUP BY
			DepartmentID, JobCodeID, PayCodeGroupID, FiscalMonthID, FiscalYearID
		) cost
		ON pay.DepartmentID = cost.DepartmentID 
			AND pay.JobCodeID = cost.JobCodeID 
			AND pay.PayCodeGroupID = cost.PayCodeGroupID 
			AND cost.FiscalMonthID = pay.FiscalMonthID
			AND cost.FiscalYearID = pay.FiscalYearID

	DROP TABLE #ABBDepts;

	--run calculations
	exec [fw].[procPayrollSampledMonthlyRecalcFlexedHours] @FiscalYearID = @FiscalYearID
	exec [fw].[procFactMonthlyYTDPriorYearUpdate] 'fw.FactPayrollSampledMonthly', 'JobCodeID,PayCodeID,PayCodeGroupID', 'Dollars,Hours', @fiscalYearID, 4, 0
	exec [fw].[procFactPayrollSampledMonthlyUpdateFTEs] @fiscalYearID = @FiscalYearID, @timeClassID = 4

	--delete blank rows
	DELETE FROM [fw].[FactPayrollSampledMonthly]
	WHERE 
		Hours = 0
		and HoursPriorYear = 0
		and HoursPriorYTD = 0
		and HoursYTD = 0
		and Dollars = 0
		and DollarsPriorYear = 0
		and DollarsPriorYTD = 0
		and DollarsYTD = 0
GO


---------------------------------------------

-- fw.procPayrollSampledMonthlyRecalcFlexedHours
CREATE PROC [fw].[procPayrollSampledMonthlyRecalcFlexedHours] 
	@FiscalYearID smallint
AS

/* ************************************************************************************************************************
** Author: Nathan LeRoy
** Create Date: 2016-05-11
** Description: Recalc payroll hours based on dollars flexing for MR
** Last Modified: 2016-05-11
**************************************************************************************************************************
** Change History
**************************************************************************************************************************
** CID		Date		Author	WI		Description
**
*************************************************************************************************************************/

UPDATE
	flex
SET
	flex.Hours = COALESCE(flex.Dollars / NULLIF((orig.Dollars / NULLIF(orig.Hours, 0)), 0), 0) 
FROM
	[fw].[FactPayrollSampledMonthly] flex
	LEFT JOIN 
	[fw].[FactPayrollSampledMonthly] orig
		ON flex.DepartmentID = orig.DepartmentID
		AND flex.JobCodeID = orig.JobCodeID
		AND flex.PayCodeGroupID = orig.PayCodeGroupID
		AND flex.PayCodeID = orig.PayCodeID
		AND flex.FiscalYearID = orig.FiscalYearID
		AND flex.FiscalMonthID = orig.FiscalMonthID
WHERE
	orig.TimeClassID = 2 --budget
	AND
	flex.TimeClassID = 4 --flex
	AND
	orig.FiscalYearID = @FiscalYearID
	AND
	flex.FiscalYearID = @FiscalYearID
GO


---------------------------------------------

-- fw.procPayrollSampledPayPeriodDetailedInsert
/************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		9.19.14		MJS		B-02788	Excluding Budget data from the detailed sample since budgeting at Pay Code level is not supported
** 2		2015-10-28	MJS		D-03587	Added logic to exclude ignored hours and dollars
** 3		2016-09-22	AK		B-11845	Added procFactPayrollSampledDetailedBaselineTargetUpdate
** 4		2016-12-13	NL		B-13759	Added fiscalYearID param and filtering
** 5		2017-02-22	GF		D-05545	Move duplicate record handling from YTD into sampling + general cleanup
** 6		2017-02-22	IP		B-14098 MR - Adjust Budgeted FTEs (Sampling). Added part that adds adjusted values to temp table #TEMPPAYROLL
** 7		2017-03-06	GF		B-14693	Added baseline target year filter
** 8		2017-03-08	GF		B-14693	Fix adjustment records year filter handling
** 9		2017-04-11	IP		B-15086	Sampling Performance Improvements. Using temp tables insead of fw.FactPayrollSampledMonthlyDetailed.
** 10		2017-06-12	IP				Changed type of hours/dollars fields to numeric instead of "money"
** 11		2017-06-15	IP		B-15086 Modify SP to use unique temp table
** 12		2017-07-11	IP		D-06150 Fixed conditions of merge statement (update part)
** 13		2017-07-13	IP		TK-45395 Fixed conditions of merge statement (include isSystemGenerated column)
** 14		2017-08-29 	ip		B-16798		Add using of Budget Adjustment.
** 15		2017-09-26 	GF		TK-48298 	Fixed adjustments for all years case
** 16		2017-11-26 	IP		D-06490 	Fixed splitting for first-last periods
** 17		2018-01-17	IP		B-16703 Omit archived budget adjustments
** 18		2018-02-09	IP 		B-18724	Omit archived Budgeted FTE Adjustments
** 19		2018-02-22	IP 		D-06786	add department calculation for TC = 2 if dept is not in PR , Dept is in Budget Allocation
** 20		2018-05-17	IP 		D-07329	Returning fuctionality to include stats for departments using non-PR driver departments
** 21		2018-08-09	OV		B-19715 added condition where IsPR = 1 for jobcode
** 22       2018-11-16  OV      D-07714 fix: deleted rows where IsPR = 0 for department
** 23		2019-08-19	vfay	D-08311		PR Sampling Proc : removed filtering out 0 Value Rows
** 24		2020-12-07	HV 		JAZZ-11135	Remove table variable in procPayrollSampledPayPeriodDetailedInsert
** 25		2020-12-15	HV 		JAZZ-11506	Bug - PR Sampling: data for beginning of future year is deleted when running Payroll Pay Period Detailed one year sampling
** 26		2020-12-21	HV 		JAZZ-10222	Proc procPayrollSampledPayPeriodDetailedInsert is timing out
** 27		2022-03-11	HV		JAZZ-27781	Run PR Process Task can fail silently during Payroll Sampling
** 28		2022-10-25	HV		JAZZ-45100	Reuse split by batches functionality in existing procedure
** 29		2023-12-04	ishah		JAZZ-62485	Remove @departmentIDs param in procFactPayPeriodYTDPriorYearUpdate_Staging
*************************************************************/
CREATE PROC [fw].[procPayrollSampledPayPeriodDetailedInsert]
	@departmentIDs nvarchar(max) = null,
	@fiscalYearID int = 0
as
	print 'Starting calculating staging table --- '+convert(varchar(20),GETDATE(),113) 
	IF OBJECT_ID('tempdb..#PayrollSampledPayPeriodDetailedStaging') IS NOT NULL  DROP TABLE #PayrollSampledPayPeriodDetailedStaging
	IF OBJECT_ID('tempdb..#PayrollSampledPayPeriodDetailedPreStaging') IS NOT NULL  DROP TABLE #PayrollSampledPayPeriodDetailedPreStaging
	IF OBJECT_ID('fw.PayrollSampledPayPeriodDetailedStagingWithCalcs') IS NOT NULL  DROP TABLE fw.PayrollSampledPayPeriodDetailedStagingWithCalcs
	
	IF OBJECT_ID('tempdb..#DepartmentsBudgetAllocations') IS NOT NULL  DROP TABLE #DepartmentsBudgetAllocations
	CREATE table #DepartmentsBudgetAllocations (DepartmentID int)
	insert into #DepartmentsBudgetAllocations 
	select 
		SourceDepartmentID as DepartmentID 
	from mr.BudgetReallocationAdjustment a
	inner join mr.BudgetReallocation r on r.BudgetReallocationGUID=a.BudgetReallocationGUID
	inner join FW.DimDepartment d on d.DepartmentID = r.TargetDepartmentID and d.IsPR = 1
	where SourceDepartmentID <> 0
		union  -- unique
	select 
		TargetDepartmentID as DepartmentID
	from mr.BudgetReallocationAdjustment a
	inner join mr.BudgetReallocation r on r.BudgetReallocationGUID=a.BudgetReallocationGUID
	inner join FW.DimDepartment d on d.DepartmentID = r.SourceDepartmentID and d.IsPR = 1 -- Filtering all departments that move data FROM selected
	where TargetDepartmentID <> 0

	IF OBJECT_ID('tempdb..#PayPeriodIDs') IS NOT NULL  DROP TABLE #PayPeriodIDs
	CREATE TABLE #PayPeriodIDs (PayPeriodID smallint primary key)
	insert into #PayPeriodIDs 
	select PayPeriodID from fw.DimPayPeriod where @fiscalYearID = 0 or FiscalYearIDSecond = @fiscalYearID

	IF OBJECT_ID('tempdb..#PayPeriodsToMonths') IS NOT NULL  DROP TABLE #PayPeriodsToMonths
	CREATE TABLE #PayPeriodsToMonths (
		PayPeriodID INT,
		PayCycleID INT,
		[PeriodNumber] INT,
		[FiscalMonthID] INT,
		[FiscalYearID] INT,
		[PeriodWeight] NUMERIC(25, 10),
		DaysinPeriodWeight NUMERIC(25, 10)
	)

	INSERT INTO #PayPeriodsToMonths
	SELECT [PayPeriodID],
		PayCycleID,
		[PeriodNumber],
		[FiscalMonthIDStart] AS FiscalMonthID,
		[FiscalYearIDStart] AS FiscalYearID,
		[PeriodWeightStart] AS PreriodWeight,
		DaysinPeriodWeightStart as DaysinPeriodWeight
	FROM [fw].[DimPayPeriod]
	WHERE [PeriodWeightStart] <> 0.0
	UNION ALL

	SELECT [PayPeriodID],
		PayCycleID,
		[PeriodNumber],
		FiscalMonthIDSecond AS FiscalMonthID,
		FiscalYearIDSecond AS FiscalYearID,
		PeriodWeightSecond AS PreriodWeight,
		DaysinPeriodWeightSecond as DaysinPeriodWeight
	FROM [fw].[DimPayPeriod]
	WHERE PeriodWeightSecond <> 0.0

	IF OBJECT_ID('tempdb..#PayrollPayPeriodTempTable') IS NOT NULL  DROP TABLE #PayrollPayPeriodTempTable
	CREATE TABLE #PayrollPayPeriodTempTable (
		DepartmentID INT,		
		JobCodeID INT,
		PayCodeID INT,
		PayCodeGroupID INT,
		EmployeeID INT,
		PayPeriodID int,
		TimeClassID INT,
		Hours NUMERIC(25, 10), 
		Dollars NUMERIC(25, 10),
		ApplyDate DATETIME,
		Src VARCHAR(max)
		)

	--pull new data - data integration
	create table #PayrollSampledPayPeriodDetailedStaging (DepartmentID int, JobCodeID int, PayCodeID int, PayCodeGroupID int, EmployeeID int, PayPeriodID int, TimeClassID int, Hours decimal(18, 6), Dollars decimal(18, 6), isDeleted bit default (0), isSystemGenerated bit default(0))
	create table #PayrollSampledPayPeriodDetailedPreStaging (DepartmentID int, JobCodeID int, PayCodeID int, PayCodeGroupID int, EmployeeID int, PayPeriodID int, TimeClassID int, Hours decimal(18, 6), Dollars decimal(18, 6), isDeleted bit default (0), isSystemGenerated bit default(0))

	insert into #PayrollSampledPayPeriodDetailedPreStaging (DepartmentID, JobCodeID,PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, TimeClassID, Hours, Dollars)
	select
		data.DepartmentID,		
		data.JobCodeID,
		data.PayCodeID,
		pc.PayCodeGroupID,
		data.EmployeeID,
		data.PayPeriodID,
		data.TimeClassID,
		sum(case when data.UnitTypeID = 51 then data.Value else 0 end) as Hours, 
		sum(case when data.UnitTypeID = 34 then data.Value else 0 end) as Dollars
	from
		int.FactStaffingByPayPeriod data
                inner join [fw].[DimJobCode] jc on data.JobCodeID = jc.JobCodeID and IsPR = 1	
		inner join [fw].[DimPayCode] pc on data.PayCodeID=pc.PayCodeID
		inner join [fw].[DimPayPeriod] pp on data.PayPeriodID = pp.PayPeriodID
		inner join [fw].[DimDepartment] d on d.DepartmentID = data.DepartmentID
	where
		data.PayPeriodID != 0
		and data.IsDeleted = 0
		and (d.IsPR = 1 or exists (select 1 from #DepartmentsBudgetAllocations dba where dba.DepartmentID = d.DepartmentID))
		and TimeClassID = 2
		and TimeClassID <> 20
		and (@fiscalYearID = 0 or pp.FiscalYearIDSecond = @fiscalYearID)
		and ((data.UnitTypeID = 51 and pc.IsHoursIgnored = 0) or (data.UnitTypeID = 34 and pc.IsDollarsIgnored = 0))
	group by
		data.DepartmentID,		
		data.JobCodeID,
		data.PayCodeID,
		pc.PayCodeGroupID,
		data.EmployeeID,
		data.PayPeriodID,
		data.TimeClassID
	
	IF OBJECT_ID('tempdb..#DepartmentsBudgetAllocations') IS NOT NULL  DROP TABLE #DepartmentsBudgetAllocations

	-- BudgetAdjustments Start
	declare @iteration int = 1 
	DECLARE @BudgetReallocationGUID uniqueidentifier,@date datetime,@BudgetReallocationType varchar(50)

	DECLARE BRA_cursor CURSOR FOR   
	SELECT distinct BudgetReallocationGUID,date,BudgetReallocationType from fw.BudgetReallocationWithDefinedType
	WHERE (FiscalYearID = @FiscalYearID or @FiscalYearID = 0) and DataType = 1
	ORDER BY date;  

	OPEN BRA_cursor  

	FETCH NEXT FROM BRA_cursor   
	INTO @BudgetReallocationGUID,@date,@BudgetReallocationType   

	WHILE @@FETCH_STATUS = 0  
	BEGIN  

		
		BEGIN
		INSERT INTO #PayrollPayPeriodTempTable(DepartmentID, JobCodeID, EmployeeID, PayCodeID, PayCodeGroupID, PayPeriodID, TimeClassID, Hours, Dollars)
			SELECT TargetDepartmentID as DepartmentID,TargetJobCodeID as JobCodeID, stt.EmployeeID, stt.PayCodeID, stt.PayCodeGroupID, stt.PayPeriodID, stt.TimeClassID, 
			HOURS = STT.Hours*pptm.DaysinPeriodWeight,
			Dollars = STT.Dollars*pptm.DaysinPeriodWeight
			FROM #PayrollSampledPayPeriodDetailedPreStaging STT
			inner join #PayPeriodsToMonths pptm on pptm.PayPeriodID = stt.PayPeriodID 
			INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceJobCodeID = stt.JobCodeID and b.FiscalYearID = pptm.FiscalYearID
			INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and pptm.FiscalMonthID = ba.FiscalMonthID
			where 
				b.BudgetReallocationGUID = @BudgetReallocationGUID
				and TimeClassID = 2
				and DataType = 1
				and Archived = 0
			UNION
			SELECT SourceDepartmentID as DepartmentID,SourceJobCodeID as JobCodeID, stt.EmployeeID, stt.PayCodeID, stt.PayCodeGroupID, stt.PayPeriodID, stt.TimeClassID, 
			HOURS = -STT.Hours*pptm.DaysinPeriodWeight,
			Dollars = -STT.Dollars*pptm.DaysinPeriodWeight
			FROM #PayrollSampledPayPeriodDetailedPreStaging STT
			inner join #PayPeriodsToMonths pptm on pptm.PayPeriodID = stt.PayPeriodID 
			INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceJobCodeID = stt.JobCodeID and b.FiscalYearID = pptm.FiscalYearID
			INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and pptm.FiscalMonthID = ba.FiscalMonthID
			where 
				b.BudgetReallocationGUID = @BudgetReallocationGUID
				and TimeClassID = 2
				and DataType = 1
				and Archived = 0
	
		END

		set @iteration  = @iteration +1

		FETCH NEXT FROM BRA_cursor   
		INTO @BudgetReallocationGUID,@date,@BudgetReallocationType   
	END   
	CLOSE BRA_cursor;  
	DEALLOCATE BRA_cursor;  
	-- BudgetAdjustments END
	--SplittingMonthsToPayPeriod
	--insert into #PayrollSampledPayPeriodDetailedStaging (DepartmentID, JobCodeID,PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, TimeClassID, Hours, Dollars)
	--SELECT fact.DepartmentID, JobCodeID,PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, TimeClassID, Hours*PeriodWeight, Dollars*PeriodWeight FROM #PayrollSampledMonthlyDetailedStaging fact
	--INNER JOIN fw.DimDepartment dd on fact.DepartmentID = dd.DepartmentID
	--INNER JOIN #PayPeriodsToMonths PP ON PP.FiscalYearID = fact.FiscalYearID
	--	AND pp.FiscalMonthID = fact.FiscalMonthID
	--	and pp.PayCycleID = dd.PayCycleID

	IF OBJECT_ID('tempdb..#PayPeriodsToMonths') IS NOT NULL  DROP TABLE #PayPeriodsToMonths
	
INSERT INTO #PayrollSampledPayPeriodDetailedStaging (DepartmentID, JobCodeID,PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, TimeClassID,Hours,Dollars)
SELECT 	DepartmentID,JobCodeID,PayCodeID,PayCodeGroupID,EmployeeID,PayPeriodID,TimeClassID,Hours,Dollars
FROM #PayrollPayPeriodTempTable

IF OBJECT_ID('tempdb..#PayrollPayPeriodTempTable') IS NOT NULL  DROP TABLE #PayrollPayPeriodTempTable

insert into #PayrollSampledPayPeriodDetailedStaging (DepartmentID, JobCodeID,PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, TimeClassID, Hours, Dollars)
select
	data.DepartmentID,		
	data.JobCodeID,
	data.PayCodeID,
	pc.PayCodeGroupID,
	data.EmployeeID,
	data.PayPeriodID,
	data.TimeClassID,
	sum(case when data.UnitTypeID = 51 then data.Value else 0 end) as Hours, 
	sum(case when data.UnitTypeID = 34 then data.Value else 0 end) as Dollars
from
	int.FactStaffingByPayPeriod data
        inner join [fw].[DimJobCode] jc on data.JobCodeID = jc.JobCodeID and IsPR = 1	
	inner join [fw].[DimPayCode] pc on data.PayCodeID=pc.PayCodeID
	inner join [fw].[DimPayPeriod] pp on data.PayPeriodID = pp.PayPeriodID
	inner join [fw].[DimDepartment] d on d.DepartmentID = data.DepartmentID
where
	data.PayPeriodID != 0
	and data.IsDeleted = 0
	and d.IsPR = 1
	and TimeClassID <> 20
	and (@fiscalYearID = 0 or pp.FiscalYearIDSecond = @fiscalYearID)
	and ((data.UnitTypeID = 51 and pc.IsHoursIgnored = 0) or (data.UnitTypeID = 34 and pc.IsDollarsIgnored = 0))
group by
	data.DepartmentID,
	data.JobCodeID,
	data.PayCodeID,
	pc.PayCodeGroupID,
	data.EmployeeID,
	data.PayPeriodID,
	data.TimeClassID

	--pull new data - adjustments
	DECLARE @NonProdGroupID INT = (
		SELECT TOP 1 pcg.PayCodeGroupID
		FROM fw.DimProductiveClass pc
		INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID
		WHERE pc.Name = 'Non-Productive' AND pcg.PayCodeGroupID != 0
		ORDER BY pcg.SortOrder)

	DECLARE @ProdGroupID INT = (
		SELECT TOP 1 pcg.PayCodeGroupID
		FROM fw.DimProductiveClass pc
		INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID
		WHERE pc.Name = 'Productive' AND pcg.PayCodeGroupID != 0
		ORDER BY pcg.SortOrder)

	DECLARE @NonProdPayCodeID INT = (
		SELECT TOP 1 pcg.DefaultPayCodeID
		FROM fw.DimProductiveClass pc
		INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID
		WHERE pc.Name = 'Non-Productive' AND pcg.PayCodeGroupID != 0
		ORDER BY pcg.SortOrder)

	DECLARE @ProdPayCodeID INT = (
		SELECT TOP 1 pcg.DefaultPayCodeID
		FROM fw.DimProductiveClass pc
		INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID
		WHERE pc.Name = 'Productive' AND pcg.PayCodeGroupID != 0
		ORDER BY pcg.SortOrder)

	INSERT INTO #PayrollSampledPayPeriodDetailedStaging (DepartmentID, JobCodeID,PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, TimeClassID, Hours, Dollars)
	SELECT 
		Adj.DepartmentID,
		Adj.JobCodeID,
		Adj.PayCodeId,
		Adj.PayCodeGroupID,
		0 as EmployeeID,
		PP.PayPeriodID,
		2 AS TimeClassID, -- always Budgeted
		sum(Adj.Hours * PP.PreriodWeight) AS Hours,
		0 AS Dollars
	FROM (
		SELECT 
			b.DepartmentID,
			b.JobCodeID,
			@ProdPayCodeID as PayCodeID,
			@ProdGroupID AS PayCodeGroupID,
			b.FiscalYearID,
			ba.FiscalMonthID,
			ba.ProductiveChange AS Hours
		FROM mr.BudgetPayrollReallocationAdjustment ba
		INNER JOIN mr.BudgetPayrollReallocation b ON b.BudgetPayrollReallocationGUID = ba.BudgetPayrollReallocationGUID
		LEFT JOIN 
		(select SourceDepartmentID as DepartmentID,
			 SourceJobCodeID as JobCodeID,
			 FiscalYearID,
			 FiscalMonthID
		FROM [mr].[BudgetReallocation] b
		INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		WHERE DataType = 1
		UNION ALL
		select TargetDepartmentID as DepartmentID,
			 TargetJobCodeID as JobCodeID,
			 FiscalYearID,
			 FiscalMonthID
		FROM [mr].[BudgetReallocation] b
		INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		WHERE DataType = 1
		) fact on fact.DepartmentID = b.DepartmentID and fact.JobCodeID = b.JobCodeID and fact.FiscalYearID = b.FiscalYearID and fact.FiscalMonthID = ba.FiscalMonthID
		WHERE (@fiscalYearID = 0 or b.FiscalYearID = @fiscalYearID) and fact.DepartmentID is null and b.Archived = 0
		UNION ALL
		SELECT b.DepartmentID,
			b.JobCodeID,
			@NonProdPayCodeID as PayCodeID,
			@NonProdGroupID AS PayCodeGroupID,
			b.FiscalYearID,
			ba.FiscalMonthID,
			ba.NonProductiveChange AS Hours
		FROM mr.BudgetPayrollReallocationAdjustment ba
		INNER JOIN mr.BudgetPayrollReallocation b ON b.BudgetPayrollReallocationGUID = ba.BudgetPayrollReallocationGUID
		LEFT JOIN 
		(select SourceDepartmentID as DepartmentID,
			 SourceJobCodeID as JobCodeID,
			 FiscalYearID,
			 FiscalMonthID
		FROM [mr].[BudgetReallocation] b
		INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		WHERE DataType = 1
		UNION ALL
		select TargetDepartmentID as DepartmentID,
			 TargetJobCodeID as JobCodeID,
			 FiscalYearID,
			 FiscalMonthID
		FROM [mr].[BudgetReallocation] b
		INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		WHERE DataType = 1
		) fact on fact.DepartmentID = b.DepartmentID and fact.JobCodeID = b.JobCodeID and fact.FiscalYearID = b.FiscalYearID and fact.FiscalMonthID = ba.FiscalMonthID
		WHERE (@fiscalYearID = 0 or b.FiscalYearID = @fiscalYearID) and fact.DepartmentID is null and b.Archived = 0
		) AS Adj
        INNER JOIN fw.DimJobCode jc ON jc.JobCodeID = Adj.JobCodeID and jc.IsPR = 1
	INNER JOIN fw.DimDepartment dd on adj.DepartmentID = dd.DepartmentID and dd.IsPR = 1
	INNER JOIN (
		SELECT 
			[PayPeriodID],
			PayCycleID,
			[PeriodNumber],
			[FiscalMonthIDStart] AS FiscalMonthID,
			[FiscalYearIDStart] AS FiscalYearID,
			[PeriodWeightStart] AS PreriodWeight
		FROM [fw].[DimPayPeriod]
		WHERE (@fiscalYearID = 0 or [FiscalYearIDSecond] = @fiscalYearID)
		UNION ALL
		SELECT 
			[PayPeriodID],
			PayCycleID,
			[PeriodNumber],
			FiscalMonthIDSecond AS FiscalMonthID,
			FiscalYearIDSecond AS FiscalYearID,
			PeriodWeightSecond AS PreriodWeight
		FROM [fw].[DimPayPeriod]
		WHERE (@fiscalYearID = 0 or [FiscalYearIDSecond] = @fiscalYearID)
		) PP ON PP.FiscalYearID = Adj.FiscalYearID
		AND pp.FiscalMonthID = adj.FiscalMonthID
		and pp.PayCycleID = dd.PayCycleID
	GROUP BY Adj.DepartmentID,
		Adj.JobCodeID,
		Adj.PayCodeID,
		Adj.PayCodeGroupID,
		PP.PayPeriodID

	--run calculations on staging table 
	exec fw.procFactPayPeriodMergeDuplicates '#PayrollSampledPayPeriodDetailedStaging', 'JobCodeID,PayCodeID,PayCodeGroupID, EmployeeID', 'Dollars,Hours', @fiscalYearID, 0, 0, @departmentIDs
	exec fw.procFactPayrollSampledPayPeriodDetailedBaselineTargetUpdate @departmentIDs = @departmentIDs, @fiscalYearID = @fiscalYearID
	exec fw.procFactPayPeriodYTDPriorYearUpdate_Staging 'fw.FactPayrollSampledPayPeriodDetailed','#PayrollSampledPayPeriodDetailedStaging', 'JobCodeID,PayCodeID,PayCodeGroupID, EmployeeID', 'Dollars,Hours', @fiscalYearID, 0, 0

	IF OBJECT_ID('tempdb..#PayrollSampledPayPeriodDetailedFTEs') IS NOT NULL  DROP TABLE #PayrollSampledPayPeriodDetailedFTEs
	CREATE TABLE #PayrollSampledPayPeriodDetailedFTEs (DepartmentID int,JobCodeID int,PayCodeID int,PayCodeGroupID int,EmployeeID int,PayPeriodID int,TimeClassID int, FTEs decimal(18, 6), FTEsYTD decimal(18, 6), FTEsPriorYear decimal(18, 6), FTEsPriorYTD decimal(18, 6))
	exec client.procFactPayrollSampledPayPeriodDetailedFTEsInsert_Staging @departmentIDs = @departmentIDs, @fiscalYearID = @fiscalYearID
	
	--!!!Removing all records where Department is not PR
	delete fact
	from fw.PayrollSampledPayPeriodDetailedStagingWithCalcs fact
	inner join fw.dimDepartment d on d.DepartmentID = fact.DepartmentID and d.isPR = 0
	
	IF @fiscalYearID = 0 and @departmentIDs is null
	BEGIN
		DECLARE @BatchSize INT = 50000000
		
-- Split data into batches
	IF OBJECT_ID('tempdb..#inputPayPeriods') IS NOT NULL DROP TABLE #inputPayPeriods
 
	CREATE TABLE #inputPayPeriods (PayPeriodID INT, RecordsCount INT, BatchID INT)
	INSERT INTO #inputPayPeriods
	EXEC dbo.procGetInputDataByBatches
	  	@batchSize = @batchSize,
		@columnName = 'PayPeriodID',
		@tableAlias = 'ps',
		@fromClause = 'fw.PayrollSampledPayPeriodDetailedStagingWithCalcs ps',
		@whereClause = '',
		@isDebug = 0

	DECLARE @BatchID INT, @MaxBatchID INT
	SELECT @MaxBatchID = MAX(BatchID) FROM #inputPayPeriods

	truncate table fw.FactPayrollSampledPayPeriodDetailed

	IF @MaxBatchID >= 2
	BEGIN
		CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.PayrollSampledPayPeriodDetailedStagingWithCalcs (PayPeriodID,DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID,TimeClassID)
	END

	-- Loop thru batches and update data
	SET @BatchID = 1
	WHILE @BatchID <= @MaxBatchID
	BEGIN  			
		INSERT INTO fw.FactPayrollSampledPayPeriodDetailed With (TABLOCKX) (
				DepartmentID,
				PayPeriodID,
				JobCodeID,
				PayCodeID,
				PayCodeGroupID,
				EmployeeID,
				TimeClassID,
				Dollars,
				DollarsYTD,
				DollarsPriorYear,
				DollarsPriorYTD,
				Hours,
				HoursYTD,
				HoursPriorYear,
				HoursPriorYTD,
				FTEs,
				FTEsYTD,
				FTEsPriorYear,
				FTEsPriorYTD,
				IsDeleted,
				IsSystemGenerated)

			SELECT fw.DepartmentID,
			fw.PayPeriodID,
			fw.JobCodeID,
			fw.PayCodeID,
			fw.PayCodeGroupID,
			fw.EmployeeID,
			fw.TimeClassID,
			fw.Dollars,
			fw.DollarsYTD,
			fw.DollarsPriorYear,
			fw.DollarsPriorYTD,
			fw.Hours,
			fw.HoursYTD,
			fw.HoursPriorYear,
			fw.HoursPriorYTD,
			isnull(fte.FTEs,0) as FTEs,
			isnull(fte.FTEsYTD,0) as FTEsYTD,
			isnull(fte.FTEsPriorYear,0) as FTEsPriorYear,
			isnull(fte.FTEsPriorYTD,0) as FTEsPriorYTD,
			0 as IsDeleted,
			isnull(fw.IsSystemGenerated,0) as IsSystemGenerated
		FROM fw.PayrollSampledPayPeriodDetailedStagingWithCalcs fw
			inner join [fw].[DimJobCode] jc on fw.JobCodeID = jc.JobCodeID and IsPR = 1
			left join #PayrollSampledPayPeriodDetailedFTEs fte on fw.DepartmentID = fte.DepartmentID AND fw.JobCodeID = fte.JobCodeID AND	fw.PayCodeID = fte.PayCodeID AND fw.PayCodeGroupID = fte.PayCodeGroupID AND fw.EmployeeID = fte.EmployeeID AND fw.PayPeriodID = fte.PayPeriodID AND fw.TimeClassID = fte.TimeClassID
			INNER JOIN #inputPayPeriods IPP ON IPP.PayPeriodID = fw.PayPeriodID
			WHERE IPP.BatchID = @BatchID
  
		SET @BatchID = @BatchID + 1
	END
	END
		ELSE 
	BEGIN
		CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.PayrollSampledPayPeriodDetailedStagingWithCalcs (DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID,PayPeriodID,TimeClassID)
		BEGIN TRANSACTION Sampling
		BEGIN TRY 
		WITH TGT AS (SELECT t.* FROM 
		fw.FactPayrollSampledPayPeriodDetailed t With (TABLOCKX)
		inner join #PayPeriodIDs ppt on t.PayPeriodID = ppt.PayPeriodID
		)
		MERGE 
		TGT AS target
		USING  
			(select 
			fw.DepartmentID,
			fw.PayPeriodID,
			fw.JobCodeID,
			fw.PayCodeID,
			fw.PayCodeGroupID,
			fw.EmployeeID,
			fw.TimeClassID,
			fw.Dollars,
			fw.DollarsYTD,
			fw.DollarsPriorYear,
			fw.DollarsPriorYTD,
			fw.Hours,
			fw.HoursYTD,
			fw.HoursPriorYear,
			fw.HoursPriorYTD,
			isnull(fte.FTEs,0) as FTEs,
			isnull(fte.FTEsYTD,0) as FTEsYTD,
			isnull(fte.FTEsPriorYear,0) as FTEsPriorYear,
			isnull(fte.FTEsPriorYTD,0) as FTEsPriorYTD,
			0 as IsDeleted,
			isnull(fw.IsSystemGenerated,0) as IsSystemGenerated
			from fw.PayrollSampledPayPeriodDetailedStagingWithCalcs fw
					left join #PayrollSampledPayPeriodDetailedFTEs fte on fw.DepartmentID = fte.DepartmentID AND fw.JobCodeID = fte.JobCodeID AND	fw.PayCodeID = fte.PayCodeID AND fw.PayCodeGroupID = fte.PayCodeGroupID AND fw.EmployeeID = fte.EmployeeID AND fw.PayPeriodID = fte.PayPeriodID AND fw.TimeClassID = fte.TimeClassID
			) AS source
			ON source.DepartmentID = target.DepartmentID
				AND source.JobCodeID = target.JobCodeID
				AND source.EmployeeID = target.EmployeeID
				AND source.PayCodeID = target.PayCodeID
				AND source.PayCodeGroupID = target.PayCodeGroupID
				AND source.PayPeriodID = target.PayPeriodID
				AND source.TimeClassID = target.TimeClassID
				AND source.PayCodeID = target.PayCodeID
		WHEN MATCHED AND 
			(target.Dollars <> source.Dollars
			or target.DollarsYTD <> source.DollarsYTD
			or target.DollarsPriorYear <> source.DollarsPriorYear
			or target.DollarsPriorYTD <> source.DollarsPriorYTD
			or target.Hours <> source.Hours
			or target.HoursYTD <> source.HoursYTD
			or target.HoursPriorYear <> source.HoursPriorYear
			or target.HoursPriorYTD <> source.HoursPriorYTD
			or target.FTEs <> source.FTEs
			or target.FTEsYTD <> source.FTEsYTD
			or target.FTEsPriorYear <> source.FTEsPriorYear
			or target.FTEsPriorYTD <> source.FTEsPriorYTD
			or target.isSystemGenerated <> source.isSystemGenerated)
			THEN
				UPDATE
				SET target.Dollars = source.Dollars,
					target.DollarsYTD = source.DollarsYTD,
					target.DollarsPriorYear = source.DollarsPriorYear,
					target.DollarsPriorYTD = source.DollarsPriorYTD,
					target.Hours = source.Hours,
					target.HoursYTD = source.HoursYTD,
					target.HoursPriorYear = source.HoursPriorYear,
					target.HoursPriorYTD = source.HoursPriorYTD,
					target.FTEs = source.FTEs,
					target.FTEsYTD = source.FTEsYTD,
					target.FTEsPriorYear = source.FTEsPriorYear,
					target.FTEsPriorYTD = source.FTEsPriorYTD,
					target.isSystemGenerated = source.isSystemGenerated
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					DepartmentID,
					PayPeriodID,
					JobCodeID,
					PayCodeID,
					PayCodeGroupID,
					EmployeeID,
					TimeClassID,
					Dollars,
					DollarsYTD,
					DollarsPriorYear,
					DollarsPriorYTD,
					Hours,
					HoursYTD,
					HoursPriorYear,
					HoursPriorYTD,
					FTEs,
					FTEsYTD,
					FTEsPriorYear,
					FTEsPriorYTD,
					IsDeleted,
					IsSystemGenerated
					)
				VALUES (
					source.DepartmentID,
					source.PayPeriodID,
					source.JobCodeID,
					source.PayCodeID,
					source.PayCodeGroupID,
					source.EmployeeID,
					source.TimeClassID,
					source.Dollars,
					source.DollarsYTD,
					source.DollarsPriorYear,
					source.DollarsPriorYTD,
					source.Hours,
					source.HoursYTD,
					source.HoursPriorYear,
					source.HoursPriorYTD,
					source.FTEs,
					source.FTEsYTD,
					source.FTEsPriorYear,
					source.FTEsPriorYTD,
					0,
					isnull(IsSystemGenerated,0)
					)
		WHEN NOT MATCHED BY SOURCE
			THEN
				DELETE;

		COMMIT TRANSACTION Sampling
		END TRY
		BEGIN CATCH 
			ROLLBACK TRANSACTION Sampling;
			THROW
		END CATCH
	END

	IF OBJECT_ID('tempdb..#PayrollSampledPayPeriodDetailedStaging') IS NOT NULL  DROP TABLE #PayrollSampledPayPeriodDetailedStaging
	IF OBJECT_ID('fw.PayrollSampledPayPeriodDetailedStagingWithCalcs') IS NOT NULL  DROP TABLE fw.PayrollSampledPayPeriodDetailedStagingWithCalcs
	IF OBJECT_ID('tempdb..#PayrollSampledMonthlyDetailedStaging') IS NOT NULL  DROP TABLE #PayrollSampledMonthlyDetailedStaging
	IF OBJECT_ID('tempdb..#PayrollSampledMonthlyDetailedPreStaging') IS NOT NULL  DROP TABLE #PayrollSampledMonthlyDetailedPreStaging
	IF OBJECT_ID('tempdb..#PayPeriodIDs') IS NOT NULL  DROP TABLE #PayPeriodIDs
GO


---------------------------------------------

-- fw.procPayrollSampledPayPeriodInsert
/**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2013-09-19	AKK		64193		Changing source table to be int.FactStaffingByPayPeriod
** 2		2013-10-03	RA					Updating proc to include db setting options
** 3		2014-06-24	JG		B-02536		Updating Pay Code to be Pay Code Group
** 4		2014-09-03	MS		B-02863		Removing the parameter from the YTD proc call
** 5		2014-11-23  JG					Removing Flexing Piece
** 6		2015-02-19	JG					Removing differential and non-fte pay code hours from the data
** 7		2015-04-20	MS					Adding differential and non-fte pay code hours back. These hours are excluded from standard in pi.procCalculateProductivityMetrics and should be handled in report mappings.
** 8		2015-10-28	MJS		D-03587		Added logic to exclude ignored hours and dollars
** 9		2016-02-29	MJS		D-04023		Removed update of default payperiod
** 10		2016-04-28	AK		B-11864		Added IsPR check
** 11		2016-10-04	MH		B-13126		Added procFactPayrollSampledPayPeriodBaselineTargetUpdate
** 12		2017-01-31	AK		B-13926		Added department filter
** 13		2017-02-08	GF		B-14308		Added year filter
** 14		2017-02-20	GF		D-05545		Move duplicate record handling from YTD into sampling
** 15		2017-02-20  GF		D-05613		Prevent zero rows
** 16		2017-02-23	IP		B-14063		Added functionality of adding rows with adjustment values to fw.FactPayrollSampledPayPeriod
** 17		2017-02-23	IP		TK-39445	Fixed bug with incorrect accounting payperiod which belongs to 2 fiscal years
** 18		2017-03-08	GF		B-14693		Fix adjustment records year filter handling
** 19       2017-03-30  IP      B-15085     Performace optimization by aggregating "detailed" data
** 20       2017-04-11  IP      D-05763     Replaced hardcoded value hours in pay period from 80.00 to (DimPayPeriod.WorkingDays * 8.0)
** 21		2017-05-29 	ipetriv	B-15994		Refactored sampling process and implemented using of staging tables
** 22		2017-06-15	IP		B-15086 	Modify SP to use unique temp table
** 23		2017-07-11	IP		D-06152 	Fixed conditions of merge statement (update part)
** 24		2017-10-04 	GF		D-06489		Fix pay period select when running all years
** 25		2018-02-02 	GF		TK-53716	Re-enable calculation of FTEs for non-standart work Weeks
** 26		2019-08-19	vfay	D-08311		PR Sampling Proc : removed filtering out 0 Value Rows
** 27		2021-02-18	KF		JAZZ-15158	Variable Productive Hours - Detailed Target Spread
** 28		2022-03-11	HV		JAZZ-27781	Run PR Process Task can fail silently during Payroll Sampling
** 29		2023-12-04	ishah		JAZZ-62485	Remove @departmentIDs param for procFactPayPeriodYTDPriorYearUpdate_AG
*************************************************************/
CREATE proc [fw].[procPayrollSampledPayPeriodInsert] 
	@departmentIDs nvarchar(max) = null,
	@fiscalYearID int = 0,
	@useTargetOverrides bit = 0
as

	IF OBJECT_ID('tempdb..#PayrollSampledPayPeriodStaging') IS NOT NULL  DROP TABLE #PayrollSampledPayPeriodStaging
	IF OBJECT_ID('fw.PayrollSampledPayPeriodStagingWithCalcs') IS NOT NULL  DROP TABLE fw.PayrollSampledPayPeriodStagingWithCalcs

	declare @departments table(val int primary key)
	insert into @departments select val from ConvertCSValuesToTable(@departmentIDs, ',')

	declare @payperiods table(val smallint primary key)
	insert into @payperiods select PayPeriodID from fw.DimPayPeriod where FiscalYearIDSecond = @fiscalYearID or @fiscalYearID = 0

	--run custom scripts
	exec [client].[procPayrollSampledInsertPreprocess]

/*If Target basis is rolling average then we can't calculate baseline as simple sum of detailed table.
 in his case we should
	1)insert summed values for all timeclasses except baseline (TimeClassId  = 20)
	2)recalculate baseline 
	3)run stored procedure to update columns YTD, priorYear etc.
*/

SELECT DepartmentID,
	JobCodeID,
	WorkingHoursCoef = cast(dww.Hours AS NUMERIC(20, 6)) / 7
INTO #WorkWeekHours
FROM (
	SELECT DepartmentID,
		JobCodeID,
		WorkWeekID = COALESCE(jc.WorkWeekID, de.WorkWeekID, - 1)
	FROM (
		SELECT dp.DepartmentID,
			WorkWeekID = CASE 
				WHEN e.WorkWeekID > - 1
					THEN e.WorkWeekID
				ELSE NULL
				END
		FROM fw.DimEntity e
		INNER JOIN fw.DimDepartment dp on e.EntityID = dp.EntityID
		) DE
	CROSS JOIN (
		SELECT djc.JobCodeID,
			djcg.JobCodeGroupID,
			WorkWeekID = CASE 
				WHEN djc.WorkWeekOverrideID > - 1
					THEN djc.WorkWeekOverrideID
				WHEN djc.WorkWeekOverrideID = - 1
					AND djcg.WorkWeekOverrideID > - 1
					THEN djcg.WorkWeekOverrideID
				ELSE NULL
				END
		FROM fw.DimJobCode djc
		INNER JOIN fw.DimJobCodeGroup djcg
			ON djc.JobCodeGroupID = djcg.JobCodeGroupID
		) JC
	) DeptJobCode
LEFT JOIN fw.DimWorkWeek dww
	ON DeptJobCode.WorkWeekID = dww.WorkWeekID


DECLARE @IsRollingAverage BIT
SELECT @IsRollingAverage = CASE WHEN Value = 10 THEN 1 ELSE 0 END from pi.SystemSetting where Name = 'Target Basis'

IF (@IsRollingAverage = 1 OR @useTargetOverrides = 1)
BEGIN
  CREATE TABLE #TimeClasses (TimeClassID tinyint Primary Key)
  INSERT INTO #TimeClasses (TimeClassID) VALUES (1), (2)
  IF(@IsRollingAverage = 0)
  BEGIN
    INSERT INTO #TimeClasses (TimeClassID) VALUES (20)
  END

  SELECT fact.DepartmentID,
	fact.JobCodeID,
	fact.PayPeriodID,
	fact.TimeClassID,
	fact.PayCodeGroupID,
	fact.IsSystemGenerated,
	fact.Hours,
	fact.HoursYTD,
	fact.HoursPriorYear,
	fact.HoursPriorYTD,
	fact.Dollars,
	fact.DollarsYTD,
	fact.DollarsPriorYear,
	fact.DollarsPriorYTD,
	FTEs = isnull(CASE 
			WHEN pcg.ProductiveClassID IN ('3','2')	AND pp.PeriodNumber != 0
				THEN CASE 
						WHEN WorkingHoursCoef IS NOT NULL
							THEN (cast(fact.Hours AS NUMERIC(20, 6)) / cast(PeriodDays AS NUMERIC(20, 6))) -- fact hours per calendar day 
								/ WorkingHoursCoef
						ELSE fact.Hours / (WorkingDays * 8.0)
						END
			END, 0),
	FTEsYTD = isnull(CASE 
			WHEN pcg.ProductiveClassID IN ('3','2')	AND pp.PeriodNumber != 0
				THEN CASE 
						WHEN WorkingHoursCoef IS NOT NULL
							THEN (cast(fact.HoursYTD AS NUMERIC(20, 6)) / (cast(PeriodDays AS NUMERIC(20, 6)) * cast(pp.PeriodNumber AS NUMERIC(20, 6)))) -- YTD hours / YTD days 
								/ WorkingHoursCoef
						ELSE fact.HoursYTD / (WorkingDays * 8.0 * pp.PeriodNumber)
						END
			END, 0),
	FTEsPriorYear = isnull(CASE 
			WHEN pcg.ProductiveClassID IN ('3','2')	AND pp.PeriodNumber != 0
				THEN CASE 
						WHEN WorkingHoursCoef IS NOT NULL
							THEN (cast(fact.HoursPriorYear AS NUMERIC(20, 6)) / cast(PeriodDays AS NUMERIC(20, 6))) -- fact hours for Prior Year per calendar day 
								/ WorkingHoursCoef
						ELSE fact.HoursPriorYear / (WorkingDays * 8.0)
						END
			END, 0),
	FTEsPriorYTD = isnull(CASE 
			WHEN pcg.ProductiveClassID IN ('3','2')	AND pp.PeriodNumber != 0
				THEN CASE 
						WHEN WorkingHoursCoef IS NOT NULL
							THEN (cast(fact.HoursPriorYTD AS NUMERIC(20, 6)) / (cast(PeriodDays AS NUMERIC(20, 6)) * cast(pp.PeriodNumber AS NUMERIC(20, 6)))) -- YTD for PY hours / YTD days 
								/ WorkingHoursCoef
						ELSE fact.HoursPriorYTD / (WorkingDays * 8.0 * pp.PeriodNumber)
						END
			END, 0)
  INTO #PayrollSampledPayPeriodStaging
  FROM (
	SELECT d.DepartmentID,
		d.JobCodeID,
		d.PayCodeGroupID,
		d.PayPeriodID,
		d.TimeClassID,
		sum(d.Hours) AS Hours,
		sum(d.HoursYTD) AS HoursYTD,
		sum(d.HoursPriorYear) AS HoursPriorYear,
		sum(d.HoursPriorYTD) AS HoursPriorYTD,
		sum(d.Dollars) AS Dollars,
		sum(d.DollarsYTD) AS DollarsYTD,
		sum(d.DollarsPriorYear) AS DollarsPriorYear,
		sum(d.DollarsPriorYTD) AS DollarsPriorYTD,
		IsSystemGenerated = min(cast(IsSystemGenerated AS TINYINT))
    FROM fw.FactPayrollSampledPayPeriodDetailed d
    INNER JOIN [fw].[DimPayPeriod] pp ON d.PayPeriodID = pp.PayPeriodID
	INNER JOIN #TimeClasses TC ON TC.TimeClassID = d.TimeClassID
    WHERE (@departmentIDs IS NULL OR d.DepartmentID IN (SELECT val	FROM @departments))
		AND (@fiscalYearID = 0 OR pp.FiscalYearIDSecond = @fiscalYearID)
	GROUP BY d.DepartmentID,
		d.JobCodeID,
		d.PayCodeGroupID,
		d.PayPeriodID,
		d.TimeClassID
  ) fact
  LEFT JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID = fact.PayPeriodID
  LEFT JOIN [fw].[DimPayCodeGroup] pcg ON fact.PayCodeGroupID = pcg.PayCodeGroupID
  LEFT JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID AND ww.JobCodeID = fact.JobCodeID
  
  IF(@IsRollingAverage = 1) exec fw.procFactPayrollSampledPayPeriodBaselineTargetUpdate @departmentIDs = @departmentIDs, @fiscalYearID = @fiscalYearID -- recalculate baseline 
  
  IF(@useTargetOverrides = 1) exec fw.procFactPayrollSampledPayPeriodBaselineTargetOverridesUpdate
  
  exec fw.procFactPayPeriodYTDPriorYearUpdate_AG 'fw.FactPayrollSampledPayPeriod','#PayrollSampledPayPeriodStaging','JobCodeID,PayCodeGroupID', 'Dollars,Hours,FTEs', @fiscalYearID, 20, 0 -- recalculate for baseline rows
  exec client.procFactPayrollSampledPayPeriodFTEsInsert_Staging @departmentIDs = @departmentIDs, @fiscalYearID = @fiscalYearID

  IF @fiscalYearID = 0 and @departmentIDs is null
	BEGIN
	truncate table fw.FactPayrollSampledPayPeriod
	INSERT INTO fw.FactPayrollSampledPayPeriod With (TABLOCKX) (
			DepartmentID,
			PayPeriodID,
			JobCodeID,
			PayCodeGroupID,
			TimeClassID,
			Dollars,
			DollarsYTD,
			DollarsPriorYear,
			DollarsPriorYTD,
			Hours,
			HoursYTD,
			HoursPriorYear,
			HoursPriorYTD,
			FTEs,
			FTEsYTD,
			FTEsPriorYear,
			FTEsPriorYTD,
			IsDeleted,
			IsSystemGenerated)

		SELECT DepartmentID,
		PayPeriodID,
		JobCodeID,
		PayCodeGroupID,
		TimeClassID,
		Dollars,
		DollarsYTD,
		DollarsPriorYear,
		DollarsPriorYTD,
		Hours,
		HoursYTD,
		HoursPriorYear,
		HoursPriorYTD,
		FTEs,
		FTEsYTD,
		FTEsPriorYear,
		FTEsPriorYTD,
		0 as IsDeleted,
		isnull(IsSystemGenerated,0) as IsSystemGenerated
	FROM fw.PayrollSampledPayPeriodStagingWithCalcs
	END
  ELSE 
	BEGIN
		print 'Starting creating index --- '+convert(varchar(20),GETDATE(),113) 
		CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.PayrollSampledPayPeriodStagingWithCalcs (DepartmentID,JobCodeID,PayCodeGroupID,PayPeriodID,TimeClassID)
		print 'Starting transaction --- '+convert(varchar(20),GETDATE(),113) 
		BEGIN TRANSACTION Sampling
		BEGIN TRY 
		WITH TGT AS (SELECT t.* FROM 
		fw.FactPayrollSampledPayPeriod t With (TABLOCKX)
		inner join fw.DimPayPeriod pp on t.PayPeriodId  = pp.PayPeriodID
		where (@fiscalYearID = 0 or t.PayPeriodID in(select val from @payperiods))
		and (@departmentIDs is null or DepartmentID in(select val from @departments))
		)
		MERGE 
		TGT AS target
		USING fw.PayrollSampledPayPeriodStagingWithCalcs AS source
			ON source.DepartmentID = target.DepartmentID
				AND source.JobCodeID = target.JobCodeID
				AND source.PayCodeGroupID = target.PayCodeGroupID
				AND source.PayPeriodID = target.PayPeriodID
				AND source.TimeClassID = target.TimeClassID
		WHEN MATCHED AND (
			target.Dollars <> source.Dollars
			or target.DollarsYTD <> source.DollarsYTD
			or target.DollarsPriorYear <> source.DollarsPriorYear
			or target.DollarsPriorYTD <> source.DollarsPriorYTD
			or target.Hours <> source.Hours
			or target.HoursYTD <> source.HoursYTD
			or target.HoursPriorYear <> source.HoursPriorYear
			or target.HoursPriorYTD <> source.HoursPriorYTD
			or target.FTEs <> source.FTEs
			or target.FTEsYTD <> source.FTEsYTD
			or target.FTEsPriorYear <> source.FTEsPriorYear
			or target.FTEsPriorYTD <> source.FTEsPriorYTD
			or target.isSystemGenerated <> source.isSystemGenerated)
			THEN
				UPDATE
				SET target.Dollars = source.Dollars,
					target.DollarsYTD = source.DollarsYTD,
					target.DollarsPriorYear = source.DollarsPriorYear,
					target.DollarsPriorYTD = source.DollarsPriorYTD,
					target.Hours = source.Hours,
					target.HoursYTD = source.HoursYTD,
					target.HoursPriorYear = source.HoursPriorYear,
					target.HoursPriorYTD = source.HoursPriorYTD,
					target.FTEs = source.FTEs,
					target.FTEsYTD = source.FTEsYTD,
					target.FTEsPriorYear = source.FTEsPriorYear,
					target.FTEsPriorYTD = source.FTEsPriorYTD,
					target.isSystemGenerated = source.isSystemGenerated
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					DepartmentID,
					PayPeriodID,
					JobCodeID,
					PayCodeGroupID,
					TimeClassID,
					Dollars,
					DollarsYTD,
					DollarsPriorYear,
					DollarsPriorYTD,
					Hours,
					HoursYTD,
					HoursPriorYear,
					HoursPriorYTD,
					FTEs,
					FTEsYTD,
					FTEsPriorYear,
					FTEsPriorYTD,
					IsDeleted,
					IsSystemGenerated
					)
				VALUES (
					source.DepartmentID,
					source.PayPeriodID,
					source.JobCodeID,
					source.PayCodeGroupID,
					source.TimeClassID,
					source.Dollars,
					source.DollarsYTD,
					source.DollarsPriorYear,
					source.DollarsPriorYTD,
					source.Hours,
					source.HoursYTD,
					source.HoursPriorYear,
					source.HoursPriorYTD,
					source.FTEs,
					source.FTEsYTD,
					source.FTEsPriorYear,
					source.FTEsPriorYTD,
					0,
					isnull(IsSystemGenerated,0)
					)
		WHEN NOT MATCHED BY SOURCE
			THEN
				DELETE;

		COMMIT TRANSACTION Sampling
		END TRY
		BEGIN CATCH 
			ROLLBACK TRANSACTION Sampling;
			THROW
		END CATCH
  END

END
ELSE /*Here is  inserting aggregated rows in case when "Target Basis" is not rolling average and @useTargetOverrides = 0*/
BEGIN 	
  IF @fiscalYearID = 0 and @departmentIDs is null 
	BEGIN 
	truncate table fw.FactPayrollSampledPayPeriod 
	insert into fw.FactPayrollSampledPayPeriod (
			DepartmentID,
			JobCodeID,
			PayPeriodID,
			TimeClassID,
			PayCodeGroupID,
			IsSystemGenerated,
			Hours,
			HoursYTD,
			HoursPriorYear,
			HoursPriorYTD,
			Dollars,
			DollarsYTD,
			DollarsPriorYear,
			DollarsPriorYTD,
			FTEs,
			FTEsYTD,
			FTEsPriorYear,
			FTEsPriorYTD
		)
		SELECT fact.DepartmentID,
			fact.JobCodeID,
			fact.PayPeriodID,
			fact.TimeClassID,
			fact.PayCodeGroupID,
			fact.IsSystemGenerated,
			fact.Hours,
			fact.HoursYTD,
			fact.HoursPriorYear,
			fact.HoursPriorYTD,
			fact.Dollars,
			fact.DollarsYTD,
			fact.DollarsPriorYear,
			fact.DollarsPriorYTD,
			FTEs = isnull(CASE WHEN pcg.ProductiveClassID IN ('3','2')	AND pp.PeriodNumber != 0
						THEN CASE 
								WHEN WorkingHoursCoef IS NOT NULL
									THEN (cast(fact.Hours AS NUMERIC(20, 6)) / cast(PeriodDays AS NUMERIC(20, 6))) -- fact hours per calendar day 
										/ WorkingHoursCoef
								ELSE fact.Hours / (WorkingDays * 8.0)
								END
					END, 0),
			FTEsYTD = isnull(CASE WHEN pcg.ProductiveClassID IN ('3','2')	AND pp.PeriodNumber != 0
						THEN CASE 
								WHEN WorkingHoursCoef IS NOT NULL
									THEN (cast(fact.HoursYTD AS NUMERIC(20, 6)) / (cast(PeriodDays AS NUMERIC(20, 6)) * cast(pp.PeriodNumber AS NUMERIC(20, 6)))) -- YTD hours / YTD days 
										/ WorkingHoursCoef
								ELSE fact.HoursYTD / (WorkingDays * 8.0 * pp.PeriodNumber)
								END
					END, 0),
			FTEsPriorYear = isnull(CASE WHEN pcg.ProductiveClassID IN ('3','2')	AND pp.PeriodNumber != 0
						THEN CASE 
								WHEN WorkingHoursCoef IS NOT NULL
									THEN (cast(fact.HoursPriorYear AS NUMERIC(20, 6)) / cast(PeriodDays AS NUMERIC(20, 6))) -- fact hours for Prior Year per calendar day 
										/ WorkingHoursCoef
								ELSE fact.HoursPriorYear / (WorkingDays * 8.0)
								END
					END, 0),
			FTEsPriorYTD = isnull(CASE WHEN pcg.ProductiveClassID IN ('3','2')	AND pp.PeriodNumber != 0
						THEN CASE 
								WHEN WorkingHoursCoef IS NOT NULL
									THEN (cast(fact.HoursPriorYTD AS NUMERIC(20, 6)) / (cast(PeriodDays AS NUMERIC(20, 6)) * cast(pp.PeriodNumber AS NUMERIC(20, 6)))) -- YTD for PY hours / YTD days 
										/ WorkingHoursCoef
								ELSE fact.HoursPriorYTD / (WorkingDays * 8.0 * pp.PeriodNumber)
								END
					END, 0)
		FROM (
			SELECT
				d.DepartmentID,
				d.JobCodeID,
				d.PayCodeGroupID,
				d.PayPeriodID,
				d.TimeClassID,
				sum(d.Hours) AS Hours,
				sum(d.HoursYTD) AS HoursYTD,
				sum(d.HoursPriorYear) AS HoursPriorYear,
				sum(d.HoursPriorYTD) AS HoursPriorYTD,
				sum(d.Dollars) AS Dollars,
				sum(d.DollarsYTD) AS DollarsYTD,
				sum(d.DollarsPriorYear) AS DollarsPriorYear,
				sum(d.DollarsPriorYTD) AS DollarsPriorYTD,
				IsSystemGenerated = min(cast(IsSystemGenerated as tinyint))
			FROM fw.FactPayrollSampledPayPeriodDetailed d
			INNER JOIN [fw].[DimPayPeriod] pp on d.PayPeriodID = pp.PayPeriodID
			WHERE (@departmentIDs is null or d.DepartmentID in(select val from @departments))
			and (@fiscalYearID = 0 or pp.FiscalYearIDSecond = @fiscalYearID)
			GROUP BY
				d.DepartmentID,
				d.JobCodeID,
				d.PayCodeGroupID,
				d.PayPeriodID,
				d.TimeClassID
		) fact
		left join [fw].[DimPayPeriod] pp on pp.PayPeriodID=fact.PayPeriodID
		left join [fw].[DimPayCodeGroup] pcg on fact.PayCodeGroupID = pcg.PayCodeGroupID
		left join #WorkWeekHours ww on ww.DepartmentID = fact.DepartmentID and ww.JobCodeID = fact.JobCodeID		
	END
  ELSE 
		WITH TGT AS (SELECT t.* FROM 
		fw.FactPayrollSampledPayPeriod t With (TABLOCKX)
		inner join fw.DimPayPeriod pp on t.PayPeriodId  = pp.PayPeriodID
		where (@fiscalYearID = 0 or t.PayPeriodID in(select val from @payperiods))
		and (@departmentIDs is null or DepartmentID in(select val from @departments))
		)
		MERGE 
		TGT AS target
		USING (
				SELECT fact.DepartmentID,
					fact.JobCodeID,
					fact.PayPeriodID,
					fact.TimeClassID,
					fact.PayCodeGroupID,
					fact.IsSystemGenerated,
					fact.Hours,
					fact.HoursYTD,
					fact.HoursPriorYear,
					fact.HoursPriorYTD,
					fact.Dollars,
					fact.DollarsYTD,
					fact.DollarsPriorYear,
					fact.DollarsPriorYTD,
					FTEs = isnull(CASE WHEN pcg.ProductiveClassID IN ('3','2')	AND pp.PeriodNumber != 0
								THEN CASE 
										WHEN WorkingHoursCoef IS NOT NULL
											THEN (cast(fact.Hours AS NUMERIC(20, 6)) / cast(PeriodDays AS NUMERIC(20, 6))) -- fact hours per calendar day 
												/ WorkingHoursCoef
										ELSE fact.Hours / (WorkingDays * 8.0)
										END
							END, 0),
					FTEsYTD = isnull(CASE WHEN pcg.ProductiveClassID IN ('3','2')	AND pp.PeriodNumber != 0
								THEN CASE 
										WHEN WorkingHoursCoef IS NOT NULL
											THEN (cast(fact.HoursYTD AS NUMERIC(20, 6)) / (cast(PeriodDays AS NUMERIC(20, 6)) * cast(pp.PeriodNumber AS NUMERIC(20, 6)))) -- YTD hours / YTD days 
												/ WorkingHoursCoef
										ELSE fact.HoursYTD / (WorkingDays * 8.0 * pp.PeriodNumber)
										END
							END, 0),
					FTEsPriorYear = isnull(CASE WHEN pcg.ProductiveClassID IN ('3','2')	AND pp.PeriodNumber != 0
								THEN CASE 
										WHEN WorkingHoursCoef IS NOT NULL
											THEN (cast(fact.HoursPriorYear AS NUMERIC(20, 6)) / cast(PeriodDays AS NUMERIC(20, 6))) -- fact hours for Prior Year per calendar day 
												/ WorkingHoursCoef
										ELSE fact.HoursPriorYear / (WorkingDays * 8.0)
										END
							END, 0),
					FTEsPriorYTD = isnull(CASE WHEN pcg.ProductiveClassID IN ('3','2')	AND pp.PeriodNumber != 0
								THEN CASE 
										WHEN WorkingHoursCoef IS NOT NULL
											THEN (cast(fact.HoursPriorYTD AS NUMERIC(20, 6)) / (cast(PeriodDays AS NUMERIC(20, 6)) * cast(pp.PeriodNumber AS NUMERIC(20, 6)))) -- YTD for PY hours / YTD days 
												/ WorkingHoursCoef
										ELSE fact.HoursPriorYTD / (WorkingDays * 8.0 * pp.PeriodNumber)
										END
							END, 0)
				FROM (
					SELECT
						d.DepartmentID,
						d.JobCodeID,
						d.PayCodeGroupID,
						d.PayPeriodID,
						d.TimeClassID,
						sum(d.Hours) AS Hours,
						sum(d.HoursYTD) AS HoursYTD,
						sum(d.HoursPriorYear) AS HoursPriorYear,
						sum(d.HoursPriorYTD) AS HoursPriorYTD,
						sum(d.Dollars) AS Dollars,
						sum(d.DollarsYTD) AS DollarsYTD,
						sum(d.DollarsPriorYear) AS DollarsPriorYear,
						sum(d.DollarsPriorYTD) AS DollarsPriorYTD,
						IsSystemGenerated = min(cast(IsSystemGenerated as tinyint))
					FROM fw.FactPayrollSampledPayPeriodDetailed d
					INNER JOIN [fw].[DimPayPeriod] pp on d.PayPeriodID = pp.PayPeriodID
					WHERE (@departmentIDs is null or d.DepartmentID in(select val from @departments))
					and (@fiscalYearID = 0 or pp.FiscalYearIDSecond = @fiscalYearID)
					GROUP BY
						d.DepartmentID,
						d.JobCodeID,
						d.PayCodeGroupID,
						d.PayPeriodID,
						d.TimeClassID
				) fact
				left join [fw].[DimPayPeriod] pp on pp.PayPeriodID=fact.PayPeriodID
				left join [fw].[DimPayCodeGroup] pcg on fact.PayCodeGroupID = pcg.PayCodeGroupID
				left join #WorkWeekHours ww on ww.DepartmentID = fact.DepartmentID and ww.JobCodeID = fact.JobCodeID				
		) AS source
			ON source.DepartmentID = target.DepartmentID
				AND source.JobCodeID = target.JobCodeID
				AND source.PayCodeGroupID = target.PayCodeGroupID
				AND source.PayPeriodID = target.PayPeriodID
				AND source.TimeClassID = target.TimeClassID
		WHEN MATCHED AND ( 
			target.Dollars <> source.Dollars
			or target.DollarsYTD <> source.DollarsYTD
			or target.DollarsPriorYear <> source.DollarsPriorYear
			or target.DollarsPriorYTD <> source.DollarsPriorYTD
			or target.Hours <> source.Hours
			or target.HoursYTD <> source.HoursYTD
			or target.HoursPriorYear <> source.HoursPriorYear
			or target.HoursPriorYTD <> source.HoursPriorYTD
			or target.FTEs <> source.FTEs
			or target.FTEsYTD <> source.FTEsYTD
			or target.FTEsPriorYear <> source.FTEsPriorYear
			or target.FTEsPriorYTD <> source.FTEsPriorYTD
			or target.isSystemGenerated <> source.isSystemGenerated)
			THEN
				UPDATE
				SET target.Dollars = source.Dollars,
					target.DollarsYTD = source.DollarsYTD,
					target.DollarsPriorYear = source.DollarsPriorYear,
					target.DollarsPriorYTD = source.DollarsPriorYTD,
					target.Hours = source.Hours,
					target.HoursYTD = source.HoursYTD,
					target.HoursPriorYear = source.HoursPriorYear,
					target.HoursPriorYTD = source.HoursPriorYTD,
					target.FTEs = source.FTEs,
					target.FTEsYTD = source.FTEsYTD,
					target.FTEsPriorYear = source.FTEsPriorYear,
					target.FTEsPriorYTD = source.FTEsPriorYTD,
					target.isSystemGenerated = source.isSystemGenerated
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					DepartmentID,
					PayPeriodID,
					JobCodeID,
					PayCodeGroupID,
					TimeClassID,
					Dollars,
					DollarsYTD,
					DollarsPriorYear,
					DollarsPriorYTD,
					Hours,
					HoursYTD,
					HoursPriorYear,
					HoursPriorYTD,
					FTEs,
					FTEsYTD,
					FTEsPriorYear,
					FTEsPriorYTD,
					IsDeleted,
					IsSystemGenerated
					)
				VALUES (
					source.DepartmentID,
					source.PayPeriodID,
					source.JobCodeID,
					source.PayCodeGroupID,
					source.TimeClassID,
					source.Dollars,
					source.DollarsYTD,
					source.DollarsPriorYear,
					source.DollarsPriorYTD,
					source.Hours,
					source.HoursYTD,
					source.HoursPriorYear,
					source.HoursPriorYTD,
					source.FTEs,
					source.FTEsYTD,
					source.FTEsPriorYear,
					source.FTEsPriorYTD,
					0,
					isnull(IsSystemGenerated,0)
					)
		WHEN NOT MATCHED BY SOURCE
			THEN
				DELETE;
END
GO


---------------------------------------------

-- fw.procPlanTypeCreateMaintenanceCustomScriptStub
CREATE proc [fw].[procPlanTypeCreateMaintenanceCustomScriptStub] 
	@schema sysname,
	@plantypename nvarchar(100)
as

declare @ptguid uniqueidentifier
select @ptguid = plantypeguid from PlanType where Name = @plantypename

if @ptguid is null begin
	print 'invalid plantype name'
	return
end

declare @cs1guid uniqueidentifier
declare @cs2guid uniqueidentifier
declare @cnt int

select
	@cs1guid = cs.CustomScriptGUID,
	@cs2guid = cs2.CustomScriptGUID,
	@cnt = case when coalesce(cs.name,cs2.name) = @plantypename + ' Maintenance' then 1 else 0 end 
from
	PlanType pt
	left join CustomScript cs on pt.OnSaveCustomScriptGUID = cs.CustomScriptGUID
	left join CustomScript cs2 on pt.OnSaveCustomScript2GUID = cs2.CustomScriptGUID
where
	pt.PlanTypeGUID = @ptguid
	
if @cnt > 0 begin
	print 'maintenance script already exists'
	return
end

if not @cs1guid is null and not @cs2guid is null begin
	print 'no onsave slots left'
	return
end

declare @sql nvarchar(max)
set @sql = '
create proc [' + @schema + '].[proc' + replace(@plantypename, ' ','') +  'Maintenance]
	@planguid uniqueidentifier
as

	--do plan maintenance here
'
exec (@sql)

declare @scriptguid uniqueidentifier
set @scriptguid = NEWID()

insert into CustomScript ( CustomScriptGUID,Name, ScriptText, IsSynchronous)
values (@scriptguid,@plantypename + ' Maintenance', 'exec [' + @schema + '].[proc' + replace(@plantypename, ' ','') +  'Maintenance] @planGuidList',1)

if @cs1guid is null begin
	update PlanType set OnSaveCustomScriptGUID = @scriptguid where plantypeguid = @ptguid
end else begin	
	update PlanType set OnSaveCustomScript2GUID = @scriptguid where plantypeguid = @ptguid
end

set @sql = '
alter proc [' + @schema + '].[proc' + replace(@plantypename, ' ','') +  'Maintenance]
	@planguid uniqueidentifier
as

	--do plan maintenance here
go
'

print @sql
GO


---------------------------------------------

-- fw.procPostDiMergeEncounterBasedStatistics
CREATE   PROC fw.procPostDiMergeEncounterBasedStatistics
  @statisticId int,
  @year int,
  @months SqlInt32ListTableType READONLY
AS
BEGIN
  SET NOCOUNT ON

    CREATE TABLE #detailsToMerge
  (
  RowID bigint identity(1,1),
  DateID int,
  DepartmentID int,
  AccountID int,
  Value decimal(19, 4)
  )
  CREATE CLUSTERED INDEX CNU_RowId ON #detailsToMerge(RowId)

  INSERT #detailsToMerge (DepartmentID, AccountID, DateID, Value)
  SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, SUM(ebs.Value)
  FROM fw.FactEncounterBasedStatistics ebs
  JOIN fw.DimDate d ON ebs.DateID = d.DateID
  JOIN @months m ON d.CalendarMonth = m.value
  WHERE ebs.StatisticID = @statisticId 
    AND d.FiscalYear = @year
  GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.DateID

  CREATE TABLE #batch
  (
  DateID int,
  DepartmentID int,
  AccountID int,
  Value decimal(19, 4)
  )

  DECLARE
  @startRowId bigint,
  @maxRowId bigint,
  @endRowId bigint

  SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId)
  FROM #detailsToMerge

  WHILE (@startRowId <= @maxRowId)
  BEGIN
    SELECT @endRowId = MAX(d.RowId)
    FROM (SELECT TOP 1000000 RowId
          FROM #detailsToMerge
          WHERE RowId >= @startRowId
          ORDER BY RowID) as d

    TRUNCATE TABLE #batch

    INSERT #batch (DepartmentID, AccountID, DateID, Value)
    SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, ebs.Value
    FROM #detailsToMerge ebs
    WHERE ebs.RowId >= @startRowId
      AND ebs.RowId <= @endRowId

    UPDATE fw.FactChargeBasedStatistics
    SET Value = ebs.Value
    FROM fw.FactChargeBasedStatistics cbs
      JOIN #batch ebs
        ON cbs.DepartmentID = ebs.DepartmentID
          AND cbs.AccountID = ebs.AccountID
          AND cbs.DateID = ebs.DateID

    INSERT fw.FactChargeBasedStatistics (DepartmentID, AccountID, DateID, Value)
    SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, ebs.Value
    FROM #batch ebs
    WHERE NOT EXISTS
      (
        SELECT cbs.RowID
        FROM fw.FactChargeBasedStatistics cbs
        WHERE ebs.DepartmentID = cbs.DepartmentID
          AND ebs.AccountID = cbs.AccountID
          AND ebs.DateID = cbs.DateID
      )

    SELECT @startRowId = MIN(d.RowId)
    FROM #detailsToMerge d
    WHERE RowId > @endRowId
  END

  DROP TABLE IF EXISTS #detailsToMerge
  DROP TABLE IF EXISTS #batch
END
GO


---------------------------------------------

-- fw.procPostDiMergeEncounterBasedStatisticsMonthly
CREATE   PROC fw.procPostDiMergeEncounterBasedStatisticsMonthly
  @statisticId int,
  @year int,
  @months SqlInt32ListTableType READONLY
AS
BEGIN
  SET NOCOUNT ON

  DROP TABLE IF EXISTS #detailsToMerge

  CREATE TABLE #detailsToMerge
  (
  FiscalYearID smallint,
  FiscalMonthID tinyint,
  DepartmentID int,
  AccountID int,
  Value decimal(19, 4)
  )

  INSERT #detailsToMerge (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value)
  SELECT ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID, ebs.Value
  FROM fw.FactEncounterBasedStatisticsMonthly ebs
  JOIN @months s ON ebs.FiscalMonthID = s.value
  WHERE ebs.FiscalYearID = @year
    AND ebs.StatisticID = @statisticId

  UPDATE #detailsToMerge
  SET Value = aggr.AggregatedValue
  FROM
  (
    SELECT ebs.FiscalYearID, ebs.FiscalMonthID, ebs.DepartmentID, ebs.AccountID, SUM(ebs.Value) AS AggregatedValue
    FROM #detailsToMerge d
      JOIN fw.FactEncounterBasedStatisticsMonthly ebs
        ON ebs.DepartmentID = d.DepartmentID
          AND ebs.AccountID = d.AccountID
          AND ebs.FiscalYearID = d.FiscalYearID
          AND ebs.FiscalMonthID = d.FiscalMonthID
    GROUP BY ebs.FiscalYearID, ebs.FiscalMonthID, ebs.DepartmentID, ebs.AccountID
    ) aggr
    JOIN #detailsToMerge det
      ON aggr.DepartmentID = det.DepartmentID
          AND aggr.AccountID = det.AccountID
          AND aggr.FiscalYearID = det.FiscalYearID
          AND aggr.FiscalMonthID = det.FiscalMonthID

  UPDATE fw.FactChargeBasedStatisticsMonthly
  SET Value = ebs.Value
  FROM #detailsToMerge ebs
    JOIN fw.FactChargeBasedStatisticsMonthly cbs
      ON ebs.DepartmentID = cbs.DepartmentID
        AND ebs.AccountID = cbs.AccountID
        AND ebs.FiscalYearID = cbs.FiscalYearID
        AND ebs.FiscalMonthID = cbs.FiscalMonthID

  INSERT fw.FactChargeBasedStatisticsMonthly (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value)
  SELECT ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID, ebs.Value
  FROM #detailsToMerge ebs
  WHERE NOT EXISTS
    (
      SELECT cbs.RowID
      FROM fw.FactChargeBasedStatisticsMonthly cbs
      WHERE ebs.DepartmentID = cbs.DepartmentID
        AND ebs.AccountID = cbs.AccountID
        AND ebs.FiscalYearID = cbs.FiscalYearID
        AND ebs.FiscalMonthID = cbs.FiscalMonthID
    )
END
GO


---------------------------------------------

-- fw.procPostDiMergeEncounterBasedStatisticsMonthlyOpt
CREATE   PROC fw.procPostDiMergeEncounterBasedStatisticsMonthlyOpt
AS
BEGIN
  SET NOCOUNT ON

  DROP TABLE IF EXISTS #detailsToMerge

  CREATE TABLE #detailsToMerge
  (
  FiscalYearID smallint,
  FiscalMonthID tinyint,
  DepartmentID int,
  AccountID int,
  Value decimal(19, 4)
  )

  INSERT #detailsToMerge (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value)
  SELECT ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID, ebs.Value
  FROM fw.FactEncounterBasedStatisticsMonthly ebs
    JOIN data.EbsPostDiCacheMonthly c
      ON ebs.StatisticID = c.StatisticID
        AND ebs.FiscalYearID = c.Year
        AND ebs.FiscalMonthID = c.Month

  UPDATE #detailsToMerge
  SET Value = aggr.AggregatedValue
  FROM
  (
    SELECT ebs.FiscalYearID, ebs.FiscalMonthID, ebs.DepartmentID, ebs.AccountID, SUM(ebs.Value) AS AggregatedValue
    FROM #detailsToMerge d
      JOIN fw.FactEncounterBasedStatisticsMonthly ebs
        ON ebs.DepartmentID = d.DepartmentID
          AND ebs.AccountID = d.AccountID
          AND ebs.FiscalYearID = d.FiscalYearID
          AND ebs.FiscalMonthID = d.FiscalMonthID
    GROUP BY ebs.FiscalYearID, ebs.FiscalMonthID, ebs.DepartmentID, ebs.AccountID
    ) aggr
    JOIN #detailsToMerge det
      ON aggr.DepartmentID = det.DepartmentID
          AND aggr.AccountID = det.AccountID
          AND aggr.FiscalYearID = det.FiscalYearID
          AND aggr.FiscalMonthID = det.FiscalMonthID

  UPDATE fw.FactChargeBasedStatisticsMonthly
  SET Value = ebs.Value
  FROM #detailsToMerge ebs
    JOIN fw.FactChargeBasedStatisticsMonthly cbs
      ON ebs.DepartmentID = cbs.DepartmentID
        AND ebs.AccountID = cbs.AccountID
        AND ebs.FiscalYearID = cbs.FiscalYearID
        AND ebs.FiscalMonthID = cbs.FiscalMonthID

  INSERT fw.FactChargeBasedStatisticsMonthly (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value)
  SELECT ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID, ebs.Value
  FROM #detailsToMerge ebs
  WHERE NOT EXISTS
    (
      SELECT cbs.RowID
      FROM fw.FactChargeBasedStatisticsMonthly cbs
      WHERE ebs.DepartmentID = cbs.DepartmentID
        AND ebs.AccountID = cbs.AccountID
        AND ebs.FiscalYearID = cbs.FiscalYearID
        AND ebs.FiscalMonthID = cbs.FiscalMonthID
    )
END
GO


---------------------------------------------

-- fw.procPostDiMergeEncounterBasedStatisticsOpt
CREATE   PROC fw.procPostDiMergeEncounterBasedStatisticsOpt
AS
BEGIN
  SET NOCOUNT ON

    CREATE TABLE #detailsToMerge
  (
  RowID bigint identity(1,1),
  DateID int,
  DepartmentID int,
  AccountID int,
  Value decimal(19, 4)
  )
  CREATE CLUSTERED INDEX CNU_RowId ON #detailsToMerge(RowId)

  INSERT #detailsToMerge (DepartmentID, AccountID, DateID, Value)
  SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, SUM(ebs.Value)
  FROM fw.FactEncounterBasedStatistics ebs
  JOIN fw.DimDate d ON ebs.DateID = d.DateID
  JOIN data.EbsPostDiCache c
    ON ebs.StatisticID = c.StatisticID
      AND d.FiscalYear = c.Year
      AND d.CalendarMonth = c.Month
  GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.DateID

  CREATE TABLE #batch
  (
  DateID int,
  DepartmentID int,
  AccountID int,
  Value decimal(19, 4)
  )

  DECLARE
  @startRowId bigint,
  @maxRowId bigint,
  @endRowId bigint

  SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId)
  FROM #detailsToMerge

  WHILE (@startRowId <= @maxRowId)
  BEGIN
    SELECT @endRowId = MAX(d.RowId)
    FROM (SELECT TOP 1000000 RowId
          FROM #detailsToMerge
          WHERE RowId >= @startRowId
          ORDER BY RowID) as d

    TRUNCATE TABLE #batch

    INSERT #batch (DepartmentID, AccountID, DateID, Value)
    SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, ebs.Value
    FROM #detailsToMerge ebs
    WHERE ebs.RowId >= @startRowId
      AND ebs.RowId <= @endRowId

    UPDATE fw.FactChargeBasedStatistics
    SET Value = ebs.Value
    FROM fw.FactChargeBasedStatistics cbs
      JOIN #batch ebs
        ON cbs.DepartmentID = ebs.DepartmentID
          AND cbs.AccountID = ebs.AccountID
          AND cbs.DateID = ebs.DateID

    INSERT fw.FactChargeBasedStatistics (DepartmentID, AccountID, DateID, Value)
    SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, ebs.Value
    FROM #batch ebs
    WHERE NOT EXISTS
      (
        SELECT cbs.RowID
        FROM fw.FactChargeBasedStatistics cbs
        WHERE ebs.DepartmentID = cbs.DepartmentID
          AND ebs.AccountID = cbs.AccountID
          AND ebs.DateID = cbs.DateID
      )

    SELECT @startRowId = MIN(d.RowId)
    FROM #detailsToMerge d
    WHERE RowId > @endRowId
  END

  DROP TABLE IF EXISTS #detailsToMerge
  DROP TABLE IF EXISTS #batch
END
GO


---------------------------------------------

-- fw.procPostDiRestoreChargeBasedStatistics
CREATE   PROC fw.procPostDiRestoreChargeBasedStatistics
  @statisticId int,
  @year int,
  @months SqlInt32ListTableType READONLY
AS
BEGIN
  SET NOCOUNT ON

  CREATE TABLE #detailsToRestore
  (
  RowID bigint identity(1,1),
  DateID int,
  DepartmentID int,
  AccountID int
  )
  CREATE CLUSTERED INDEX CNU_RowId ON #detailsToRestore(RowId)

  INSERT #detailsToRestore (DepartmentID, AccountID, DateID)
  SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID
  FROM fw.FactEncounterBasedStatistics ebs
  JOIN fw.DimDate d ON ebs.DateID = d.DateID
  JOIN @months m ON d.CalendarMonth = m.value
  WHERE ebs.StatisticID = @statisticId 
    AND d.FiscalYear = @year
  GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.DateID

  DECLARE
  @startRowId bigint,
  @maxRowId bigint,
  @endRowId bigint

  SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId)
  FROM #detailsToRestore

  WHILE (@startRowId <= @maxRowId)
  BEGIN
    SELECT @endRowId = MAX(d.RowId)
    FROM (SELECT TOP 1000000 RowId
          FROM #detailsToRestore
          WHERE RowId >= @startRowId
          ORDER BY RowID) as d

    DELETE cbs
    FROM fw.FactChargeBasedStatistics cbs
      JOIN #detailsToRestore ebs
        ON cbs.DepartmentID = ebs.DepartmentID
          AND cbs.AccountID = ebs.AccountID
          AND cbs.DateID = ebs.DateID
    WHERE ebs.RowId >= @startRowId
      AND ebs.RowId <= @endRowId

    INSERT fw.FactChargeBasedStatistics (DepartmentID, AccountID, DateID, Value)
    SELECT sgs.DepartmentID, sgs.AccountID, sgs.DateID, AVG(sgs.Value)
    FROM fw.FactSystemGeneratedStatistics sgs
      JOIN #detailsToRestore ebs
        ON sgs.DepartmentID = ebs.DepartmentID
          AND sgs.AccountID = ebs.AccountID
          AND sgs.DateID = ebs.DateID
    WHERE ebs.RowId >= @startRowId
      AND ebs.RowId <= @endRowId
    GROUP BY sgs.DepartmentID, sgs.AccountID, sgs.DateID

    SELECT @startRowId = MIN(d.RowId)
    FROM #detailsToRestore d
    WHERE RowId > @endRowId
  END

  DROP TABLE IF EXISTS #detailsToRestore
END
GO


---------------------------------------------

-- fw.procPostDiRestoreChargeBasedStatisticsMonthly
CREATE   PROC fw.procPostDiRestoreChargeBasedStatisticsMonthly
  @statisticId int,
  @year int,
  @months SqlInt32ListTableType READONLY
AS
BEGIN
  SET NOCOUNT ON

  DELETE cbs
  FROM fw.FactEncounterBasedStatisticsMonthly ebs
  JOIN @months m ON ebs.FiscalMonthID = m.value
  JOIN fw.FactChargeBasedStatisticsMonthly cbs
    ON ebs.DepartmentID = cbs.DepartmentID
    AND ebs.AccountID = cbs.AccountID
    AND ebs.FiscalYearID = cbs.FiscalYearID
    AND ebs.FiscalMonthID = cbs.FiscalMonthID
  WHERE ebs.FiscalYearID = @year
    AND ebs.StatisticID = @statisticId

  INSERT fw.FactChargeBasedStatisticsMonthly (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value)
  SELECT sgs.DepartmentID, sgs.AccountID, sgs.FiscalYearID, sgs.FiscalMonthID, AVG(sgs.Value)
  FROM fw.FactEncounterBasedStatisticsMonthly ebs
  JOIN @months m ON ebs.FiscalMonthID = m.value
  JOIN fw.FactSystemGeneratedStatisticsMonthly sgs
    ON ebs.DepartmentID = sgs.DepartmentID
    AND ebs.AccountID = sgs.AccountID
    AND ebs.FiscalYearID = sgs.FiscalYearID
    AND ebs.FiscalMonthID = sgs.FiscalMonthID
  WHERE ebs.FiscalYearID = @year
    AND ebs.StatisticID = @statisticId
  GROUP BY sgs.DepartmentID, sgs.AccountID, sgs.FiscalYearID, sgs.FiscalMonthID
END
GO


---------------------------------------------

-- fw.procPostDiRestoreChargeBasedStatisticsMonthlyOpt
CREATE   PROC fw.procPostDiRestoreChargeBasedStatisticsMonthlyOpt
AS
BEGIN
  SET NOCOUNT ON

  DELETE cbs
  FROM fw.FactEncounterBasedStatisticsMonthly ebs
    JOIN data.EbsPostDiCacheMonthly c
      ON ebs.StatisticID = c.StatisticID
        AND ebs.FiscalYearID = c.Year
        AND ebs.FiscalMonthID = c.Month
   JOIN fw.FactChargeBasedStatisticsMonthly cbs
      ON ebs.DepartmentID = cbs.DepartmentID
      AND ebs.AccountID = cbs.AccountID
      AND ebs.FiscalYearID = cbs.FiscalYearID
      AND ebs.FiscalMonthID = cbs.FiscalMonthID

  INSERT fw.FactChargeBasedStatisticsMonthly (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value)
  SELECT sgs.DepartmentID, sgs.AccountID, sgs.FiscalYearID, sgs.FiscalMonthID, AVG(sgs.Value)
  FROM fw.FactEncounterBasedStatisticsMonthly ebs
   JOIN data.EbsPostDiCacheMonthly c
      ON ebs.StatisticID = c.StatisticID
        AND ebs.FiscalYearID = c.Year
        AND ebs.FiscalMonthID = c.Month
    JOIN fw.FactSystemGeneratedStatisticsMonthly sgs
      ON ebs.DepartmentID = sgs.DepartmentID
      AND ebs.AccountID = sgs.AccountID
      AND ebs.FiscalYearID = sgs.FiscalYearID
      AND ebs.FiscalMonthID = sgs.FiscalMonthID
  GROUP BY sgs.DepartmentID, sgs.AccountID, sgs.FiscalYearID, sgs.FiscalMonthID
END
GO


---------------------------------------------

-- fw.procPostDiRestoreChargeBasedStatisticsOpt
CREATE   PROC fw.procPostDiRestoreChargeBasedStatisticsOpt
AS
BEGIN
  SET NOCOUNT ON

  CREATE TABLE #detailsToRestore
  (
  RowID bigint identity(1,1),
  DateID int,
  DepartmentID int,
  AccountID int
  )
  CREATE CLUSTERED INDEX CNU_RowId ON #detailsToRestore(RowId)

  INSERT #detailsToRestore (DepartmentID, AccountID, DateID)
  SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID
  FROM fw.FactEncounterBasedStatistics ebs
    JOIN fw.DimDate d ON ebs.DateID = d.DateID
    JOIN data.EbsPostDiCache c
      ON ebs.StatisticID = c.StatisticID
        AND d.FiscalYear = c.Year
        AND d.CalendarMonth = c.Month
  GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.DateID

  DECLARE
  @startRowId bigint,
  @maxRowId bigint,
  @endRowId bigint

  SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId)
  FROM #detailsToRestore

  WHILE (@startRowId <= @maxRowId)
  BEGIN
    SELECT @endRowId = MAX(d.RowId)
    FROM (SELECT TOP 1000000 RowId
          FROM #detailsToRestore
          WHERE RowId >= @startRowId
          ORDER BY RowID) as d

    DELETE cbs
    FROM fw.FactChargeBasedStatistics cbs
      JOIN #detailsToRestore ebs
        ON cbs.DepartmentID = ebs.DepartmentID
          AND cbs.AccountID = ebs.AccountID
          AND cbs.DateID = ebs.DateID
    WHERE ebs.RowId >= @startRowId
      AND ebs.RowId <= @endRowId

    INSERT fw.FactChargeBasedStatistics (DepartmentID, AccountID, DateID, Value)
    SELECT sgs.DepartmentID, sgs.AccountID, sgs.DateID, AVG(sgs.Value)
    FROM fw.FactSystemGeneratedStatistics sgs
      JOIN #detailsToRestore ebs
        ON sgs.DepartmentID = ebs.DepartmentID
          AND sgs.AccountID = ebs.AccountID
          AND sgs.DateID = ebs.DateID
    WHERE ebs.RowId >= @startRowId
      AND ebs.RowId <= @endRowId
    GROUP BY sgs.DepartmentID, sgs.AccountID, sgs.DateID

    SELECT @startRowId = MIN(d.RowId)
    FROM #detailsToRestore d
    WHERE RowId > @endRowId
  END

  DROP TABLE IF EXISTS #detailsToRestore
END
GO


---------------------------------------------

-- fw.procPrepareGL
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2018-03-19	IP		D-06997		Replaced table variable by temp tables 
** 2		2018-05-15	KF		D-07006		Rolling Average method for metric target calculation doesn't include months with 0 values
** 3		2018-05-31	IP		TK-58509	reverting part of migrations for D-07006
** 4		2018-06-04	IP 		TK-58587	re-applying changes  (2018-05-16  D-07187 Budget adjustment effecting historical budget fiscal years)
** 5		2019-09-03	vfay	D-08704		Fix incorrectly adding previous year's data into the current year
** 6		2024-06-04	ishah	JAZZ-61244	[TrLog][High] Bug - Run Management Reporting Monthly Process (MR Sampling, all years run): Task failed on Inserting GL Sampled.
***************************************************************/
----- #FactGLStagingValue with specified columns(DepartmentID int, AccountID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Amount decimal(21,6), ApplyDate datetime, Src varchar(max)) should be created before calling the proc
CREATE PROCEDURE [fw].[procPrepareGL]
	@FiscalYearID int = 0
AS
BEGIN
	DECLARE 
		@iteration INT = 1, 
		@batchSize INT, 
		@applyDateString nvarchar(100) =  '''' + '1900-01-01' + ''''
		
	-- Split by batches
	EXEC mr.procGetIntBatchSize
		@DefaultBatchSize = 30000000,
		@ResultBatchSize = @batchSize OUTPUT

	IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments
	CREATE TABLE #inputDepartments (DepartmentID INT, RecordsCount INT, BatchID INT)
	
	DECLARE @fromClause nvarchar(max) = '
	(
	SELECT
		stat.DepartmentID,
		stat.AccountID,
		stat.FiscalYearID,
		stat.FiscalMonthID,
		stat.TimeClassID
	FROM
		int.FactGL stat  
		inner join fw.DimDepartment D on D.Departmentid = STAT.Departmentid
	WHERE 
		stat.IsDeleted = 0
		and stat.Value != 0
		and (stat.FiscalYearID = ' + cast(@FiscalYearID as nvarchar(100)) + ' or ' + cast(@FiscalYearID as nvarchar(100)) + ' = 0)
	GROUP BY stat.DepartmentID,
		stat.AccountID,
		stat.FiscalYearID,
		stat.FiscalMonthID,
		stat.TimeClassID ) X
	'
	
	INSERT INTO #inputDepartments
	EXEC dbo.procGetInputDataByBatches
	  	@batchSize = @batchSize,
		@columnName = 'DepartmentID',
		@tableAlias = 'X',
		@fromClause = @fromClause,
		@whereClause = '',
		@isDebug = 0
		
	DECLARE @BatchID INT, @MaxBatchID INT
	SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments

	SET @BatchID = 1
	WHILE @BatchID <= @MaxBatchID
	BEGIN
		INSERT INTO #FactGLStagingValue	(DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src)
		SELECT
			stat.DepartmentID,
			stat.AccountID,
			stat.FiscalYearID,
			stat.FiscalMonthID,
			stat.TimeClassID,
			sum(stat.Value) as Amount,
			cast('1900-01-01' as datetime) as ApplyDate,
			cast('int_1' as varchar(max))+'V' as src
		from
			int.FactGL stat  
			inner join fw.DimDepartment D on D.Departmentid = stat.Departmentid
			inner join #inputDepartments ID ON ID.DepartmentID = D.DepartmentID
		where 
			stat.IsDeleted = 0
			and stat.Value != 0
			and ID.BatchID = @BatchID
			and (stat.FiscalYearID = @FiscalYearID or @FiscalYearID = 0)
		Group by stat.DepartmentID,
			stat.AccountID,
			stat.FiscalYearID,
			stat.FiscalMonthID,
			stat.TimeClassID
			
		SET @BatchID = @BatchID + 1	
	END
	
DECLARE @BudgetReallocationGUID uniqueidentifier,@date datetime,@BudgetReallocationType varchar(50)

PRINT '-------- Vendor Products Report --------';  

DECLARE BRA_cursor CURSOR FOR   
SELECT distinct BudgetReallocationGUID,date,BudgetReallocationType from fw.BudgetReallocationWithDefinedType
WHERE (FiscalYearID = @FiscalYearID or @FiscalYearID = 0)
ORDER BY date;  

OPEN BRA_cursor  

FETCH NEXT FROM BRA_cursor   
INTO @BudgetReallocationGUID,@date,@BudgetReallocationType   

WHILE @@FETCH_STATUS = 0  
BEGIN  
	IF @BudgetReallocationType = 'ReallocateSingle'
	BEGIN -- Insert rows with "correcting" values 
		UPDATE STT
		SET Amount = Amount + Change,
		stt.ApplyDate = b.Date,
		src = SRC + '[Added_'+cast(Change as varchar(50))+'_from_'+cast(SourceDepartmentID as varchar(10))+']'
		FROM #FactGLStagingValue STT
		INNER JOIN [mr].[BudgetReallocation] b ON b.TargetDepartmentID = stt.DepartmentID and b.TargetAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID  and stt.FiscalMonthID = ba.FiscalMonthID
		WHERE Change <> 0
			  and b.BudgetReallocationGUID = @BudgetReallocationGUID
			  and UnitTypeID = 34
			  and TimeClassID = 2
			  and b.Archived = 0

		UPDATE STT
		SET Amount = Amount - Change,
		stt.ApplyDate = b.Date,
		src = SRC + '[Removed_'+cast(Change as varchar(50))+'_to_'+cast(TargetDepartmentID as varchar(10))+']'
		FROM #FactGLStagingValue STT
		INNER JOIN [mr].[BudgetReallocation] b ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID  and stt.FiscalMonthID = ba.FiscalMonthID
		WHERE Change <> 0
			  and b.BudgetReallocationGUID = @BudgetReallocationGUID
			  and UnitTypeID = 34
			  and TimeClassID = 2
			  and b.Archived = 0

		INSERT INTO #FactGLStagingValue	(DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src)
		SELECT 
				b.SourceDepartmentID as DepartmentID,
				b.SourceAccountID as AccountID,
				b.FiscalYearID,
				ba.FiscalMonthID,
				2 as TimeclassID,		
				Change * -1 as Value,
				b.Date as ApplyDate,
				'ra_1_m' as src
		FROM [mr].[BudgetReallocation] b
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		LEFT JOIN (select DepartmentID,AccountID,FiscalYearID,FiscalMonthID,max(ApplyDate) as ApplyDate from #FactGLStagingValue where TimeClassID = 2 group by DepartmentID,AccountID,FiscalYearID,FiscalMonthID) STT ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID
		where Change <> 0
				  and b.BudgetReallocationGUID = @BudgetReallocationGUID
				  and stt.DepartmentID is null
				  and UnitTypeID = 34
				  and b.Archived = 0
		UNION All
		SELECT 
				b.TargetDepartmentID as DepartmentID,
				b.TargetAccountID as AccountID,
				b.FiscalYearID,
				ba.FiscalMonthID,
				2 as TimeclassID,
				Change as Value,
				b.Date as ApplyDate,
				'ra_1_p' as src
		FROM [mr].[BudgetReallocation] b
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		LEFT JOIN (select DepartmentID,AccountID,FiscalYearID,FiscalMonthID,max(ApplyDate) as ApplyDate from #FactGLStagingValue where TimeClassID = 2 group by DepartmentID,AccountID,FiscalYearID,FiscalMonthID) STT ON b.TargetDepartmentID = stt.DepartmentID and b.TargetAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID
		where Change <> 0
				  and b.BudgetReallocationGUID = @BudgetReallocationGUID
				  and stt.DepartmentID is null
				  and UnitTypeID = 34
				  and b.Archived = 0
	END
	ELSE
	----------------------
	IF @BudgetReallocationType = 'ReallocateMulti'
	BEGIN

	UPDATE STT
	set 
		STT.Amount = STT.Amount + STT_SRC.Amount,
		STT.ApplyDate = b.[Date],
		STT.Src = stt.Src + '[RealMulti_'+cast(stt_src.Amount as varchar(50))+'_from_'+cast(stt_src.DepartmentID as varchar(10))+']'
	FROM #FactGLStagingValue STT
	INNER JOIN [mr].[BudgetReallocation] b on 
		b.TargetDepartmentID = STT.DepartmentID and 
		b.TargetAccountID = STT.AccountID and
		b.FiscalYearID = STT.FiscalYearID and
		b.[Date] >= STT.ApplyDate
	INNER JOIN [mr].[BudgetReallocationAdjustment] ba on 
		ba.BudgetReallocationGUID = b.BudgetReallocationGUID and 
		ba.FiscalMonthID = STT.FiscalMonthID
	INNER JOIN #FactGLStagingValue STT_SRC on 
		STT_SRC.DepartmentID = b.SourceDepartmentID and 
		STT_SRC.AccountID = b.SourceAccountID and 
		STT_SRC.FiscalYearID = b.FiscalYearID and 
		STT_SRC.FiscalMonthID = ba.FiscalMonthID and 
		STT_SRC.TimeClassID = STT.TimeClassID
	where 
		b.BudgetReallocationGUID = @BudgetReallocationGUID and 
		ba.UnitTypeID = 34 and 
		ba.Change <> 0 and 
		STT.TimeClassID = 2 and
		b.Archived = 0
	
	INSERT INTO #FactGLStagingValue	(DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, ApplyDate, Src)
	SELECT
		b.TargetDepartmentID as DepartmentID,
		b.TargetAccountID as AccountID,
		b.FiscalYearID,
		ba.FiscalMonthID,
		2 as TimeclassID,
		STT_SRC.Amount as Value,
		b.[Date] as ApplyDate,
		'ReallocateMulti' as src
	FROM [mr].[BudgetReallocation] b
	INNER JOIN [mr].[BudgetReallocationAdjustment] ba on 
		b.BudgetReallocationGUID = ba.BudgetReallocationGUID
	INNER JOIN #FactGLStagingValue STT_SRC on 
		STT_SRC.DepartmentID = b.SourceDepartmentID and 
		STT_SRC.AccountID = b.SourceAccountID and 
		STT_SRC.FiscalYearID = b.FiscalYearID and 
		STT_SRC.FiscalMonthID = ba.FiscalMonthID and 
		STT_SRC.TimeClassID = 2
	LEFT JOIN #FactGLStagingValue STT on 
		STT.DepartmentID = b.TargetDepartmentID and 
		STT.AccountID = b.TargetAccountID and 
		STT.FiscalYearID = b.FiscalYearID and 
		STT.FiscalMonthID = ba.FiscalMonthID and 
		STT.TimeClassID = 2
	where 
		stt.DepartmentID is null and 
		ba.Change <> 0 and 
		ba.UnitTypeID = 34 and 
		b.[Date] >= isnull(stt.ApplyDate,'1900-01-01') and 
		b.BudgetReallocationGUID = @BudgetReallocationGUID and
		b.Archived = 0

	UPDATE STT_SRC
	SET 
		STT_SRC.Amount = 0,
		STT_SRC.ApplyDate = b.[Date],
		STT_SRC.Src = stt_src.Src + '[RealMulti_'+cast(stt_src.Amount as varchar(50))+'_to_'+cast(stt.DepartmentID as varchar(10))+']'
	FROM #FactGLStagingValue STT
	INNER JOIN [mr].[BudgetReallocation] b on 
		b.TargetDepartmentID = STT.DepartmentID and 
		b.TargetAccountID = STT.AccountID and
		b.FiscalYearID = STT.FiscalYearID and 
		b.[Date] >= STT.ApplyDate
	INNER JOIN [mr].[BudgetReallocationAdjustment] ba on 
		b.BudgetReallocationGUID = ba.BudgetReallocationGUID and 
		ba.FiscalMonthID = STT.FiscalMonthID
	INNER JOIN #FactGLStagingValue STT_SRC on 
		b.SourceDepartmentID = STT_SRC.DepartmentID and 
		b.SourceAccountID = STT_SRC.AccountID and 
		b.FiscalYearID = STT_SRC.FiscalYearID and 
		ba.FiscalMonthID = STT_SRC.FiscalMonthID and 
		STT_SRC.TimeClassID = 2
	where 
		ba.Change <> 0 and 
		b.BudgetReallocationGUID = @BudgetReallocationGUID and 
		ba.UnitTypeID = 34 and
		b.Archived = 0

	END
	ELSE
	IF @BudgetReallocationType = 'AdjustMontly'
	BEGIN	
		UPDATE STT
		SET 
			stt.Amount = stt.Amount+Change,
			stt.ApplyDate = b.Date,
			stt.Src = stt.Src + '[AdjustMontly_'+cast(Change as varchar(50))+']'
		FROM #FactGLStagingValue STT
		INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and b.Date >= stt.ApplyDate and b.FiscalYearID = stt.FiscalYearID
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID
		where 
			b.BudgetReallocationGUID = @BudgetReallocationGUID
			and ba.UnitTypeID = 34
			and Change <> 0
			and b.Date >= isnull(stt.ApplyDate,'1900-01-01')
			and TimeClassID = 2
			and b.Archived = 0

		INSERT INTO #FactGLStagingValue	(DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src)
		SELECT 
			b.SourceDepartmentID as DepartmentID,
			b.SourceAccountID as AccountID,
			b.FiscalYearID,
			ba.FiscalMonthID,
			2 as TimeclassID,
			Change as Value,
			b.date as ApplyDate,
			'ra_3' as src
		FROM [mr].[BudgetReallocation] b
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		LEFT JOIN #FactGLStagingValue STT ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID and TimeClassID = 2 
		where Change <> 0
			and stt.DepartmentID is null
			and ba.UnitTypeID =34
			and b.Date >= isnull(stt.ApplyDate,'1900-01-01')
			and b.BudgetReallocationGUID = @BudgetReallocationGUID
			and b.Archived = 0 
		END
	ELSE
	IF @BudgetReallocationType = 'ManualFile'
	BEGIN
		UPDATE STT
			SET 
				stt.Amount = ba.NewSourceValue,
				stt.ApplyDate = b.Date,
				stt.Src = stt.Src + '[ManualFile_'+cast(NewSourceValue as varchar(50))+']'				
		FROM #FactGLStagingValue STT
		INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and b.Date >= stt.ApplyDate and b.FiscalYearID = stt.FiscalYearID
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID
		where 
			b.BudgetReallocationGUID = @BudgetReallocationGUID
			and ba.UnitTypeID = 34
			and TimeClassID = 2
			and Change <> 0
			and b.Archived = 0
		
		INSERT INTO #FactGLStagingValue	(DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src)
		SELECT 
			b.SourceDepartmentID as DepartmentID,
			b.SourceAccountID as AccountID,
			b.FiscalYearID,
			ba.FiscalMonthID,
			2 as TimeclassID,
			NewSourceValue as Value,
			b.date as ApplyDate,
			'ManualFile' as src
		FROM [mr].[BudgetReallocation] b
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		LEFT JOIN #FactGLStagingValue STT ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID and TimeClassID = 2 
		where Change <> 0
			and stt.DepartmentID is null
			and ba.UnitTypeID =34
			and b.Date >= isnull(stt.ApplyDate,'1900-01-01')
			and b.BudgetReallocationGUID = @BudgetReallocationGUID
			and b.Archived = 0
	END

	set @iteration  = @iteration +1

	FETCH NEXT FROM BRA_cursor   
	INTO @BudgetReallocationGUID,@date,@BudgetReallocationType   
END   
CLOSE BRA_cursor;  
DEALLOCATE BRA_cursor;  

SET @fromClause  = '
(
	SELECT 	
		STT.DepartmentID,
		STT.AccountID,
		STT.FiscalYearID,
		STT.FiscalMonthID,
		STT.TimeclassID,		
		0 as Amount,
		' + '''' + 'none' + '''' + ' as src
	FROM int.FactGL STT
	INNER JOIN fw.DimDepartment D ON D.DepartmentID = STT.DepartmentID
	LEFT JOIN #FactGLStagingValue fgs 
		ON fgs.DepartmentID = STT.DepartmentID 
		AND fgs.AccountID = STT.AccountID 
		AND fgs.FiscalYearID = STT.FiscalYearID 
		AND fgs.FiscalMonthID = STT.FiscalMonthID 
		AND fgs.TimeClassID = STT.TimeClassID
	WHERE fgs.DepartmentID IS NULL AND STT.IsDeleted = 0 AND STT.Value != 0 AND (STT.FiscalYearID = ' + cast(@FiscalYearID as nvarchar(100)) + ' or ' + cast(@FiscalYearID as nvarchar(100)) + ' = 0)
 ) X
'

TRUNCATE TABLE #inputDepartments

INSERT INTO #inputDepartments
EXEC dbo.procGetInputDataByBatches
    @batchSize = @batchSize,
	@columnName = 'DepartmentID',
	@tableAlias = 'X',
	@fromClause = @fromClause,
	@whereClause = '',
	@isDebug = 0

SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments
 		
SET @BatchID = 1
WHILE @BatchID <= @MaxBatchID
BEGIN	
	INSERT INTO #FactGLStagingValue (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, Src)
	SELECT stat.DepartmentID, stat.AccountID, stat.FiscalYearID, stat.FiscalMonthID, stat.TimeClassID, 0 as Amount, 'none' as src
	FROM int.FactGL stat  
	INNER JOIN fw.DimDepartment D ON D.Departmentid = stat.Departmentid
	LEFT JOIN #FactGLStagingValue fgs 
		ON fgs.DepartmentID = stat.DepartmentID 
		AND fgs.AccountID = stat.AccountID 
		AND fgs.FiscalYearID = stat.FiscalYearID 
		AND fgs.FiscalMonthID = stat.FiscalMonthID 
		AND fgs.TimeClassID = stat.TimeClassID
	INNER JOIN #inputDepartments ID ON ID.DepartmentID = D.Departmentid
	WHERE stat.IsDeleted = 0 
	  AND stat.Value != 0 
	  AND (stat.FiscalYearID = @FiscalYearID or @FiscalYearID = 0) 
	  AND ID.BatchID = @BatchID
	  AND fgs.DepartmentID IS NULL
	  
	SET @BatchID = @BatchID + 1
END
END
GO


---------------------------------------------

-- fw.procPreparePayrollByMonth
CREATE PROC [fw].[procPreparePayrollByMonth] (@FiscalYearID int =0)
as
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2018-03-19	IP		D-06997		Replaced table variable by temp tables 
***************************************************************/
	IF OBJECT_ID('tempdb.dbo.#StatisticTempTable', 'U') IS NOT NULL DROP TABLE #StatisticTempTable; 
	declare @iteration int = 1 
	create table #StatisticTempTable (
		DepartmentID int,
		JobCodeID int,
		EmployeeID int,
		PayCodeID int,
		PayCodeGroupID int,
		FiscalYearID smallint,
		FiscalMonthID tinyint,
		TimeClassID tinyint,
		Hours decimal(18,6),
		Dollars decimal(18,6),
		ApplyDate datetime,
		Src varchar(max)
)
	INSERT INTO #StatisticTempTable	(DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID,FiscalYearID,FiscalMonthID,TimeClassID,Hours,Dollars,ApplyDate,Src)
	SELECT
		pr.DepartmentID,
		pr.JobCodeID,
		pr.EmployeeID,
		pr.PayCodeID,
		pc.PayCodeGroupID,
		PR.FiscalYearID,
		pr.FiscalMonthID,
		pr.TimeClassID,
		SUM(CASE WHEN pr.unittypeID=51 and pc.IsHoursIgnored=0 then value ELSE 0 END) AS Hours,
		SUM(CASE WHEN pr.unittypeID=34 and pc.IsDollarsIgnored=0 then value ELSE 0 END) AS Dollars,
		cast('1900-01-01' as date) as ApplyDate,
		'int' as Src
	FROM
		int.FactStaffing pr
		INNER JOIN fw.DimPayCode pc on pc.PayCodeID = PR.PayCodeID
	WHERE 
		pr.FiscalMonthCode not in('', '0')		
		and pr.IsDeleted = 0
		and pr.Value != 0
		AND (pr.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0)
    GROUP BY
		pr.DepartmentID,
		pr.JobCodeID,
		pr.EmployeeID,
		pr.PayCodeID,
		pc.PayCodeGroupID,
		PR.FiscalYearID,
		pr.FiscalMonthID,
		pr.TimeClassID,
		pr.PayCodeID


DECLARE @BudgetReallocationGUID uniqueidentifier,@date datetime,@BudgetReallocationType varchar(50)

PRINT '-------- Vendor Products Report --------';  

DECLARE BRA_cursor CURSOR FOR   
SELECT distinct BudgetReallocationGUID,date,BudgetReallocationType from fw.BudgetReallocationWithDefinedType
WHERE (FiscalYearID = @FiscalYearID or @FiscalYearID = 0)
ORDER BY date;  

OPEN BRA_cursor  

FETCH NEXT FROM BRA_cursor   
INTO @BudgetReallocationGUID,@date,@BudgetReallocationType   

WHILE @@FETCH_STATUS = 0  
BEGIN  

print @iteration

	IF @BudgetReallocationType = 'ReallocateMulti'
	BEGIN
		UPDATE STT
			SET 
				stt.DepartmentID = b.TargetDepartmentID,
				stt.JobCodeID = b.TargetJobCodeID,
				stt.Src = stt.Src + ';RealMulti'
		FROM #StatisticTempTable STT
		INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceJobCodeID = stt.JobCodeID and b.Date >= stt.ApplyDate
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID
		where 
			b.BudgetReallocationGUID = @BudgetReallocationGUID
			and ba.UnitTypeID = 34
			and change <> 0
			and TimeClassID = 2
			and DataType = 1
	END

	set @iteration  = @iteration +1

	FETCH NEXT FROM BRA_cursor   
	INTO @BudgetReallocationGUID,@date,@BudgetReallocationType   
END   
CLOSE BRA_cursor;  
DEALLOCATE BRA_cursor;  

SELECT 	DepartmentID,
		JobCodeID,
		EmployeeID,
		PayCodeID,
		PayCodeGroupID,
		FiscalYearID,
		FiscalMonthID,
		TimeClassID,
		sum(Hours) as Hours,
		sum(Dollars) as Dollars
FROM (		
	SELECT 
		DepartmentID,
		JobCodeID,
		EmployeeID,
		PayCodeID,
		PayCodeGroupID,
		FiscalYearID,
		FiscalMonthID,
		TimeClassID,
		Hours,
		Dollars
	from #StatisticTempTable stt
	UNION ALL
	SELECT
		pr.DepartmentID,
		pr.JobCodeID,
		pr.EmployeeID,
		pr.PayCodeID,
		pc.PayCodeGroupID,
		PR.FiscalYearID,
		pr.FiscalMonthID,
		pr.TimeClassID,
		0 AS Hours,
		0 AS Dollars
	FROM
		int.FactStaffing pr
		INNER JOIN fw.DimPayCode pc on pc.PayCodeID = PR.PayCodeID
	WHERE 
		pr.FiscalMonthCode not in('', '0')		
		and pr.IsDeleted = 0
		and pr.Value != 0
		AND (pr.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0)
) SubSelect	
GROUP BY DepartmentID,
		JobCodeID,
		EmployeeID,
		PayCodeID,
		PayCodeGroupID,
		FiscalYearID,
		FiscalMonthID,
		TimeClassID
GO


---------------------------------------------

-- fw.procProviderSampledAdjustedTargetMonthlyInsert
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2018-10-30	KZ		B-20910	Provider - Create adjusted target
*************************************************************/
CREATE proc [fw].[procProviderSampledAdjustedTargetMonthlyInsert] (@FiscalYearID int = 0)
AS
BEGIN
	DECLARE @IsFlexingEnabled INT = (
		SELECT VALUE
		FROM [mr].[SystemSetting]
		WHERE NAME = 'Is Target Flexed'
		)
	DECLARE @IsEfficiencyFactorPresent INT = (
		SELECT count(*)
		FROM mr.EfficiencyFactor
		)
		
	IF @IsEfficiencyFactorPresent > 0 BEGIN
		DELETE FROM fw.FactProviderSampledMonthly_Pivoted WHERE (@FiscalYearID = FiscalYearID OR @FiscalYearID = 0) and TimeClassID = 22
		
		INSERT INTO fw.FactProviderSampledMonthly_Pivoted (DepartmentID,
			ProviderID,
			FiscalYearID,
			FiscalMonthID,
			TimeClassID,
			OBForecastDetailID,
			Volume,
			Dollars,
			Hours,
			FTEs)
		SELECT DepartmentID,
			ProviderID,
			FiscalYearID,
			FiscalMonthID,
			22,
			OBForecastDetailID,
			SUM(Volume),
			SUM(Dollars),
			SUM(Hours),
			SUM(FTEs)
		FROM fw.FactProviderSampledMonthly_Pivoted fact
		WHERE (
				(
					ISNULL(fact.TimeClassID,0) = 4 AND @IsFlexingEnabled = 1
				)
				OR (
					(
						ISNULL(fact.TimeClassID,0) = 20) AND @IsFlexingEnabled = 0
					)
			)
			AND (fact.FiscalYearID = @FiscalYearID OR @FiscalYearID = 0)
		GROUP BY DepartmentID,
			ProviderID,
			FiscalYearID,
			FiscalMonthID,
			TimeClassID,
			OBForecastDetailID
			
		EXEC [fw].[procFactMonthlyYTDPriorYearUpdate] @factTableName = 'fw.FactProviderSampledMonthly_Pivoted', @keyNameCSV = 'OBForecastDetailID,ProviderID',
			@measureNameCSV = 'Volume,Dollars,Hours,FTEs',@fiscalYearID  = @FiscalYearID, @timeClassID = 22, @isDebugOnly = 0
	END
END
GO


---------------------------------------------

-- fw.procProviderSampledInsertMonthly
/*************************************************************
** Change History
**************************************************************
** CID	Date        Author    	WI			Description
** 1	2016-12-13	NL			B-13759		Adding fiscalYearID param and filtering on it
** 2	2017-02-20	GF			D-05545		Move duplicate record handling from YTD into sampling + general cleanup
** 3	2017-04-11	IP			B-15086		Sampling Performance Improvements. Using temp tables insead of fw.FactProviderSampledMonthly.
** 4	2017-06-15	IP			B-15086 	odify SP to use unique temp table
** 5	2018-02-07	IP			B-18725 	MR - Provider sampling from payroll
** 6	2018-02-08	IP			TK-53982 	Fixed amount calculated as sum of Hours and Dollars
** 7	2018-02-28	IP			B-18946		Update provider payroll sampling to be consistent with OB when there is duplicate data
** 8	2018-06-27	KF			B-20195		MR - Provider calculate baseline target
** 9	2018-07-25	KF			B-20342		MR - Update provider sampling to be in the appropriate format
**10	2018-08-22	KF			D-07561		MR Sampling: Provider FTEsYTD values are calculated incorrectly
**11	2018-10-30	KF			D-07727		MR Provider Sampling: FTEs and FTEsYTD are calculated based on different Work Week overrides
**12	2022-03-15	KF			JAZZ-27781	Run PR Process Task can fail silently during Payroll Sampling
**13	2023-09-12  BS			JAZZ-55750  Remove filter to allow other time classes in MR reporting
*************************************************************/
CREATE proc [fw].[procProviderSampledInsertMonthly]
	@fiscalYearID smallint = 0
as

	IF OBJECT_ID('tempdb..#ProviderSampledStaging') IS NOT NULL  DROP TABLE #ProviderSampledStaging
	IF OBJECT_ID('fw.ProviderSampledStagingWithCalcs') IS NOT NULL  DROP TABLE fw.ProviderSampledStagingWithCalcs

	CREATE TABLE #ProviderSampledStaging (RowID bigint identity(1,1), DepartmentID int, ProviderID int, FiscalYearID int, FiscalMonthID int, OBForecastDetailID int, TimeClassID int,
	    Dollars decimal(18,6), Hours decimal(18,6), Volume decimal(18,6), FTEs decimal(18,6), isDeleted bit, isSystemGenerated bit)

		--push new data to fact table
    insert into #ProviderSampledStaging (DepartmentID, ProviderID, FiscalYearID, FiscalMonthID, OBForecastDetailID, TimeClassID, Dollars, Hours, Volume, FTEs)
    select
        p.DepartmentID,
        p.ProviderID,
        p.FiscalYearID,
        p.FiscalMonthID,
        p.OBForecastDetailID,
        p.TimeClassID,
		SUM(CASE WHEN fd.UnitTypeID=34 then value ELSE 0 END) AS Dollars,
		SUM(CASE WHEN fd.UnitTypeID=51 then value ELSE 0 END) AS Hours,
		SUM(CASE WHEN fd.UnitTypeID=140 then value ELSE 0 END) AS Volume,
		SUM(CASE WHEN fd.UnitTypeID=144 then value ELSE 0 END) AS FTEs
    from
        int.FactImportProvider p
		INNER JOIN ob.DimOBForecastDetail fd on fd.OBForecastDetailID = p.OBForecastDetailID
    where
        p.IsDeleted = 0 
		and p.Value != 0
		AND (p.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0)
    group by
        p.DepartmentID,
        p.ProviderID,
        p.FiscalYearID,
        p.FiscalMonthID,
        p.OBForecastDetailID,
        p.TimeClassID
	
	;with ProviderHours as (
	SELECT data.DepartmentID, data.ProviderID, data.FiscalYearID, data.FiscalMonthID, data.TimeClassID, SUM(data.Amount) as Hours
	FROM mr.viewFactProviderBasedOnPayroll data
	LEFT JOIN #ProviderSampledStaging pss on pss.DepartmentID = data.DepartmentID and pss.ProviderID = data.ProviderID and pss.FiscalYearID = data.FiscalYearID and pss.FiscalMonthID = data.FiscalMonthID and pss.OBForecastDetailID = 1000 and pss.TimeClassID = data.TimeClassID
	where data.UnitTypeID=51 --Hours
	and data.IsProvider = 1
	and pss.DepartmentID is null --use the provider import data and ignore the payroll data
	and data.ProductiveClass in
		(
			'Productive',
			'Productive Non-FTE', 
			'Non-Productive'
		)
	AND (data.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0)
	group by
	data.DepartmentID, data.ProviderID, data.FiscalYearID, data.FiscalMonthID,data.TimeClassID
	)

	INSERT INTO #ProviderSampledStaging 
		(DepartmentID, ProviderID, FiscalYearID, FiscalMonthID, OBForecastDetailID, TimeClassID, Dollars, Hours, Volume, FTEs)
	SELECT 
		 vw.DepartmentID, vw.ProviderID, vw.FiscalYearID, vw.FiscalMonthID, vw.OBForecastDetailID, vw.TimeClassID, SUM(vw.Amount) AS Dollars, 0 AS Hours, 0 AS Volume, 0 AS FTEs
	FROM mr.viewFactProviderBasedOnPayroll vw
	LEFT JOIN #ProviderSampledStaging pss on pss.DepartmentID = vw.DepartmentID and pss.ProviderID = vw.ProviderID and pss.FiscalYearID = vw.FiscalYearID and pss.FiscalMonthID = vw.FiscalMonthID and pss.OBForecastDetailID = vw.OBForecastDetailID and pss.TimeClassID = vw.TimeClassID
	--If there is overlap for the same month, year, time class, provider, and forecastdetail between the provider import data and the payroll data, then the system should use the provider import data and ignore the payroll data
	WHERE IsProvider = 1
	and pss.DepartmentID is null --use the provider import data and ignore the payroll data
	and vw.UnitTypeID=34 --Dollars
	and vw.Amount != 0
		AND (vw.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0)
    GROUP BY
        vw.DepartmentID,
        vw.ProviderID,
        vw.FiscalYearID,
        vw.FiscalMonthID,
        vw.OBForecastDetailID,
        vw.TimeClassID
	
	UNION ALL
	
	SELECT 
		 DepartmentID, ProviderID, FiscalYearID, FiscalMonthID,1000 as OBForecastDetailID, TimeClassID, 0 AS Dollars, Hours, 0 AS Volume, 0 AS FTEs
	FROM ProviderHours

	UNION ALL

	SELECT fact.DepartmentID, fact.ProviderID, fact.FiscalYearID, fact.FiscalMonthID,1001 as OBForecastDetailID, TimeClassID, 0 AS Dollars, 0 AS Hours, 0 AS Volume, fact.Value / (wpmCY.Hours) AS FTEs
	from int.FactImportProvider fact   
	inner join fw.dimProvider pr on pr.ProviderID = fact.ProviderID
	inner join fw.DimDepartment D on fact.DepartmentID=D.DepartmentID
	inner join fw.DimEntity de on de.EntityID = D.EntityID
	inner join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY on fact.FiscalMonthID=wpmCY.FiscalMonthID and fact.FiscalYearID = wpmCY.FiscalYearID
	  and wpmCY.WorkWeekID = case when pr.WorkWeekOverrideID != -1 then pr.WorkWeekOverrideID when pr.WorkWeekOverrideID = -1 AND D.WorkWeekID >= 0 then D.WorkWeekID else de.WorkWeekID end
	where fact.IsDeleted = 0 and fact.Value != 0 AND (fact.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) and 1000 = fact.OBForecastDetailID

	UNION ALL
	
	--Provider
	SELECT fact.DepartmentID, fact.ProviderID, fact.FiscalYearID, fact.FiscalMonthID,1001 as OBForecastDetailID, TimeClassID, 0 AS Dollars, 0 AS Hours, 0 AS Volume, fact.Hours / (wpmCY.Hours) AS FTEs
	from ProviderHours fact 
	inner join fw.dimProvider pr on pr.ProviderID = fact.ProviderID
	inner join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY on fact.FiscalMonthID=wpmCY.FiscalMonthID AND fact.FiscalYearID = wpmCY.FiscalYearID and wpmCY.WorkWeekID=pr.WorkWeekOverrideID
	where pr.WorkWeekOverrideID!=-1
	
	UNION ALL

	--Department
	SELECT fact.DepartmentID, fact.ProviderID, fact.FiscalYearID, fact.FiscalMonthID,1001 as OBForecastDetailID, TimeClassID, 0 AS Dollars, 0 AS Hours, 0 AS Volume, fact.Hours / (wpmCY.Hours) AS FTEs
	from ProviderHours fact
	inner join fw.dimProvider pr on pr.ProviderID = fact.ProviderID
	inner join fw.DimDepartment D on fact.DepartmentID=D.DepartmentID
	inner join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY on fact.FiscalMonthID=wpmCY.FiscalMonthID and fact.FiscalYearID = wpmCY.FiscalYearID and wpmCY.WorkWeekID=D.WorkWeekID
	where pr.WorkWeekOverrideID=-1 AND D.WorkWeekID >= 0

	UNION ALL

	--Entity
	SELECT fact.DepartmentID, fact.ProviderID, fact.FiscalYearID, fact.FiscalMonthID,1001 as OBForecastDetailID, TimeClassID, 0 AS Dollars, 0 AS Hours, 0 AS Volume, fact.Hours / (wpmCY.Hours) AS FTEs
	from ProviderHours fact
	inner join fw.dimProvider pr on pr.ProviderID = fact.ProviderID
	inner join fw.DimDepartment D on fact.DepartmentID=D.DepartmentID
	inner join fw.DimEntity de on de.EntityID = D.EntityID
	inner join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY on fact.FiscalMonthID=wpmCY.FiscalMonthID and fact.FiscalYearID = wpmCY.FiscalYearID and wpmCY.WorkWeekID=de.WorkWeekID
	where pr.WorkWeekOverrideID=-1 AND D.WorkWeekID < 0	

	--run calculations
	exec fw.procFactMonthlyMergeDuplicates '#ProviderSampledStaging', 'ProviderID,OBForecastDetailID', 'Dollars,Hours,Volume,FTEs', @fiscalYearID, 0, 0
	exec fw.procFactProviderSampledBaselineTargetUpdate @fiscalYearID = @fiscalYearID
	exec fw.procFactMonthlyYTDPriorYearUpdateStaging 'fw.FactProviderSampledMonthly_Pivoted','#ProviderSampledStaging','ProviderID,OBForecastDetailID', 'Dollars,Hours,Volume,FTEs', @fiscalYearID, 0, 0
	exec client.procFactProviderSampledMonthlyDetailedFTEsInsertStaging @fiscalYearID = @fiscalYearID

	print 'finish staging calculations  --- '+convert(varchar(20),GETDATE(),113)

	IF @fiscalYearID = 0 
	BEGIN
	truncate table fw.FactProviderSampledMonthly_Pivoted
	INSERT INTO fw.FactProviderSampledMonthly_Pivoted With (TABLOCKX) (
			DepartmentID,
			FiscalMonthID,
			FiscalYearID,
			ProviderID,
			OBForecastDetailID,
			TimeClassID,
			Dollars,
			DollarsYTD,
			DollarsPriorYear,
			DollarsPriorYTD,
			Hours,
			HoursYTD,
			HoursPriorYear,
			HoursPriorYTD,
			Volume,
			VolumeYTD,
			VolumePriorYear,
			VolumePriorYTD,
			FTEs,
			FTEsYTD,
			FTEsPriorYear,
			FTEsPriorYTD,
			IsDeleted,
			IsSystemGenerated
			)
	SELECT
		DepartmentID,
		FiscalMonthID,
		FiscalYearID,
		ProviderID,
		OBForecastDetailID,
		TimeClassID,
		Dollars,
		DollarsYTD,
		DollarsPriorYear,
		DollarsPriorYTD,
		Hours,
		HoursYTD,
		HoursPriorYear,
		HoursPriorYTD,
		Volume,
		VolumeYTD,
		VolumePriorYear,
		VolumePriorYTD,
		FTEs,
		FTEsYTD,
		FTEsPriorYear,
		FTEsPriorYTD,
		0 as IsDeleted,
		isnull(IsSystemGenerated,0) as IsSystemGenerated
	FROM fw.ProviderSampledStagingWithCalcs
	END
ELSE 
	BEGIN
		print 'Starting creating index --- '+convert(varchar(20),GETDATE(),113) 
		CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.ProviderSampledStagingWithCalcs (DepartmentID,FiscalMonthID,FiscalYearID,ProviderID,OBForecastDetailID,TimeClassID)
		print 'Starting transaction --- '+convert(varchar(20),GETDATE(),113) 
		BEGIN TRANSACTION Sampling
		BEGIN TRY 
		MERGE fw.FactProviderSampledMonthly_Pivoted With (TABLOCKX) AS target
		USING fw.ProviderSampledStagingWithCalcs AS source
			ON source.DepartmentID = target.DepartmentID
				AND source.ProviderID = target.ProviderID
				AND source.FiscalYearID = target.FiscalYearID
				AND source.FiscalMonthID = target.FiscalMonthID
				AND source.TimeClassID = target.TimeClassID
				AND source.OBForecastDetailID = target.OBForecastDetailID
		WHEN MATCHED AND NOT
			(target.Dollars = source.Dollars
			and target.DollarsYTD = source.DollarsYTD
			and target.DollarsPriorYear = source.DollarsPriorYear
			and target.DollarsPriorYTD = source.DollarsPriorYTD
			and target.Hours = source.Hours
			and target.HoursYTD = source.HoursYTD
			and target.HoursPriorYear = source.HoursPriorYear
			and target.HoursPriorYTD = source.HoursPriorYTD
			and target.Volume = source.Volume
			and target.VolumeYTD = source.VolumeYTD
			and target.VolumePriorYear = source.VolumePriorYear
			and target.VolumePriorYTD = source.VolumePriorYTD
			and target.FTEs = source.FTEs
			and target.FTEsYTD = source.FTEsYTD
			and target.FTEsPriorYear = source.FTEsPriorYear
			and target.FTEsPriorYTD = source.FTEsPriorYTD)
			THEN
				UPDATE
				SET target.Dollars = source.Dollars,
					target.DollarsYTD = source.DollarsYTD,
					target.DollarsPriorYear = source.DollarsPriorYear,
					target.DollarsPriorYTD = source.DollarsPriorYTD,
					target.Hours = source.Hours,
					target.HoursYTD = source.HoursYTD,
					target.HoursPriorYear = source.HoursPriorYear,
					target.HoursPriorYTD = source.HoursPriorYTD,
					target.Volume = source.Volume,
					target.VolumeYTD = source.VolumeYTD,
					target.VolumePriorYear = source.VolumePriorYear,
					target.VolumePriorYTD = source.VolumePriorYTD,
					target.FTEs = source.FTEs,
					target.FTEsYTD = source.FTEsYTD,
					target.FTEsPriorYear = source.FTEsPriorYear,
					target.FTEsPriorYTD = source.FTEsPriorYTD
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					DepartmentID,
					ProviderID,
					FiscalMonthID,
					FiscalYearID,
					OBForecastDetailID,
					TimeClassID,
					Dollars,
					DollarsYTD,
					DollarsPriorYear,
					DollarsPriorYTD,
					Hours,
					HoursYTD,
					HoursPriorYear,
					HoursPriorYTD,
					Volume,
					VolumeYTD,
					VolumePriorYear,
					VolumePriorYTD,
					FTEs,
					FTEsYTD,
					FTEsPriorYear,
					FTEsPriorYTD,
					IsDeleted,
					IsSystemGenerated
					)
				VALUES (
					source.DepartmentID,
					source.ProviderID,
					source.FiscalMonthID,
					source.FiscalYearID,
					source.OBForecastDetailID,
					source.TimeClassID,
					source.Dollars,
					source.DollarsYTD,
					source.DollarsPriorYear,
					source.DollarsPriorYTD,
					source.Hours,
					source.HoursYTD,
					source.HoursPriorYear,
					source.HoursPriorYTD,
					source.Volume,
					source.VolumeYTD,
					source.VolumePriorYear,
					source.VolumePriorYTD,
					source.FTEs,
					source.FTEsYTD,
					source.FTEsPriorYear,
					source.FTEsPriorYTD,
					0,
					isnull(IsSystemGenerated,0)
					)
		WHEN NOT MATCHED BY SOURCE
			AND Target.FiscalYearID = @fiscalYearID		
			THEN
				DELETE;

		COMMIT TRANSACTION Sampling
		END TRY
		BEGIN CATCH 
			ROLLBACK TRANSACTION Sampling;
			THROW
		END CATCH
	END
	IF OBJECT_ID('tempdb..#ProviderSampledStaging') IS NOT NULL  DROP TABLE #ProviderSampledStaging
	IF OBJECT_ID('fw.ProviderSampledStagingWithCalcs') IS NOT NULL  DROP TABLE fw.ProviderSampledStagingWithCalcs
GO


---------------------------------------------

-- fw.procRefreshEncounterBasedStatistics
CREATE   PROC fw.procRefreshEncounterBasedStatistics
  @departmentIds nvarchar(MAX) = NULL
AS
BEGIN
  SET NOCOUNT ON

  DROP TABLE IF EXISTS #departments

  SELECT val AS DepartmentId
  INTO #departments
  FROM ConvertCSValuesToTable(@departmentIds, ',')

  DROP TABLE IF EXISTS #detailsToMerge

  CREATE TABLE #detailsToMerge
  (
    RowID bigint identity(1,1),
    DateID int,
    DepartmentID int,
    AccountID int,
    Value decimal(19, 4)
  )
  CREATE CLUSTERED INDEX CNU_RowId ON #detailsToMerge(RowId)

  IF (@departmentIds IS NULL)
  BEGIN
    INSERT #detailsToMerge (DepartmentID, AccountID, DateID, Value)
    SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, SUM(ebs.Value)
    FROM fw.FactEncounterBasedStatistics ebs
      INNER JOIN fw.DimAccount a 
        ON a.AccountID = ebs.AccountID
      INNER JOIN fw.DimDepartment dep
        ON dep.DepartmentID = ebs.DepartmentID
    GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.DateID
  END
  ELSE
  BEGIN
    INSERT #detailsToMerge (DepartmentID, AccountID, DateID, Value)
    SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, SUM(ebs.Value)
    FROM fw.FactEncounterBasedStatistics ebs
      INNER JOIN fw.DimAccount a 
        ON a.AccountID = ebs.AccountID
      INNER JOIN fw.DimDepartment dep
        ON dep.DepartmentID = ebs.DepartmentID
      INNER JOIN #departments d
        ON ebs.DepartmentID = d.DepartmentId
    GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.DateID
  END

  DECLARE 
  @startRowId bigint,
  @maxRowId bigint,
  @endRowId bigint

  SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId)
  FROM #detailsToMerge

  WHILE (@startRowId <= @maxRowId)
  BEGIN
    SELECT @endRowId = MAX(d.RowId)
    FROM (SELECT TOP 1000000 RowId
            FROM #detailsToMerge
            WHERE RowId >= @startRowId
            ORDER BY RowID) AS d

    UPDATE fw.FactChargeBasedStatistics
    SET Value = ebs.Value
    FROM #detailsToMerge ebs
    INNER JOIN fw.FactChargeBasedStatistics cbs
      ON ebs.DepartmentID = cbs.DepartmentID
        AND ebs.AccountID = cbs.AccountID
        AND ebs.DateID = cbs.DateID
    WHERE ebs.RowId >= @startRowId
        AND ebs.RowId <= @endRowId

    INSERT fw.FactChargeBasedStatistics (DepartmentID, AccountID, DateID, Value)
    SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, ebs.Value
    FROM #detailsToMerge ebs
    WHERE ebs.RowId >= @startRowId
      AND ebs.RowId <= @endRowId
      AND NOT EXISTS
      (
        SELECT cbs.RowID
        FROM fw.FactChargeBasedStatistics cbs
        WHERE ebs.DepartmentID = cbs.DepartmentID
          AND ebs.AccountID = cbs.AccountID
          AND ebs.DateID = cbs.DateID
      )

    SELECT @startRowId = MIN(d.RowId)
    FROM #detailsToMerge d
    WHERE RowId > @endRowId
  END

  DROP TABLE IF EXISTS #departments
  DROP TABLE IF EXISTS #detailsToMerge

END
GO


---------------------------------------------

-- fw.procRefreshEncounterBasedStatisticsMonthly
CREATE   PROC fw.procRefreshEncounterBasedStatisticsMonthly
  @fiscalYearId smallint = 0
AS
BEGIN
  SET NOCOUNT ON

  DROP TABLE IF EXISTS #detailsToMerge

  CREATE TABLE #detailsToMerge
  (
    RowID bigint identity(1,1),
    FiscalYearID smallint,
    FiscalMonthID tinyint,
    DepartmentID int,
    AccountID int,
    Value decimal(19, 4)
  )
  CREATE CLUSTERED INDEX CNU_RowId ON #detailsToMerge(RowId)

  INSERT #detailsToMerge (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value)
  SELECT ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID, SUM(ebs.Value)
  FROM fw.FactEncounterBasedStatisticsMonthly ebs
    INNER JOIN fw.DimAccount a 
      ON a.AccountID = ebs.AccountID
    INNER JOIN fw.DimDepartment dep
      ON dep.DepartmentID = ebs.DepartmentID
  WHERE ebs.FiscalYearID = @fiscalYearId OR @fiscalYearId = 0
  GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID

  DECLARE
  @startRowId bigint,
  @maxRowId bigint,
  @endRowId bigint

  SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId)
  FROM #detailsToMerge

  WHILE (@startRowId <= @maxRowId)
  BEGIN
    SELECT @endRowId = MAX(d.RowId)
    FROM (SELECT TOP 1000000 RowId
            FROM #detailsToMerge
            WHERE RowId >= @startRowId
            ORDER BY RowID) AS d

    UPDATE fw.FactChargeBasedStatisticsMonthly
    SET Value = ebs.Value
    FROM #detailsToMerge ebs
    INNER JOIN fw.FactChargeBasedStatisticsMonthly cbs
      ON ebs.DepartmentID = cbs.DepartmentID
        AND ebs.AccountID = cbs.AccountID
        AND ebs.FiscalYearID = cbs.FiscalYearID
        AND ebs.FiscalMonthID = cbs.FiscalMonthID
    WHERE ebs.RowId >= @startRowId
        AND ebs.RowId <= @endRowId

    INSERT fw.FactChargeBasedStatisticsMonthly (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value)
    SELECT ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID, ebs.Value
    FROM #detailsToMerge ebs
    WHERE ebs.RowId >= @startRowId
      AND ebs.RowId <= @endRowId
      AND NOT EXISTS
      (
      SELECT cbs.RowID
      FROM fw.FactChargeBasedStatisticsMonthly cbs
      WHERE ebs.DepartmentID = cbs.DepartmentID
        AND ebs.AccountID = cbs.AccountID
        AND ebs.FiscalYearID = cbs.FiscalYearID
        AND ebs.FiscalMonthID = cbs.FiscalMonthID
      )

    SELECT @startRowId = MIN(d.RowId)
    FROM #detailsToMerge d
    WHERE RowId > @endRowId
  END

  DROP TABLE IF EXISTS #detailsToMerge

END
GO


---------------------------------------------

-- fw.procRestoreChargeBasedStatistics
CREATE   PROC fw.procRestoreChargeBasedStatistics
  @statisticID int
AS
BEGIN
  SET NOCOUNT ON

  CREATE TABLE #detailsToRestore
  (
  RowID bigint identity(1,1),
  DateID int,
  DepartmentID int,
  AccountID int
  )
  CREATE CLUSTERED INDEX CNU_RowId ON #detailsToRestore(RowId)

  INSERT #detailsToRestore (DepartmentID, AccountID, DateID)
  SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID
  FROM fw.FactEncounterBasedStatistics ebs
  WHERE ebs.StatisticID = @statisticID
  GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.DateID

  DECLARE
  @startRowId bigint,
  @maxRowId bigint,
  @endRowId bigint

  SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId)
  FROM #detailsToRestore

  WHILE (@startRowId <= @maxRowId)
  BEGIN
    SELECT @endRowId = MAX(d.RowId)
    FROM (SELECT TOP 1000000 RowId
          FROM #detailsToRestore
          WHERE RowId >= @startRowId
          ORDER BY RowID) as d

    DELETE cbs
    FROM fw.FactChargeBasedStatistics cbs
      JOIN #detailsToRestore ebs
        ON cbs.DepartmentID = ebs.DepartmentID
          AND cbs.AccountID = ebs.AccountID
          AND cbs.DateID = ebs.DateID
    WHERE ebs.RowId >= @startRowId
      AND ebs.RowId <= @endRowId

    INSERT fw.FactChargeBasedStatistics (DepartmentID, AccountID, DateID, Value)
    SELECT sgs.DepartmentID, sgs.AccountID, sgs.DateID, AVG(sgs.Value)
    FROM fw.FactSystemGeneratedStatistics sgs
      JOIN #detailsToRestore ebs
        ON sgs.DepartmentID = ebs.DepartmentID
          AND sgs.AccountID = ebs.AccountID
          AND sgs.DateID = ebs.DateID
    WHERE ebs.RowId >= @startRowId
      AND ebs.RowId <= @endRowId
    GROUP BY sgs.DepartmentID, sgs.AccountID, sgs.DateID

    SELECT @startRowId = MIN(d.RowId)
    FROM #detailsToRestore d
    WHERE RowId > @endRowId
  END

  DROP TABLE IF EXISTS #detailsToRestore
END
GO


---------------------------------------------

-- fw.procRestoreChargeBasedStatisticsMonthly
CREATE   PROC fw.procRestoreChargeBasedStatisticsMonthly
  @statisticID int
AS
BEGIN
  SET NOCOUNT ON

  DELETE cbs
  FROM fw.FactEncounterBasedStatisticsMonthly ebs
    JOIN fw.FactChargeBasedStatisticsMonthly cbs
      ON ebs.DepartmentID = cbs.DepartmentID
        AND ebs.AccountID = cbs.AccountID
        AND ebs.FiscalYearID = cbs.FiscalYearID
        AND ebs.FiscalMonthID = cbs.FiscalMonthID
  WHERE ebs.StatisticID = @statisticID

  INSERT fw.FactChargeBasedStatisticsMonthly (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value)
  SELECT sgs.DepartmentID, sgs.AccountID, sgs.FiscalYearID, sgs.FiscalMonthID, AVG(sgs.Value)
  FROM fw.FactEncounterBasedStatisticsMonthly ebs
    JOIN fw.FactSystemGeneratedStatisticsMonthly sgs
      ON ebs.DepartmentID = sgs.DepartmentID
        AND ebs.AccountID = sgs.AccountID
        AND ebs.FiscalYearID = sgs.FiscalYearID
        AND ebs.FiscalMonthID = sgs.FiscalMonthID
  WHERE ebs.StatisticID = @statisticID
  GROUP BY sgs.DepartmentID, sgs.AccountID, sgs.FiscalYearID, sgs.FiscalMonthID
END
GO


---------------------------------------------

-- fw.procSampleChargeBasedStatistics
/************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI	Description
** 1		2016-04-12	GF		B-11831	Add fiscalyear to mapping join
** 2		2017-01-31	AK		B-13926	Added department filter
** 3		2018-05-04	IPetriv	B-17037  PR - Set Global Weights for Charge Codes - PR Stats
** 4        2019-05-08  OV      B-22974  Performance improvements for fw.procSampleChargeBasedStatistics
** 5        2024-01-08  OK      JAZZ-63102   Add EBS statistic support
** 6        2024-05-17  OK      JAZZ-71350   Always fill out fw.SystemGeneratedStatistics
*************************************************************/
CREATE PROCEDURE [fw].[procSampleChargeBasedStatistics] @departmentIDs NVARCHAR(max) = NULL
AS
BEGIN
	IF OBJECT_ID('tempdb..#SampleChargeBasedStatisticsDepts') IS NOT NULL
		DROP TABLE #SampleChargeBasedStatisticsDepts
	
	SET NOCOUNT ON
	
	CREATE TABLE #SampleChargeBasedStatisticsDepts (val INT PRIMARY KEY)
	
	INSERT INTO #SampleChargeBasedStatisticsDepts
	SELECT val
	FROM ConvertCSValuesToTable(@departmentIDs, ',')
	
	CREATE TABLE #DepartmentChargeCodeStatisticMapping (
		[FiscalYearID] SMALLINT
		,[DepartmentID] INT
		,[ChargeCodeID] INT
		,[PatientTypeRollupID] INT
		,[AccountID] INT
		,[Weight] DECIMAL(19, 8)
		,[IsReviewed] BIT
		,[PriorityOrder] BIGINT
		)
	
	CREATE CLUSTERED INDEX BASE ON #DepartmentChargeCodeStatisticMapping (
		DepartmentID
		,ChargeCodeID
		,FiscalYearID
		,PatientTypeRollupID
		)
	
	INSERT INTO #DepartmentChargeCodeStatisticMapping
	SELECT [FiscalYearID]
		,[DepartmentID]
		,[ChargeCodeID]
		,[PatientTypeRollupID]
		,[AccountID]
		,[Weight]
		,[IsReviewed]
		,[PriorityOrder]
	FROM fw.viewDepartmentChargeCodeStatisticMapping
	
	IF (@departmentIDs IS NULL)
	BEGIN
		TRUNCATE TABLE fw.FactChargeBasedStatistics
	
		INSERT INTO fw.FactChargeBasedStatistics (
			AccountID
			,DepartmentID
			,DateID
			,Value
			)
		SELECT map.AccountID
			,bl.DepartmentID
			,bl.ServiceDateID
			,SUM(bl.UnitsOfService * map.Weight) AS Value
		FROM [dss].[FactPatientBillingLineItemDetail] bl
		INNER JOIN clientdss.FactPatientEncounterSummary es ON bl.EncounterID = es.EncounterID
		INNER JOIN fw.DimPatientType pt ON es.PatientTypeID = pt.PatientTypeID
		INNER JOIN #DepartmentChargeCodeStatisticMapping map ON bl.DepartmentID = map.DepartmentID
			AND bl.ChargeCodeID = map.ChargeCodeID
			AND pt.PatientTypeRollupID = map.PatientTypeRollupID
			AND map.FiscalYearID = bl.FiscalYearID
		WHERE map.AccountID <> 0
			AND map.Weight <> 0
		GROUP BY map.AccountID
			,bl.DepartmentID
			,bl.ServiceDateID
	END
	ELSE
	BEGIN
		WHILE EXISTS (
				SELECT NULL
				FROM fw.FactChargeBasedStatistics(NOLOCK)
				WHERE DepartmentID IN (
						SELECT val
						FROM #SampleChargeBasedStatisticsDepts
						)
				)
		BEGIN
			DELETE TOP (10000)
			FROM fw.FactChargeBasedStatistics
			WHERE DepartmentID IN (
					SELECT val
					FROM #SampleChargeBasedStatisticsDepts
					)
		END
	
		INSERT INTO fw.FactChargeBasedStatistics (
			AccountID
			,DepartmentID
			,DateID
			,Value
			)
		SELECT map.AccountID
			,bl.DepartmentID
			,bl.ServiceDateID
			,SUM(bl.UnitsOfService * map.Weight) AS Value
		FROM [dss].[FactPatientBillingLineItemDetail] bl
		INNER JOIN clientdss.FactPatientEncounterSummary es ON bl.EncounterID = es.EncounterID
		INNER JOIN fw.DimPatientType pt ON es.PatientTypeID = pt.PatientTypeID
		INNER JOIN #DepartmentChargeCodeStatisticMapping map ON bl.DepartmentID = map.DepartmentID
			AND bl.ChargeCodeID = map.ChargeCodeID
			AND pt.PatientTypeRollupID = map.PatientTypeRollupID
			AND map.FiscalYearID = bl.FiscalYearID
		WHERE map.AccountID <> 0
			AND map.Weight <> 0
			AND map.DepartmentID IN (
				SELECT val
				FROM #SampleChargeBasedStatisticsDepts
				)
		GROUP BY map.AccountID
			,bl.DepartmentID
			,bl.ServiceDateID
	END  
	
	DROP TABLE #DepartmentChargeCodeStatisticMapping
	
	DROP TABLE #SampleChargeBasedStatisticsDepts

    EXEC fw.procCopySystemGeneratedStatistics @departmentIDs

    IF EXISTS (SELECT 1 FROM dss.SystemSetting WHERE Name = 'Enable Persistent Encounter-based Statistics' AND Value = 1)
    BEGIN
        EXEC fw.procRefreshEncounterBasedStatistics @departmentIDs
    END

END
GO


---------------------------------------------

-- fw.procSampleChargeBasedStatisticsMonthly
/************************************************************
** Author: unknown
** Create Date: unknown
** Description: Translates DS charge units into account-based statistics for use throughout StrataJazz system
** Last Modified: 2015-12-17
** GM Release: 2016.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI	Description
** 1	2018-05-04	IPetriv	 B-19365  	  PR - Set Global Weights for Charge Codes - MR Stats
** 2	2018-07-09	IPetriv	 esc-09659	  relace direct join to view to temptable
** 3    2021-01-19  BS       JAZZ-10854   MR - Charge Based Statistics Flag
** 4    2024-01-08  OK       JAZZ-63102   Add EBS statistic support
** 5    2024-05-17  OK      JAZZ-71350   Always fill out fw.SystemGeneratedStatisticsMonthly
*************************************************************/
CREATE proc [fw].[procSampleChargeBasedStatisticsMonthly]
	@fiscalYearID smallint = 0
AS
BEGIN
	IF (@fiscalYearID = 0) 
	    BEGIN
		TRUNCATE TABLE fw.FactChargeBasedStatisticsMonthly
	    END 
	ELSE 
	    BEGIN
		WHILE EXISTS(SELECT NULL FROM fw.FactChargeBasedStatisticsMonthly (nolock) WHERE FiscalYearID = @fiscalYearID)
			DELETE top (1000000) fw.FactChargeBasedStatisticsMonthly WHERE FiscalYearID = @fiscalYearID
		END		

	IF (CAST((SELECT Value FROM mr.SystemSetting WHERE Name = 'Monthly Charged Based Statistics Enabled') AS bit) = 1)
		BEGIN
			exec [dbo].[procSysDropTempTable] '#Map'

			SELECT *
			INTO #Map
			FROM fw.viewDepartmentChargeCodeStatisticMapping map
			WHERE map.AccountID <> 0
				AND map.Weight <> 0
				AND (
					FiscalYearID = @fiscalYearID
					OR @fiscalYearID = 0
					)
			IF (CAST((SELECT Value FROM fw.SystemSetting WHERE Name = 'Charge Statistics Use Post Date') AS bit) = 1) 
				BEGIN
				--use post date

				INSERT INTO fw.FactChargeBasedStatisticsMonthly (AccountID, DepartmentID, FiscalYearID, FiscalMonthID, Value)
				SELECT
					map.AccountID,
					bl.DepartmentID,
					d.FiscalYear,
					d.CalendarMonth,
					SUM(bl.UnitsOfService * map.Weight) AS Value
				FROM 
					dss.[FactPatientBillingLineItemDetail] bl
					INNER JOIN fw.DimDate d WITH (READUNCOMMITTED) ON d.DateID = bl.PostDateID
					INNER JOIN clientdss.FactPatientEncounterSummary es WITH (READUNCOMMITTED) ON bl.EncounterID = es.EncounterID
					INNER JOIN fw.DimPatientType pt WITH (READUNCOMMITTED) ON es.PatientTypeID = pt.PatientTypeID
					INNER JOIN #Map map WITH (READUNCOMMITTED) ON bl.DepartmentID = map.DepartmentID AND bl.ChargeCodeID = map.ChargeCodeID AND pt.PatientTypeRollupID = map.PatientTypeRollupID AND map.FiscalYearID = d.FiscalYear
				GROUP BY
					map.AccountID,
					bl.DepartmentID,
					d.FiscalYear,
					d.CalendarMonth
				END
			ELSE 
				BEGIN
				--use service date
				INSERT INTO fw.FactChargeBasedStatisticsMonthly (AccountID, DepartmentID, FiscalYearID, FiscalMonthID, Value)
				SELECT
					map.AccountID,
					bl.DepartmentID,
					d.FiscalYear,
					d.CalendarMonth,
					SUM(bl.UnitsOfService * map.Weight) AS Value
				FROM 
					dss.[FactPatientBillingLineItemDetail] bl
					INNER JOIN fw.DimDate d WITH (READUNCOMMITTED) ON d.DateID = bl.ServiceDateID
					INNER JOIN clientdss.FactPatientEncounterSummary es WITH (READUNCOMMITTED) ON bl.EncounterID = es.EncounterID
					INNER JOIN fw.DimPatientType pt WITH (READUNCOMMITTED) ON es.PatientTypeID = pt.PatientTypeID
					INNER JOIN #Map map WITH (READUNCOMMITTED) ON bl.DepartmentID = map.DepartmentID AND bl.ChargeCodeID = map.ChargeCodeID AND pt.PatientTypeRollupID = map.PatientTypeRollupID AND map.FiscalYearID = d.FiscalYear
				GROUP BY
					map.AccountID,
					bl.DepartmentID,
					d.FiscalYear,
					d.CalendarMonth
				END	
			exec [dbo].[procSysDropTempTable] '#Map'
		END	    

    EXEC fw.procCopySystemGeneratedStatisticsMonthly @fiscalYearID

    IF EXISTS (SELECT 1 FROM dss.SystemSetting WHERE Name = 'Enable Persistent Encounter-based Statistics' AND Value = 1)
    BEGIN
        EXEC fw.procRefreshEncounterBasedStatisticsMonthly @fiscalYearID
    END

END
GO


---------------------------------------------

-- fw.procScoreFillinSetYears
--/****** Object:  StoredProcedure [dbo].[procCustomEMFSetYearFillins]    Script Date: 11/09/2009 17:17:57 ******/
--SET ANSI_NULLS ON
--GO

--SET QUOTED_IDENTIFIER ON
--GO






CREATE proc [fw].[procScoreFillinSetYears]
	@planguid uniqueidentifier
	,@PHSectionGUID uniqueidentifier
	,@FIDimensionGUID uniqueidentifier
	,@newFirstValue int
	,@newNumMembers int
	,@datatableGUIDList varchar(max)
as


--set @datatableGUIDList = '47413A00-1994-4606-8948-2BDFEDAC1FB9,63A2935D-EDB8-4DAF-863F-677831C6AC4E'
--set @planguid = 'DC0BC93A-F1D3-4BD1-B684-29DA5CBB8EEB'
--set @FIDimensionGUID = 'B383B29F-087E-4450-A216-3A3F03BB08D3'
--set @PHSectionGUID = '7696E505-7372-4D53-B6D5-5C8F95319C44'
--set @newFirstValue = 2009
--set @newNumMembers= 5


--record current first value for this section
declare @oldFirstValue int
declare @oldNumMembers int
select 
	@oldFirstValue = MIN(fy.fiscalyearid),
	@oldNumMembers= COUNT(distinct fy.fiscalyearid)
from
	ScoreFillin fi
	inner join fw.DimFiscalYear fy on fi.FillinMemberGUID = fy.MemberGUID
where
	fi.PlaceholderSectionMemberGUID = @PHSectionGUID
	and fi.ModelGUID = @planguid

if @oldFirstValue = @newFirstValue and @newNumMembers= @oldNumMembers begin
	print 'Already set correctly.'
	return
end

--clear fillins for this section
delete from ScoreFillin
where 
	PlaceholderSectionMemberGUID = @PHSectionGUID
	and ModelGUID = @planguid

--set fillins for this section
insert into ScoreFillin (modelguid, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName)
select
	@planguid, @PHSectionGUID, ROW_NUMBER() over (order by fiscalyearid) - 1, MemberGUID, FiscalYearID
from
	fw.DimFiscalYear
where
	FiscalYearID between @newFirstValue and @newFirstValue + @newNumMembers- 1
order by
	FiscalYearID

declare @offset int
set @offset = @newfirstvalue - @oldFirstValue 

declare @planDimensionGUID uniqueidentifier
select @planDimensionGUID = dimensionguid from PlanType where PlanTypeGUID = (select PlanTypeGUID from XPlan where PlanGUID = @planguid)

declare @planDimensionSchema nvarchar(max)
declare @planDimensionObject nvarchar(max)
declare @planDimensionKeyColumnName nvarchar(max)

select 
	@planDimensionSchema = sd.SQLSchemaName
	,@planDimensionObject = sd.SQLObjectName
	,@planDimensionKeyColumnName = dk.SQLColumnName --this is a touch hacky as it assumes default key is whats in the data tables
from
	ScoreDimension sd
	inner join ScoreAttribute dk on sd.DefaultKeyGUID = dk.AttributeGUID
where
	sd.DimensionGUID = @planDimensionGUID

declare @FIDimensionKeyColumnName nvarchar(max)
select 
	@FIDimensionKeyColumnName = dk.SQLColumnName --this is a touch hacky as it assumes default key is whats in the data tables
from
	ScoreDimension sd
	inner join ScoreAttribute dk on sd.DefaultKeyGUID = dk.AttributeGUID
where
	sd.DimensionGUID = @FIDimensionGUID


	
declare @sql nvarchar(max)

set @sql = '
declare @offset int
set @offset = ' + cast(@offset as varchar(max)) + '

declare @planguid uniqueidentifier
set @planguid = ''' + cast(@planguid as varchar(36)) + '''

--update data across all composites that use the specified placeholder dimension, and the specified plan dimension
update
	[{schema}].[{object}]
set
	[' + @FIDimensionKeyColumnName + '] = [' + @FIDimensionKeyColumnName + '] + @offset
where	
	[' + @planDimensionKeyColumnName + '] = (select [' + @planDimensionKeyColumnName + '] from [' + @planDimensionSchema + '].[' + @planDimensionObject + '] where MemberGUID = @planguid)
	and [' + @FIDimensionKeyColumnName + '] <> 0
	and isdeleted = 0
	
--delete data where value is not in correct range (and is not unspecified year)
update
	[{schema}].[{object}]
set
	isdeleted = 1
where	
	[' + @planDimensionKeyColumnName + '] = (select [' + @planDimensionKeyColumnName + '] from [' + @planDimensionSchema + '].[' + @planDimensionObject + '] where MemberGUID = @planguid)
	and [' + @FIDimensionKeyColumnName + '] <> 0
	and not [' + @FIDimensionKeyColumnName + '] between ' + cast(@newFirstValue as varchar(36)) + ' and ' + cast(@newFirstValue + @newNumMembers - 1 as varchar(max))  + '
	

'


declare @where varchar(max)
set @where = 'where datatableguid in (select guid from dbo.CSVGuidsToTable(''' + @datatableguidlist + '''))'

exec [procScoreRunForManyStructures] @sql, @where,1,0



--set @FirstMemberGUID = dbo.GetModelFirstFillInSection(@planguid, @phsectionguid)


--if @FirstMemberGUID = '00000000-0000-0000-0000-000000000000' begin
--	exec procEMFFillInAddToEndSection @phsectionguid, @targetfirstmemberguid, @planguid
--	set @firstmemberguid = @targetfirstmemberguid
--end 

--DECLARE @OFFSET Int

--SELECT @OFFSET = tfm.DisplayOrder - fm.DisplayOrder
--FROM
--	SecureListMember fm 
--	inner join SecureListMember tfm on fm.ListMemberGUID = @FirstMemberGUID and tfm.ListMemberGUID = @TargetFirstMemberGUID
	
--if @OFFSET is null return

--DECLARE @ONEGUID UniqueIdentifier
--SET @ONEGUID = '11111111-1111-1111-1111-111111111111'

--declare @PHDimGUID uniqueidentifier
--SELECT @PHDimGUID = listguid from SecureListMember where ListMemberGUID = @PHSectionGUID

--if @PHDimGUID is null return

--declare @fidimguid uniqueidentifier
--select @fidimguid = fillindimensionguid from SecureList where ListGUID = @PHDimGUID

--if @fidimguid is null return

--declare @higuid uniqueidentifier

--declare @cnt int
--exec procLogObjectHistory @PlanGUID, 'Changing base fill-in', 0, @higuid output

----FIX FILLINS
--UPDATE EMFFillIn SET FilledInMemberGUID = dbo.GetSecureListOffsetMember(FilledInMemberGUID,@offset)
--WHERE 
--	ModelGUID = @PlanGUID 
--	AND PlaceholderMemberGUID IN (SELECT ListMemberGUID FROM SecureListMember WHERE ParentListMemberGUID = @PHSectionGUID)

----DELETE FILLINS PUSHED OFF THE END of possible members
--DELETE FROM EMFFillIn WHERE 
--	MODELGUID = @PLANGUID 
--	and FilledInMemberGUID = @ONEGUID

----DELETE FILLINS PUSHED OFF THE END of # of members
--DELETE FROM EMFFillIn WHERE ModelGUID = @PlanGUID AND FilledInMemberGUID IN (SELECT GUID FROM dbo.getFillinMembersPastMaxIndex(@PLANGUID, @PHDimGUID, @NumMembers))

----add FILLINS to equal # of members
--exec procEMFFillInAdd @planguid, @PHDimGUID, @NumMembers

--declare @sql varchar(max)
--declare @mdTableName varchar(max)

--declare @phDimColumnName varchar(max)
--set @phDimColumnName = 'G' + REPLACE(cast(@phdimguid as varchar(36)),'-','_')

--set @sql = '
--declare @msg varchar(max)
--declare @cnt int
--declare @planguid uniqueidentifier
--set @planguid = ''' + cast(@planguid as varchar(36))+ '''

--declare @fidimguid uniqueidentifier
--set @fidimguid = ''' + cast(@fidimguid as varchar(36))+ '''

--declare @PHSectionGUID uniqueidentifier
--set @PHSectionGUID = ''' + cast(@PHSectionGUID as varchar(36))+ '''

--declare @oneguid uniqueidentifier
--set @oneguid = ''11111111-1111-1111-1111-111111111111''

--declare @higuid uniqueidentifier
--set @higuid = ''' + cast(@higuid as varchar(36)) + '''

--UPDATE zzemfmodeldata_{mdcguidfriendly}
--SET 
--   zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' = dbo.GetSecureListOffsetMember(zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ',' + cast(@offset as varchar(4)) + ')
--    ,HISTORYITEMGUID = @higuid
--WHERE 
--	MODELGUID = @planguid
--	--ONLY Update data who was previously assigned to a member that was filling in the section we are updating, altho this could cause a duplicate issue
--	AND zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' 
--		IN ( SELECT FI.FilledInMemberGUID FROM EMFFillIn FI WHERE FI.PlaceholderMemberGUID 
--				IN (SELECT ListMemberGUID FROM SecureListMember WHERE ParentListMemberGUID = @PHSectionGUID))

--DELETE FROM zzemfmodeldata_{mdcguidfriendly} WHERE VALUE = 0 AND MODELGUID = @PLANGUID and zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' = @ONEGUID
--DELETE FROM zzemfmodeldata_{mdcguidfriendly} WHERE MODELGUID = @PLANGUID and (zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' = @ONEGUID
--	OR (
--			not zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' in (select filledinmemberguid from emffillin where modelguid = @planguid)  --orphan cause not filled in
--			and
--			not zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' = ''00000000-0000-0000-0000-000000000000'' --not orphaned because emptyguid is ok
--		)
--	)
		
--set @cnt = @@rowcount
--if @cnt > 0 begin
--  set @msg = ''Cleared orphaned nonzero cells from {mdcname} while changing Year configuration''
--  exec procLogObjectHistory @PlanGUID, @msg, @cnt, @higuid
--end

--'


--declare @mtguid uniqueidentifier
--select @mtguid = modeltemplateguid from XPlan where PlanGUID = @PLANGUID

----FOR EACH MD TABLE USED BY THIS PLAN
--declare @where varchar(max)
--set @where = 'where modeldataconfigguid in (select modeldataconfigguid from viewEMFModelTemplateMDCs where modeltemplateguid = ''' + cast(@mtguid as varchar(36)) + ''')
--					and modeldataconfigguid in (select modeldataconfigguid from emfmodeldataconfigdimensionlink where dimensionguid = ''' + cast(@PHDimGUID as varchar(36)) + ''')
--'

--exec procEMFRunForManyStructures @sql, @where, 1
GO


---------------------------------------------

-- fw.procSetCurrentDataPayPeriodID
CREATE proc [fw].[procSetCurrentDataPayPeriodID]
as
	
declare @currentPP int;

set @currentPP = (
	select 
		MAX(pr.PayPeriodID)
	from 
		fw.FactPayrollSampledPayPeriod pr  
		inner join fw.DimPayPeriod pp on pp.PayPeriodID = pr.PayPeriodID
	where 
		pr.TimeClassID=1 
		and (pr.Dollars <> 0 or pr.Hours <> 0)
		and pp.PayCycleID=0
	)

if (@currentPP is null) set @currentPP = 0
	
exec procChangeDBSetting 'Current_Payroll_PayPeriodID', @currentPP	

--Update Default Report Parameter--------------------------------------------------------------
exec [pi].[procReportDefaultParameterUpdateToCurrent]
GO


---------------------------------------------

-- fw.procStatisticPrimarySampledAdjustedTargetMonthlyInsert
CREATE PROCEDURE [fw].[procStatisticPrimarySampledAdjustedTargetMonthlyInsert] (@FiscalYearID int = 0)
AS
BEGIN
/*
Proposal

If the client is not using flexing, this will be the target plus the efficiency factor
This should work regardless of the target basis (i.e. rolling avg or budget)
The factor will be applied after the inversion
If the factor type is percentage, the adjusted target will be the target*(1+factor)
i.e. if my target is 100 and my factor is 5%, the adjusted target will be 100*(1+0.05)=105
i.e. if my target is 100 and my factor is -5%, the adjusted target will be 100*(1+-0.05)=95
If the factor type is value, the adjusted value will be target + factor
i.e. if my target is 1000 and my factor is 200, the adjusted target will be will be 1000+200=1200
i.e. if my target is 1000 and my factor is -200, the adjusted target will be 1000-200=800
If there is more than one factor impacting a department and account or job code/pay code group combination, then the factors should layer on top of each other based on history order
If an efficiency factor does not exist for a particular account/job code, then the value in the new time class will be either flex or baseline target if flex is not used
This will happen after Flex is calculated
Include integration tests
*/
/*
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1      2022-08-23  BC             JAZZ-11498  Change Table Variable to Temporary Tables 
************************************************************
*/
DECLARE @IsFlexingEnabled INT = (
		SELECT VALUE
		FROM [mr].[SystemSetting]
		WHERE NAME = 'Is Target Flexed'
		)

IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE #EfficiencyFactorScope	
CREATE TABLE #EfficiencyFactorScope  (
	EfficiencyFactorGUID [uniqueidentifier] NOT NULL
	,[DepartmentID] [int] NOT NULL
	,[AccountID] [int] NOT NULL
	,[FiscalYearID] [smallint] NOT NULL
	,[FiscalMonthID] [tinyint] NOT NULL
	,Value NUMERIC(25, 6) NOT NULL
	,Type TINYINT
	,FactorType CHAR(1)
	,DateCreated DATETIME
	,UNIQUE CLUSTERED (
		FiscalYearID
		,FiscalMonthID
		,DepartmentID
		,AccountID
		,EfficiencyFactorGUID
		)
	);
IF EXISTS (SELECT TOP 1 * FROM [mr].[EfficiencyFactor]) BEGIN
WITH EfficiencyFactorScope
AS (
	SELECT *
		,rn = ROW_NUMBER() OVER (
			PARTITION BY FiscalYearID
			,FiscalMonthID
			,DepartmentID
			,AccountID
			,EfficiencyFactorGUID ORDER BY FiscalYearID
				,FiscalMonthID
				,DepartmentID
				,AccountID
				,EfficiencyFactorGUID
			)
	FROM (
		SELECT DISTINCT ef.EfficiencyFactorGUID
			,ef.FiscalYearID
			,efgd.FiscalMonthID
			,efd.DepartmentID
			,isnull(efgd.AccountID, da.AccountID) AS AccountID
			,CASE 
				WHEN isnull(efgd.AccountID, - 999) = da.AccountID
					THEN 0
				ELSE efgd.Value
				END AS Value
			,ef.Type
			,ef.FactorType
			,ef.DateCreated
		FROM mr.EfficiencyFactor ef
		INNER JOIN mr.EfficiencyFactorDepartment efd ON ef.EfficiencyFactorGUID = efd.EfficiencyFactorGUID
		INNER JOIN mr.EfficiencyFactorGLDetails efgd ON efgd.EfficiencyFactorGUID = ef.EfficiencyFactorGUID
		LEFT JOIN fw.DimAccount da ON efgd.OBFinancialReportingID = da.OBUnitsFinancialReportingID and efgd.AccountID IS NULL
		LEFT JOIN mr.EfficiencyFactorGLDetails efgd_exist ON efgd.EfficiencyFactorGUID = efgd_exist.EfficiencyFactorGUID and efgd_exist.AccountID = da.AccountID  and efgd_exist.FiscalMonthID = efgd.FiscalMonthID
		WHERE (@FiscalYearID = ef.FiscalYearID or @FiscalYearID = 0)  and (efgd_exist.AccountID is null or da.AccountID is null) AND ef.Type = 1 AND isnull(efgd.AccountID, da.AccountID) IS NOT NULL
		) X
	)
INSERT INTO #EfficiencyFactorScope (
	EfficiencyFactorGUID
	,[DepartmentID]
	,[AccountID]
	,[FiscalYearID]
	,[FiscalMonthID]
	,Value
	,Type
	,FactorType
	,DateCreated
	)
SELECT EfficiencyFactorGUID
	,[DepartmentID]
	,[AccountID]
	,[FiscalYearID]
	,[FiscalMonthID]
	,Value
	,Type
	,FactorType
	,DateCreated
FROM EfficiencyFactorScope
WHERE RN = 1

DELETE FROM fw.FactStatisticPrimarySampledMonthly WHERE (@FiscalYearID = FiscalYearID or @FiscalYearID = 0) and TimeClassID = 22

INSERT INTO fw.FactStatisticPrimarySampledMonthly (DepartmentID,
AccountID,
FiscalYearID,
FiscalMonthID,
TimeClassID,
IsDeleted,
Amount)
SELECT DepartmentID
	,AccountID
	,FiscalYearID
	,FiscalMonthID
	,22 as TimeClassID
	,0 as IsDeleted
	,SUM(Amount) as Amount
FROM (
SELECT isnull(fact.DepartmentID,ToApply.DepartmentID) as DepartmentID
	,isnull(fact.AccountID,toApply.AccountID) as AccountID
	,isnull(fact.FiscalYearID,toApply.FiscalYearID) as FiscalYearID
	,isnull(fact.FiscalMonthID,toApply.FiscalMonthID) as FiscalMonthID
	,Amount = CASE 
					WHEN FactorType = 'P'
						THEN isnull(fact.Amount,0.0) * isnull(Value,0.0) / 100
					WHEN FactorType = 'V'
						THEN isnull(Value,0.0)
					ELSE 0
					END
FROM #EfficiencyFactorScope ToApply
	INNER JOIN (SELECT distinct DepartmentID,AccountID from fw.FactStatisticPrimarySampledMonthly) GenCand on
			GenCand.DepartmentID	= ToApply.DepartmentID
		AND GenCand.AccountID		= ToApply.AccountID
	FULL JOIN fw.FactStatisticPrimarySampledMonthly fact ON 
		fact.DepartmentID = ToApply.DepartmentID
		AND fact.AccountID = ToApply.AccountID
		AND fact.FiscalYearID = ToApply.FiscalYearID
		AND fact.FiscalMonthID = ToApply.FiscalMonthID
	WHERE (
		(
			isnull(fact.TimeClassID,0) = 4
			AND @IsFlexingEnabled = 1
			)
		OR (
			isnull(fact.TimeClassID,0) = 20
			AND @IsFlexingEnabled = 0
			)
		)
	and (fact.FiscalYearID = @FiscalYearID or @FiscalYearID = 0)
UNION ALL
	
SELECT DepartmentID
	,AccountID
	,FiscalYearID
	,FiscalMonthID
	,Amount
FROM fw.FactStatisticPrimarySampledMonthly fact
WHERE (
		(
			isnull(fact.TimeClassID,0) = 4
			AND @IsFlexingEnabled = 1
			)
		OR (
			isnull(fact.TimeClassID,0) = 20
			AND @IsFlexingEnabled = 0
			)
		)
	and (fact.FiscalYearID = @FiscalYearID or @FiscalYearID = 0)
) X
GROUP BY DepartmentID
	,AccountID
	,FiscalYearID
	,FiscalMonthID

exec [fw].[procFactMonthlyYTDPriorYearUpdate] @factTableName = 'fw.FactStatisticPrimarySampledMonthly',@keyNameCSV = 'AccountID',@measureNameCSV = 'Amount',@fiscalYearID  = 0,@timeClassID = 22,@isDebugOnly = 0
END
END
IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE  #EfficiencyFactorScope
GO


---------------------------------------------

-- fw.procStatisticPrimarySampledInsertMonthly
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
** 1		2014-09-03	MS			B-02863	Removing the parameter from the YTD proc call
** 2		2016-09-22	AK			B-11845	procFactStatisticPrimarySampledBaselineTargetUpdate
** 3		2016-12-13	NL			B-13759	Adding fiscalYearID param and filtering
** 4		2017-02-20	GF			D-05545	Move duplicate record handling from YTD into sampling + general cleanup
** 5		2017-03-06	GF			B-14693	Added baseline target year filter
** 6		2017-04-11	IP			B-15086	Sampling Performance Improvements. Using temp tables insead of fw.procStatisticPrimarySampledInsertMonthly
** 7		2017-06-15	IP			B-15086 Modify SP to use unique temp table
** 8		2017-07-19	IP			TK-45395 	added isSystemGenerated to merge statement 
** 9		2017-07-26	ipetriv		B-16752		Added units Budget Adjustment
** 10		2017-08-29 	ip			B-16798		Add using of Budget Adjustment.
** 11		2022-03-15	KF			JAZZ-27781	Run PR Process Task can fail silently during Payroll Sampling
*************************************************************/
CREATE proc [fw].[procStatisticPrimarySampledInsertMonthly] 
	@fiscalYearID smallint = 0
as
	IF OBJECT_ID('tempdb..#StatisticPrimarySampledStaging') IS NOT NULL  DROP TABLE #StatisticPrimarySampledStaging
	IF OBJECT_ID('fw.StatisticPrimarySampledStagingWithCalcs') IS NOT NULL  DROP TABLE fw.StatisticPrimarySampledStagingWithCalcs
	
	CREATE TABLE #StatisticPrimarySampledStaging (RowID bigint identity(1,1),AccountID int, DepartmentID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Amount decimal(19,4), isDeleted bit, isSystemGenerated bit)		
	insert into #StatisticPrimarySampledStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount)
	exec fw.PrepareStatistics @FiscalYearID,1
	
	--run calculations	
	exec fw.procFactMonthlyMergeDuplicates 'fw.FactStatisticPrimarySampledMonthly', 'AccountID', 'Amount', @fiscalYearID, 0, 0
    exec fw.procFactStatisticPrimarySampledBaselineTargetUpdate @fiscalYearID = @fiscalYearID
	exec fw.procFactMonthlyYTDPriorYearUpdateStaging 'fw.FactStatisticPrimarySampledMonthly','#StatisticPrimarySampledStaging', 'AccountID', 'Amount', @fiscalYearID, 0, 0

	IF @fiscalYearID = 0 
	BEGIN
	truncate table fw.FactStatisticPrimarySampledMonthly
	INSERT INTO fw.FactStatisticPrimarySampledMonthly With (TABLOCKX) (
			DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID,
			Amount,
			AmountYTD,
			AmountPriorYear,
			AmountPriorYTD,
			IsDeleted,
			IsSystemGenerated
			)
		SELECT DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID,
		Amount,
		AmountYTD,
		AmountPriorYear,
		AmountPriorYTD,
		0 as IsDeleted,
		isnull(IsSystemGenerated,0) as IsSystemGenerated
	FROM fw.StatisticPrimarySampledStagingWithCalcs
	END
ELSE 
	BEGIN
		print 'Starting creating index --- '+convert(varchar(20),GETDATE(),113) 
		CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.StatisticPrimarySampledStagingWithCalcs (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID)
		print 'Starting transaction --- '+convert(varchar(20),GETDATE(),113) 
		BEGIN TRANSACTION Sampling
		BEGIN TRY 
		MERGE fw.FactStatisticPrimarySampledMonthly With (TABLOCKX) AS target
		USING fw.StatisticPrimarySampledStagingWithCalcs AS source
			ON source.DepartmentID = target.DepartmentID
				AND source.AccountID = target.AccountID
				AND source.FiscalYearID = target.FiscalYearID
				AND source.FiscalMonthID = target.FiscalMonthID
				AND source.TimeClassID = target.TimeClassID
		WHEN MATCHED AND 
			(target.Amount <> source.Amount
			or target.AmountYTD <> source.AmountYTD
			or target.AmountPriorYear <> source.AmountPriorYear
			or target.AmountPriorYTD <> source.AmountPriorYTD
			or target.IsSystemGenerated <> source.IsSystemGenerated
			)
			THEN
				UPDATE
				SET target.Amount = source.Amount,
					target.AmountYTD = source.AmountYTD,
					target.AmountPriorYear = source.AmountPriorYear,
					target.AmountPriorYTD = source.AmountPriorYTD,
					target.IsSystemGenerated = source.IsSystemGenerated
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID,
					Amount,
					AmountYTD,
					AmountPriorYear,
					AmountPriorYTD,
					IsDeleted,
					IsSystemGenerated
					)
				VALUES (
					source.DepartmentID,
					source.AccountID,
					source.FiscalYearID,
					source.FiscalMonthID,
					source.TimeClassID,
					source.Amount,
					source.AmountYTD,
					source.AmountPriorYear,
					source.AmountPriorYTD,
					0,
					isnull(IsSystemGenerated,0)
					)
		WHEN NOT MATCHED BY SOURCE
			AND Target.FiscalYearID = @fiscalYearID		
			THEN
				DELETE;

		COMMIT TRANSACTION Sampling
		END TRY
		BEGIN CATCH 
			ROLLBACK TRANSACTION Sampling;
			THROW
		END CATCH
	END
	IF OBJECT_ID('tempdb..#StatisticPrimarySampledStaging') IS NOT NULL  DROP TABLE #StatisticPrimarySampledStaging
	IF OBJECT_ID('fw.StatisticPrimarySampledStagingWithCalcs') IS NOT NULL  DROP TABLE fw.StatisticPrimarySampledStagingWithCalcs
GO


---------------------------------------------

-- fw.procStatisticSampledAdjustedTargetMonthlyInsert
CREATE PROCEDURE [fw].[procStatisticSampledAdjustedTargetMonthlyInsert] (@FiscalYearID int = 0)
AS
BEGIN
/*
Proposal

If the client is not using flexing, this will be the target plus the efficiency factor
This should work regardless of the target basis (i.e. rolling avg or budget)
The factor will be applied after the inversion
If the factor type is percentage, the adjusted target will be the target*(1+factor)
i.e. if my target is 100 and my factor is 5%, the adjusted target will be 100*(1+0.05)=105
i.e. if my target is 100 and my factor is -5%, the adjusted target will be 100*(1+-0.05)=95
If the factor type is value, the adjusted value will be target + factor
i.e. if my target is 1000 and my factor is 200, the adjusted target will be will be 1000+200=1200
i.e. if my target is 1000 and my factor is -200, the adjusted target will be 1000-200=800
If there is more than one factor impacting a department and account or job code/pay code group combination, then the factors should layer on top of each other based on history order
If an efficiency factor does not exist for a particular account/job code, then the value in the new time class will be either flex or baseline target if flex is not used
This will happen after Flex is calculated
Include integration tests
*/
/*
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1        2022-08-23  BC      JAZZ-11498  Change Table Variable to Temporary Tables 
************************************************************
*/
DECLARE @IsFlexingEnabled INT = (
		SELECT VALUE
		FROM [mr].[SystemSetting]
		WHERE NAME = 'Is Target Flexed'
		)
IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE #EfficiencyFactorScope	
CREATE TABLE #EfficiencyFactorScope  (
	EfficiencyFactorGUID [uniqueidentifier] NOT NULL
	,[DepartmentID] [int] NOT NULL
	,[AccountID] [int] NOT NULL
	,[FiscalYearID] [smallint] NOT NULL
	,[FiscalMonthID] [tinyint] NOT NULL
	,Value NUMERIC(25, 6) NOT NULL
	,Type TINYINT
	,FactorType CHAR(1)
	,DateCreated DATETIME
	,UNIQUE CLUSTERED (
		FiscalYearID
		,FiscalMonthID
		,DepartmentID
		,AccountID
		,EfficiencyFactorGUID
		)
	);
IF EXISTS (SELECT TOP 1 * FROM [mr].[EfficiencyFactor]) BEGIN
WITH EfficiencyFactorScope
AS (
	SELECT *
		,rn = ROW_NUMBER() OVER (
			PARTITION BY FiscalYearID
			,FiscalMonthID
			,DepartmentID
			,AccountID
			,EfficiencyFactorGUID ORDER BY FiscalYearID
				,FiscalMonthID
				,DepartmentID
				,AccountID
				,EfficiencyFactorGUID
			)
	FROM (
		SELECT DISTINCT ef.EfficiencyFactorGUID
			,ef.FiscalYearID
			,efgd.FiscalMonthID
			,efd.DepartmentID
			,isnull(efgd.AccountID, da.AccountID) AS AccountID
			,CASE 
				WHEN isnull(efgd.AccountID, - 999) = da.AccountID
					THEN 0
				ELSE efgd.Value
				END AS Value
			,ef.Type
			,ef.FactorType
			,ef.DateCreated
		FROM mr.EfficiencyFactor ef
		INNER JOIN mr.EfficiencyFactorDepartment efd ON ef.EfficiencyFactorGUID = efd.EfficiencyFactorGUID
		INNER JOIN mr.EfficiencyFactorGLDetails efgd ON efgd.EfficiencyFactorGUID = ef.EfficiencyFactorGUID
		LEFT JOIN fw.DimAccount da ON efgd.OBFinancialReportingID = da.OBUnitsFinancialReportingID and efgd.AccountID IS NULL
		LEFT JOIN mr.EfficiencyFactorGLDetails efgd_exist ON efgd.EfficiencyFactorGUID = efgd_exist.EfficiencyFactorGUID and efgd_exist.AccountID = da.AccountID  and efgd_exist.FiscalMonthID = efgd.FiscalMonthID
		WHERE (@FiscalYearID = ef.FiscalYearID or @FiscalYearID = 0)  and (efgd_exist.AccountID is null or da.AccountID is null) AND ef.Type = 1 AND isnull(efgd.AccountID, da.AccountID) IS NOT NULL
		) X
	)
INSERT INTO #EfficiencyFactorScope (
	EfficiencyFactorGUID
	,[DepartmentID]
	,[AccountID]
	,[FiscalYearID]
	,[FiscalMonthID]
	,Value
	,Type
	,FactorType
	,DateCreated
	)
SELECT EfficiencyFactorGUID
	,[DepartmentID]
	,[AccountID]
	,[FiscalYearID]
	,[FiscalMonthID]
	,Value
	,Type
	,FactorType
	,DateCreated
FROM EfficiencyFactorScope
WHERE RN = 1

DELETE FROM fw.FactStatisticSampledMonthly WHERE (@FiscalYearID = FiscalYearID or @FiscalYearID = 0) and TimeClassID = 22

INSERT INTO fw.FactStatisticSampledMonthly (DepartmentID,
AccountID,
FiscalYearID,
FiscalMonthID,
TimeClassID,
IsDeleted,
Amount)
SELECT DepartmentID
	,AccountID
	,FiscalYearID
	,FiscalMonthID
	,22 as TimeClassID
	,0 as IsDeleted
	,SUM(Amount) as Amount
FROM (
SELECT isnull(fact.DepartmentID,ToApply.DepartmentID) as DepartmentID
	,isnull(fact.AccountID,toApply.AccountID) as AccountID
	,isnull(fact.FiscalYearID,toApply.FiscalYearID) as FiscalYearID
	,isnull(fact.FiscalMonthID,toApply.FiscalMonthID) as FiscalMonthID
	,Amount = CASE 
					WHEN FactorType = 'P'
						THEN isnull(fact.Amount,0.0) * isnull(Value,0.0) / 100.00
					WHEN FactorType = 'V'
						THEN isnull(Value,0)
					ELSE 0
					END
FROM #EfficiencyFactorScope ToApply
	INNER JOIN (SELECT distinct DepartmentID,AccountID from fw.FactStatisticSampledMonthly) GenCand on
			GenCand.DepartmentID	= ToApply.DepartmentID
		AND GenCand.AccountID		= ToApply.AccountID
	FULL JOIN fw.FactStatisticSampledMonthly fact ON 
		fact.DepartmentID = ToApply.DepartmentID
		AND fact.AccountID = ToApply.AccountID
		AND fact.FiscalYearID = ToApply.FiscalYearID
		AND fact.FiscalMonthID = ToApply.FiscalMonthID
	WHERE (
		(
			isnull(fact.TimeClassID,0) = 4
			AND @IsFlexingEnabled = 1
			)
		OR (
			isnull(fact.TimeClassID,0) = 20
			AND @IsFlexingEnabled = 0
			)
		)
	and (fact.FiscalYearID = @FiscalYearID or @FiscalYearID = 0)
UNION ALL
	
SELECT DepartmentID
	,AccountID
	,FiscalYearID
	,FiscalMonthID
	,Amount
FROM fw.FactStatisticSampledMonthly fact
WHERE (
		(
			isnull(fact.TimeClassID,0) = 4
			AND @IsFlexingEnabled = 1
			)
		OR (
			isnull(fact.TimeClassID,0) = 20
			AND @IsFlexingEnabled = 0
			)
		)
	and (fact.FiscalYearID = @FiscalYearID or @FiscalYearID = 0)
) X
GROUP BY DepartmentID
	,AccountID
	,FiscalYearID
	,FiscalMonthID

exec [fw].[procFactMonthlyYTDPriorYearUpdate] @factTableName = 'fw.FactStatisticSampledMonthly',@keyNameCSV = 'AccountID',@measureNameCSV = 'Amount',@fiscalYearID  = 0,@timeClassID = 22,@isDebugOnly = 0
END
END
IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE  #EfficiencyFactorScope
GO


---------------------------------------------

-- fw.procStatisticSampledInsertDaily
/**************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI			Description
** 1		2016-07-11	gforeman	B-12396		Handle stats that exist in multiple data sources (dupe handling)
** 2		2016-09-16	gforeman	D-04861		Skip calculating actuals in certain cases
** 3		2016-10-12	mholov		B-12970		Pull from Baseline Target time class
** 4		2016-12-13	mholov		B-13783		Reversed actuals sampling order
** 5		2016-12-17	mholov		B-13509		Pull Budgeted amounts from monthly table	
** 6		2017-01-13	apukii		D-05426		Removed filtering departments by mappings
** 7		2017-01-31	akozlov		B-13926		Added department filter
** 8		2017-02-08  gforeman	B-14308		Added year filter
** 9		2017-03-06  gforeman	B-14693		Cancel sampling if daily disabled
** 10		2017-05-01	gforeman	B-15551		Include non-PR driver departments in sampling
** 11		2017-05-02	gforeman	B-15551		Remove primary statistics join so that all statistics are sampled
** 12		2017-06-14	ipetriv					Added additional filter on values to omit 0 rows
** 13		2017-08-29 	ipetriv		B-16798		Add using of Budget Adjustment.
** 14		2018-02-22	ipetriv 	D-06786		add department calculation for TC = 2 if dept is not in PR , Dept is in Budget Allocation
** 15		2018-03-08 	ipetriv		B-18793		PR - Daily processing post action 2 week run
** 16		2018-03-08 	ipetriv		D-07329		removed part of code, that delete non PR department from staging table
** 17		2018-06-04 	ipetriv		TK-58558	added "distinct" selection of dates in case of recalcu;lation for 2 weeks
** 18       2018-10-18  OV          D-07753     fix: daily and charged-based queries filtered by @dates (removed @FiscalYearID filter)
** 19       2018-10-23  OV          D-07753     fix: PR fails to populate daily charge-based statistics on the first pay period of the fiscal year
** 20       2019-02-20  OV          D-08116     fix: PR delete part ton filtered by PayPeriod
** 21       2019-03-12  OV          TK-71197    Table variables replaced with temp tables
** 22       2019-04-23  OV          B-20579     Allow clients to input daily budget - Statistics
** 23       2019-04-25  OV          B-20579     sampled 0 data for Statistic (except actual)
** 24       2019-07-16  OV          B-23482     Use Budget Adjustments for Daily and PayPeriod
** 25       2019-08-08  vfay        D-08668     Add Joins on DateID in budget reallocation part
** 26       2020-01-28  IH          TK-82833    Increase a deletion size from 10K to 100K
** 27       2020-03-10  HV          D-09170     fw.procStatisticSampledInsertDaily is filling log file in tempdb caused by the use of temp variables
** 28       2020-03-18  HV          TK-84583    PR Statistics Daily sampling: data is sampling incorrectly for first Pay Period days in some cases
                                    D-09470     PR Statistics Daily sampling: budget adjustments are not applied for first Pay Period days if it belongs to 2 months
									TK-84785    Statistics Sampling daily: Baseline Target values are calculated incorrectly for combinations with budget adjustments
** 29		2020-11-25  BS			JAZZ-6398	PR Process is timing out due to long running proc fw.procStatisticSampledInsertDaily
** 30		2022-11-22  HV			JAZZ-44508	Automated Daily PR processing doesn't calculate future target, when system center processing does
** 31		2023-02-03	KF			JAZZ-48413	Charge Based Statistics Modals Performance Improvement- Bug Fixing
** 32		2023-02-21	KF			JAZZ-50593	MBPR PHPUOS: Accounts with 0 charge based UOS are shown with link
** 33		2024-02-23	HV			JAZZ-67657	[RowId] Convert fw.FactStatisticSampledDaily.Rowid to bigint
*************************************************************/
CREATE proc [fw].[procStatisticSampledInsertDaily] 
	@departmentIDs nvarchar(max) = null,
	@fiscalYearID int = 0,
	@isCalcDaily bit = 0,
	@isPrMetricConfigurationOn bit = 0
with recompile
as
	IF OBJECT_ID('tempdb..#DailyCalcPeriodsScope') IS NOT NULL DROP TABLE #DailyCalcPeriodsScope
    
	DECLARE @currentDateOverride nvarchar(max) = (SELECT Value FROM [pi].[SystemSetting] WHERE Name = 'Current Date Override')
	DECLARE @currentDate date =  CASE 
								WHEN @currentDateOverride = '' THEN CAST(GETDATE() AS DATE)
								ELSE CAST (@currentDateOverride AS DATE) 
								END
	DECLARE @yesterday_date date = DATEADD(DAY, - 1, @currentDate) 

	create table #DailyCalcPeriodsScope (PayPeriodID int primary key,PayCycleID int,PeriodStartCalendarDate date,PeriodEndCalendarDate date)
    
	insert into #DailyCalcPeriodsScope (PayPeriodID,PayCycleID,PeriodStartCalendarDate,PeriodEndCalendarDate) 
	select PayPeriodID,PayCycleID,PeriodStartCalendarDate,PeriodEndCalendarDate
	from fw.DimPayPeriod
	where
		(@isCalcDaily = 1 and @yesterday_date BETWEEN PeriodStartCalendarDate and PeriodEndCalendarDate)
		or
		(@isCalcDaily = 0 and (FiscalYearIDSecond = @fiscalYearID or @fiscalYearID = 0))
	
	IF OBJECT_ID('tempdb..#departmentsBudgetAllocations') IS NOT NULL DROP TABLE #departmentsBudgetAllocations
	create table #departmentsBudgetAllocations (val int primary key)

	IF OBJECT_ID('tempdb..#FDPSD') IS NOT NULL DROP TABLE #FDPSD

	CREATE TABLE #FDPSD (DepartmentID int primary key)
	insert into #FDPSD
	select distinct DriverDepartmentID as DepartmentID
	from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache

	insert into #departmentsBudgetAllocations (val)
	select 
		SourceDepartmentID as DepartmentID 
	from mr.BudgetReallocationAdjustment a
	inner join mr.BudgetReallocation r on r.BudgetReallocationGUID=a.BudgetReallocationGUID
	inner join FW.DimDepartment d on d.DepartmentID = r.TargetDepartmentID and d.IsPR = 1
	where SourceDepartmentID <> 0 and r.Archived = 0
		union  -- unique
	select 
		TargetDepartmentID as DepartmentID
	from mr.BudgetReallocationAdjustment a
	inner join mr.BudgetReallocation r on r.BudgetReallocationGUID=a.BudgetReallocationGUID
	inner join FW.DimDepartment d on d.DepartmentID = r.SourceDepartmentID and d.IsPR = 1 -- Filtering all departments that move data FROM selected
	where TargetDepartmentID <> 0 and r.Archived = 0

	--delete existing data
	if (@fiscalYearID = 0 and @isCalcDaily = 0) begin
		truncate table fw.FactStatisticSampledDaily
	end else begin
		while exists(select null from fw.FactStatisticSampledDaily fssd (nolock) 
			inner join #DailyCalcPeriodsScope ps on fssd.PayPeriodID = ps.PayPeriodID) begin
			delete top (500000) fssd
			from fw.FactStatisticSampledDaily fssd
			inner join #DailyCalcPeriodsScope ps on fssd.PayPeriodID = ps.PayPeriodID
		end

		DECLARE @nextRowID BIGINT
		SELECT @nextRowID = ISNULL((SELECT MAX(RowID) FROM fw.FactStatisticSampledDaily), 1)
		DBCC CHECKIDENT('fw.FactStatisticSampledDaily','RESEED', @nextRowID);
	end

	--cancel if not using daily
	if (not exists(select 1 from pi.SystemSetting where Name = 'PR Daily Enabled' and Value = '1')) begin return end
		
	--pull new data - daily statistics
	IF OBJECT_ID('tempdb..#TEMPSTATISTIC') IS NOT NULL DROP TABLE #TEMPSTATISTIC

	create table #TEMPSTATISTIC (DepartmentID int, AccountID int, PayPeriodID int, DateID int, TimeClassID int, Units money)
	insert into #TEMPSTATISTIC (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units)
	select
		stat.DepartmentID,
		stat.AccountID,
		PP.PayPeriodID,
		stat.DateID,
		stat.TimeClassID,
		SUM(STAT.Value) as Units
	from
		[int].[FactSharedImportDailyStatistics] stat
		inner join [fw].[DimDate] DATE on stat.DateID=DATE.DateID
		inner join [fw].[DimDepartment] D on D.Departmentid = STAT.DepartmentID
		inner join [fw].[DimPayPeriod] PP on D.PayCycleID=PP.PayCycleID and DATE.CalendarDateTime between PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate
		inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID and ((date.CalendarDateTime <= @yesterday_date and @isCalcDaily = 1) or @isCalcDaily = 0)
		left join #FDPSD FDPSD on FDPSD.DepartmentID = STAT.DepartmentID
	where 
		PP.PayPeriodID != 0
		and STAT.Isdeleted = 0
		and (D.IsPR = 1 or FDPSD.DepartmentID is not null)
		and stat.DepartmentID != 0
		and stat.TimeClassID = 1

	group by
		stat.DepartmentID,
		stat.AccountID,
		PP.PayPeriodID,
		stat.DateID,
		stat.TimeClassID

    --pull new data - charge-based actuals where not already sampled
	insert into #TEMPSTATISTIC (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units)
	select
		STAT.DepartmentID,
		STAT.AccountID,
		pp.PayPeriodID,
		STAT.DateID,
		1 as TimeClassID,
		SUM(STAT.Value) AS Units
	from
		[fw].[FactChargeBasedStatistics] STAT
		inner join [fw].[DimDate] DATE on STAT.DateID=DATE.DateID
		inner join [fw].[DimDepartment] DEPT on STAT.DepartmentID=DEPT.DepartmentID
		inner join [fw].[DimPayPeriod] PP on DEPT.PayCycleID=PP.PayCycleID and DATE.CalendarDateTime between PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate
		inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID and ((date.CalendarDateTime <= @yesterday_date and @isCalcDaily = 1) or @isCalcDaily = 0)
		left join #FDPSD FDPSD on FDPSD.DepartmentID = STAT.DepartmentID
		left join #TEMPSTATISTIC ex ON ex.DepartmentID = STAT.DepartmentID and ex.AccountID = STAT.AccountID and ex.PayPeriodID = PP.PayPeriodID and ex.DateID = STAT.DateID and ex.TimeClassID = 1
	where
		PP.PayPeriodID != 0
		and STAT.IsDeleted = 0
		and (DEPT.IsPR = 1 or FDPSD.DepartmentID is not null)
		and STAT.DepartmentID != 0
		and ex.DepartmentID IS NULL  

	group by 
		STAT.DepartmentID,
		STAT.AccountID,
		PP.PayPeriodID,
		STAT.DateID;	
		
	IF OBJECT_ID('tempdb..#StatisticSampledMonthlyStaging') IS NOT NULL  DROP TABLE #StatisticSampledMonthlyStaging
	CREATE TABLE #StatisticSampledMonthlyStaging (RowID bigint identity(1,1),AccountID int, DepartmentID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Amount decimal(19,4), isDeleted bit, isSystemGenerated bit)		
	 
	IF OBJECT_ID('tempdb..#StatisticsDaily') IS NOT NULL  DROP TABLE #StatisticsDaily

	   select
			FACT.DepartmentID,
			FACT.AccountID,
			DT.DateID,
			FACT.TimeClassID,
			PP.PayPeriodID,
			SUM(FACT.Value) AS Units
       into #StatisticsDaily
	   from
			int.FactSharedImportDailyStatistics FACT
			inner join [fw].[DimDepartment] D on D.Departmentid = FACT.DepartmentID	           
			inner join [fw].[DimDate] DT on DT.DateID = FACT.dateID
			inner join [fw].[DimPayPeriod] PP on pp.PayCycleID = d.PayCycleID and dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate
			inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID
			left join #FDPSD FDPSD ON  FDPSD.DepartmentID = FACT.DepartmentID
			left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID
		where
			 DT.FiscalMonth != 0 
			and DT.FiscalYear != 0
			and FACT.IsDeleted = 0
			and (D.IsPR = 1 or FDPSD.DepartmentID is not null or dba.val is not null)
			and FACT.TimeClassID = 2
			and FACT.DepartmentID != 0

		group by 
			FACT.DepartmentID,
			FACT.AccountID,
			DT.DateID,
			FACT.TimeClassID,
			PP.PayPeriodID
------------------------------------------------------------------------------------------------------------------------------------
insert into #StatisticsDaily
	   select
			FACT.DepartmentID,
			FACT.AccountID,
			DT.DateID,
			FACT.TimeClassID,
			PP.PayPeriodID,
			SUM(FACT.Value/PCC.PeriodDays) AS Units
		from
			int.FactStatisticsByPayPeriod FACT 
			inner join [fw].[DimDepartment] D on D.Departmentid = FACT.DepartmentID	       
			inner join fw.DimPayPeriod pp on pp.PayPeriodID = FACT.PayPeriodID    
			inner join [fw].[DimDate] DT on dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate
			left join #StatisticsDaily spp on SPP.PayPeriodID = FACT.PayPeriodID and
			                                SPP.AccountID = FACT.AccountID and
											SPP.DepartmentID = FACT.DepartmentID and
											SPP.TimeClassID = FACT.TimeClassID
			inner join fw.DimPayCycle PCC on PCC.PayCycleID = PP.PayCycleID
			inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID
			left join #FDPSD FDPSD ON  FDPSD.DepartmentID = FACT.DepartmentID
			left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID
         where
			spp.DepartmentID IS NULL
			and DT.FiscalMonth != 0 
			and FACT.FiscalYearID != 0
			and FACT.IsDeleted = 0
			and (D.IsPR = 1 or FDPSD.DepartmentID is not null or dba.val is not null)
			and FACT.TimeClassID = 2
			and FACT.DepartmentID != 0
		group by 
			FACT.DepartmentID,
			FACT.AccountID,
			DT.DateID,
			FACT.TimeClassID,
			PP.PayPeriodID
--------------------------------------------------------------------------------------------------------------------


		insert into #StatisticsDaily
	select
			STAT.DepartmentID,
			STAT.AccountID,
			DT.DateID,
			STAT.TimeClassID,
		    DPC.PayPeriodID,
			SUM(STAT.Value/ dbo.GetDaysInMonth(DT.CalendarDateTime)) AS Units
		from
			int.FactStatistic STAT
			inner join [fw].[DimDepartment] D on D.Departmentid = STAT.Departmentid
			inner join [fw].[DimDate] DT on DT.CalendarMonth = STAT.FiscalMonthID and DT.FiscalYear = STAT.FiscalYearID
			inner join #DailyCalcPeriodsScope dpc on dpc.PayCycleID = d.PayCycleID and dt.CalendarDateTime between dpc.PeriodStartCalendarDate and dpc.PeriodEndCalendarDate
		    left join #StatisticsDaily spp on SPP.PayPeriodID = DPC.PayPeriodID and
			                                SPP.AccountID = STAT.AccountID and
											SPP.DepartmentID = STAT.DepartmentID and
											SPP.TimeClassID = STAT.TimeClassID
            left join #FDPSD FDPSD ON  FDPSD.DepartmentID = STAT.DepartmentID
			left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID
			where
		    spp.DepartmentID is null
			and 
			STAT.FiscalMonthID != 0 
			and STAT.FiscalYearID != 0
			and STAT.isDeleted = 0
		   and (D.IsPR = 1 or FDPSD.DepartmentID is not null or dba.val is not null)
		    and STAT.TimeClassID = 2
			and STAT.DepartmentID != 0

		group by 
			STAT.DepartmentID,
			STAT.AccountID,
			DT.DateID,
			STAT.TimeClassID,
			DPC.PayPeriodID



insert into #TEMPSTATISTIC (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units)
    select G.DepartmentID, AccountID, G.PayPeriodID, G.DateID, G.TimeClassID, G.Units
    from #StatisticsDaily G

---------------------------------------------------------------------------------------------------------------------
declare @iteration int = 1 


DECLARE @BudgetReallocationGUID uniqueidentifier,@date datetime,@BudgetReallocationType varchar(50)

PRINT '-------- Vendor Products Report --------';  

DECLARE BRA_cursor CURSOR FOR   
SELECT DISTINCT BudgetReallocationGUID,date,BudgetReallocationType
FROM fw.BudgetReallocationWithDefinedType BR
	INNER JOIN  [fw].[DimDate] DD ON DD.CalendarMonth = BR.FiscalMonthID AND DD.FiscalYear = BR.FiscalYearID
	INNER JOIN  #DailyCalcPeriodsScope DCPS ON DD.CalendarDateTime BETWEEN DCPS.PeriodStartCalendarDate AND DCPS.PeriodEndCalendarDate
WHERE BR.BudgetReallocationType IS NOT NULL
ORDER BY date

OPEN BRA_cursor  

FETCH NEXT FROM BRA_cursor   
INTO @BudgetReallocationGUID,@date,@BudgetReallocationType   

WHILE @@FETCH_STATUS = 0  
BEGIN  

IF @BudgetReallocationType = 'ReallocateSingle'
	BEGIN -- Insert rows with "correcting" values 
		UPDATE STT
		SET Units = STT.Units + Change/dbo.GetDaysInMonth(dd.CalendarDateTime)  ----------------------
		FROM #TEMPSTATISTIC STT
			INNER JOIN fw.dimDate dd on stt.DateID = dd.DateID
			INNER JOIN [mr].[BudgetReallocation] b ON b.TargetDepartmentID = stt.DepartmentID and b.TargetAccountID = stt.AccountID and b.FiscalYearID = dd.FiscalYear
			INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and ba.FiscalMonthID = dd.CalendarMonth	
		WHERE ba.Change <> 0
			  and b.BudgetReallocationGUID = @BudgetReallocationGUID
			  and ba.UnitTypeID = 145
			  and STT.TimeClassID = 2
			  and b.Archived = 0

        UPDATE STT
        SET Units = STT.Units - Change/dbo.GetDaysInMonth(dd.CalendarDateTime)  ---------------------------
		FROM #TEMPSTATISTIC STT
			INNER JOIN fw.dimDate dd on stt.DateID = dd.DateID 
			INNER JOIN [mr].[BudgetReallocation] b ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and b.FiscalYearID = dd.FiscalYear
			INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and ba.FiscalMonthID = dd.CalendarMonth	
		WHERE ba.Change <> 0
			  and b.BudgetReallocationGUID = @BudgetReallocationGUID
			  and ba.UnitTypeID = 145
			  and STT.TimeClassID = 2
			  and b.Archived = 0

        INSERT INTO #TEMPSTATISTIC	(DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units)
		SELECT 
			b.SourceDepartmentID as DepartmentID,
			b.SourceAccountID as AccountID,
			pp.PayPeriodID as PayPeriodID,
			dd.DateID as DateID,
			2 as TimeClassID,
			SUM((Change/dbo.GetDaysInMonth(dd.CalendarDateTime)) * -1) as Units			
		FROM [mr].[BudgetReallocation] b
			INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID	
			INNER JOIN [fw].[DimDate] dd on dd.FiscalYear = b.FiscalYearID and dd.CalendarMonth = ba.FiscalMonthID
			INNER JOIN [fw].[DimDepartment] dep on b.SourceDepartmentID = dep.DepartmentID
			INNER JOIN [fw].[DimPayPeriod] pp on pp.PayCycleID = dep.PayCycleID and dd.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate
			INNER JOIN #DailyCalcPeriodsScope dcp on dcp.PayPeriodID = pp.PayPeriodID
			LEFT JOIN #TEMPSTATISTIC stt
					  on b.SourceDepartmentID = stt.DepartmentID and 
						 b.SourceAccountID = stt.AccountID and
						 stt.TimeClassID = 2 and
						 stt.DateID = dd.DateID
			WHERE ba.Change <> 0 and
				  b.BudgetReallocationGUID = @BudgetReallocationGUID and
				  stt.DepartmentID is null and 
				  ba.UnitTypeID = 145 and
				  b.Archived = 0				  
			GROUP BY b.SourceDepartmentID,
					b.SourceAccountID,
					pp.PayPeriodID,
					dd.DateID
UNION All
		SELECT 
				b.TargetDepartmentID as DepartmentID,
				b.TargetAccountID as AccountID,
				pp.PayPeriodID as PayPeriodID,
				dd.DateID as DateID,
				2 as TimeClassID,
				sum(Change/dbo.GetDaysInMonth(dd.CalendarDateTime)) as Units				
		FROM [mr].[BudgetReallocation] b
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		INNER JOIN [fw].[DimDate] dd on dd.FiscalYear = b.FiscalYearID and dd.CalendarMonth = ba.FiscalMonthID
		INNER JOIN [fw].[DimDepartment] dep on b.TargetDepartmentID = dep.DepartmentID
		INNER JOIN [fw].[DimPayPeriod] pp on pp.PayCycleID = dep.PayCycleID and dd.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate
		INNER JOIN #DailyCalcPeriodsScope dcp on dcp.PayPeriodID = pp.PayPeriodID
		LEFT JOIN #TEMPSTATISTIC stt
				  ON b.TargetDepartmentID = stt.DepartmentID and 
					 b.TargetAccountID = stt.AccountID and
					 stt.TimeClassID = 2 and
					 stt.DateID = dd.DateID
		WHERE ba.Change <> 0 and
			  b.BudgetReallocationGUID = @BudgetReallocationGUID and 
			  stt.DepartmentID is null and 
			  ba.UnitTypeID = 145 and 
			  b.Archived = 0
		group by b.TargetDepartmentID,
				 b.TargetAccountID,
				 pp.PayPeriodID,
				 dd.DateID		
	------------------
			
	END

IF @BudgetReallocationType = 'ReallocateMulti'
	BEGIN
		Update stt
		set stt.Units = stt_src.Units + stt.Units 
		FROM #TEMPSTATISTIC STT
		inner join fw.DimDate dd on dd.DateID = stt.DateID
		INNER JOIN [mr].[BudgetReallocation] b on b.TargetDepartmentID = stt.DepartmentID and b.TargetAccountID = stt.AccountID and b.FiscalYearID = dd.FiscalYear
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and dd.CalendarMonth = ba.FiscalMonthID
		INNER JOIN #TEMPSTATISTIC STT_SRC 
					ON STT_SRC.DepartmentID = b.SourceDepartmentID and 
					   STT_SRC.AccountID = b.SourceAccountID and 
					   stt.TimeClassID = stt_src.TimeClassID and 
					   STT_SRC.DateID = stt.DateID
		where
			b.BudgetReallocationGUID = @BudgetReallocationGUID and 
			ba.UnitTypeID = 145 and 
			ba.Change <> 0 and 
			stt.TimeClassID = 2 and 
			b.Archived = 0

INSERT INTO #TEMPSTATISTIC	(DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units)
	SELECT --'Y',
		b.TargetDepartmentID as DepartmentID,
		b.TargetAccountID as AccountID,
		pp.PayPeriodID as PayPeriodID,
		dd.DateID as DateID,
		2 as TimeClassID,
		SUM(STT_SRC.Units) as Units         -----------------
	FROM [mr].[BudgetReallocation] b
	INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
	INNER JOIN [fw].[DimDate] dd on dd.FiscalYear = b.FiscalYearID and dd.CalendarMonth = ba.FiscalMonthID
	INNER JOIN [fw].[DimDepartment] dep on b.TargetDepartmentID = dep.DepartmentID
	INNER JOIN [fw].[DimPayPeriod] pp on pp.PayCycleID = dep.PayCycleID and dd.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate
	INNER JOIN #DailyCalcPeriodsScope dcp on dcp.PayPeriodID = pp.PayPeriodID
	INNER JOIN #TEMPSTATISTIC STT_SRC
			   ON STT_SRC.DepartmentID = b.SourceDepartmentID and 
				  STT_SRC.AccountID = b.SourceAccountID and
				  STT_SRC.TimeClassID = 2 and 
				  STT_SRC.DateID = dd.DateID
	LEFT JOIN #TEMPSTATISTIC STT
				ON STT.DepartmentID = b.TargetDepartmentID and 
				   STT.AccountID = b.TargetAccountID and  
				   STT.TimeClassID = 2 and 
				   STT.DateID = dd.DateID
	where stt.DepartmentID is null and 
		  ba.Change <> 0 and 
		  ba.UnitTypeID = 145 and 
		  b.BudgetReallocationGUID = @BudgetReallocationGUID and 
		  b.Archived = 0
	GROUP BY 
		b.TargetDepartmentID,
		b.TargetAccountID,
		pp.PayPeriodID,
		dd.DateID

		UPDATE STT_SRC
		SET stt_src.Units = 0
		FROM #TEMPSTATISTIC STT_SRC
			INNER JOIN fw.DimDate dd on dd.DateID = STT_SRC.DateID			 
			INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = STT_SRC.DepartmentID and b.SourceAccountID = STT_SRC.AccountID and dd.FiscalYear = b.FiscalYearID
			INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and ba.FiscalMonthID = dd.CalendarMonth
			LEFT JOIN #TEMPSTATISTIC STT
					   ON STT.DepartmentID = b.TargetDepartmentID and 
						  STT.AccountID = b.TargetAccountID and 
						  STT.TimeClassID = 2 and
						  STT.DateID = STT_SRC.DateID
			where b.BudgetReallocationGUID = @BudgetReallocationGUID and 
				  ba.UnitTypeID = 145 and 
				  Change <> 0 and 
				  b.Archived = 0 
	END
--	ELSE
	IF @BudgetReallocationType = 'AdjustMontly'
	BEGIN
	
	UPDATE STT
	SET stt.Units = stt.Units+Change/dbo.GetDaysInMonth(dd.CalendarDateTime)
	FROM #TEMPSTATISTIC STT
	inner join fw.DimDate dd on dd.DateID = stt.DateID
	INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and dd.FiscalYear = b.FiscalYearID
	INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and ba.FiscalMonthID = dd.CalendarMonth	
	where 
		b.BudgetReallocationGUID = @BudgetReallocationGUID
		and ba.UnitTypeID = 145
		and ba.Change <> 0
		and TimeClassID = 2
		and b.Archived = 0

   INSERT INTO #TEMPSTATISTIC (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units)
	SELECT 
		b.SourceDepartmentID as DepartmentID,
		b.SourceAccountID as AccountID,
		pp.PayPeriodID as PayPeriodID,
		dd.DateID as DateID,
		2 as TimeClassID,
		SUM(Change/dbo.GetDaysInMonth(dd.CalendarDateTime)) as Units
	FROM [mr].[BudgetReallocation] b
	INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
	INNER JOIN [fw].[DimDate] dd on dd.FiscalYear = b.FiscalYearID and dd.CalendarMonth = ba.FiscalMonthID
	INNER JOIN [fw].[DimDepartment] dep on b.SourceDepartmentID = dep.DepartmentID
	INNER JOIN [fw].[DimPayPeriod] pp on pp.PayCycleID = dep.PayCycleID and dd.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate	
	INNER JOIN #DailyCalcPeriodsScope dcp on dcp.PayPeriodID = pp.PayPeriodID
	LEFT JOIN #TEMPSTATISTIC stt
			  ON b.SourceDepartmentID = stt.DepartmentID and
				 b.SourceAccountID = stt.AccountID and
				 stt.TimeClassID = 2 and
				 stt.DateID = dd.DateID
	where ba.Change <> 0
		and stt.DepartmentID is null
		and ba.UnitTypeID = 145
		and b.BudgetReallocationGUID = @BudgetReallocationGUID
		and b.Archived = 0
	GROUP BY 
		b.SourceDepartmentID,
		b.SourceAccountID,
		pp.PayPeriodID,
		dd.DateID
	END

	IF @BudgetReallocationType = 'ManualFile'
	BEGIN
		UPDATE STT
		SET stt.Units = ba.NewSourceValue/dbo.GetDaysInMonth(dd.CalendarDateTime)
		FROM #TEMPSTATISTIC STT
		inner join fw.Dimdate dd on STT.DateID = dd.DateID
		INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and b.FiscalYearID = dd.FiscalYear 
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and ba.FiscalMonthID = dd.CalendarMonth
		where 
			b.BudgetReallocationGUID = @BudgetReallocationGUID
			and ba.UnitTypeID = 145
			and b.Archived = 0
			and STT.TimeClassID = 2
			and ba.Change <> 0
		
		INSERT INTO #TEMPSTATISTIC (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units)
		SELECT 
			b.SourceDepartmentID as DepartmentID,
			b.SourceAccountID as AccountID,
            pp.PayPeriodID as PayPeriodID,
			dd.DateID as DateID,
		    2 as TimeClassID,
			SUM(NewSourceValue/dbo.GetDaysInMonth(dd.CalendarDateTime)) as Value   ---------------------------
		FROM [mr].[BudgetReallocation] b
		INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID
		INNER JOIN [fw].[DimDate] dd on dd.FiscalYear = b.FiscalYearID and dd.CalendarMonth = ba.FiscalMonthID
		INNER JOIN [fw].[DimDepartment] dep on b.SourceDepartmentID = dep.DepartmentID
		INNER JOIN [fw].[DimPayPeriod] pp on pp.PayCycleID = dep.PayCycleID and dd.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate	
		INNER JOIN #DailyCalcPeriodsScope dcp on dcp.PayPeriodID = pp.PayPeriodID		
		LEFT JOIN #TEMPSTATISTIC stt
				  ON b.SourceDepartmentID = stt.DepartmentID and 
				     b.SourceAccountID = stt.AccountID and 
					 stt.TimeClassID = 2 and
					 stt.DateID = dd.DateID
		where ba.Change <> 0 and 
			stt.DepartmentID is null and 
			ba.UnitTypeID = 145 and 
			b.BudgetReallocationGUID = @BudgetReallocationGUID and 
			b.Archived = 0			
		GROUP BY b.SourceDepartmentID,
			b.SourceAccountID,
            pp.PayPeriodID,
			dd.DateID
	END

	set @iteration  = @iteration +1

	FETCH NEXT FROM BRA_cursor   
	INTO @BudgetReallocationGUID,@date,@BudgetReallocationType   
END   
CLOSE BRA_cursor;  
DEALLOCATE BRA_cursor;  

    --calculate baseline target
    declare @targetType int = (select Value from pi.SystemSetting where Name = 'Target Basis')
    if (@targetType = 2) begin
		--baseline target is based on budget, pull from monthly data
        insert into #TEMPSTATISTIC (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units)
        select DepartmentID, AccountID, PayPeriodID, DateID, 20, Units
        from #TEMPSTATISTIC
        where TimeClassID = 2
    end else if(@targetType = 10) begin
		--baseline target is based on rolling period average, pull from pay period data  
        with groupedBaselineTargetStats as(
			select
				STAT.DepartmentID,
				STAT.AccountID,
				STAT.PayPeriodID,
				DT.DateID,
				STAT.TimeClassID,
				SUM(STAT.Units) AS Units
			from
				fw.FactStatisticSampledPayPeriod STAT
				inner join [fw].[DimPayPeriod] PP on PP.PayPeriodID = STAT.PayPeriodID
				inner join [fw].[DimDate] DT on DT.CalendarDateTime between PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate
				inner join [fw].[DimDepartment] D on D.DepartmentID = STAT.DepartmentID
				inner join #DailyCalcPeriodsScope DCPS on DCPS.PayPeriodID = PP.PayPeriodID
				left join #FDPSD FDPSD ON  FDPSD.DepartmentID = STAT.DepartmentID
				left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID
			where
				STAT.PayPeriodID != 0
				and STAT.IsDeleted = 0
				and (D.IsPR = 1 or FDPSD.DepartmentID is not null or dba.val is not null)
				and stat.TimeClassID = 20
				and stat.DepartmentID != 0
			group by 
				STAT.DepartmentID,
				STAT.AccountID,
				STAT.PayPeriodID,
				DT.DateID,
				STAT.TimeClassID
		)
        insert into #TEMPSTATISTIC (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units)
        select DepartmentID, AccountID, G.PayPeriodID, DateID, TimeClassID, Units / PP.PeriodDays
        from groupedBaselineTargetStats G
        inner join fw.DimPayPeriod PP on PP.PayPeriodID = G.PayPeriodID
    end

IF OBJECT_ID('tempdb..#departmentsBudgetAllocations') IS NOT NULL DROP TABLE #departmentsBudgetAllocations

-- Fill Charge Based Statistics Sampled Keys
IF @isPrMetricConfigurationOn = 1
BEGIN
	IF @FiscalYearID = 0 AND @yesterday_date IS NULL
	BEGIN
		TRUNCATE TABLE fw.FactChargeBasedStatisticsDailyKeys
	END
	ELSE
	BEGIN
		DELETE F FROM fw.FactChargeBasedStatisticsDailyKeys F
		INNER JOIN #DailyCalcPeriodsScope PP ON PP.PayPeriodID = F.PayPeriodID
	END

	INSERT INTO fw.FactChargeBasedStatisticsDailyKeys (DepartmentID, AccountID, PayPeriodID, DateID)
	SELECT DISTINCT CB.DepartmentID, CB.AccountID, PP.PayPeriodID, CB.DateID
	FROM fw.FactChargeBasedStatistics CB
	INNER JOIN fw.DimDate DT ON DT.DateID = CB.DateID
	INNER JOIN fw.DimDepartment DEPT ON DEPT.DepartmentID = CB.DepartmentID
	INNER JOIN #DailyCalcPeriodsScope PP ON PP.PayCycleID = DEPT.PayCycleID AND DT.CalendarDateTime BETWEEN PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate 
	LEFT JOIN int.FactSharedImportDailyStatistics DS ON DS.DepartmentID = CB.DepartmentID AND DS.AccountID = CB.AccountID AND DS.DateID = CB.DateID AND DS.TimeClassID = 1
	LEFT JOIN #FDPSD FDPSD on FDPSD.DepartmentID = CB.DepartmentID
	WHERE
		CB.IsDeleted = 0
		AND CB.DepartmentID != 0
		AND PP.PayPeriodID != 0
		AND CB.Value != 0
		AND DS.RowID IS NULL
		AND (DEPT.IsPR = 1 OR FDPSD.DepartmentID IS NOT NULL)
END

IF OBJECT_ID('tempdb..#DailyCalcPeriodsScope') IS NOT NULL DROP TABLE #DailyCalcPeriodsScope

IF OBJECT_ID('tempdb..#TEMPFINAL') IS NOT NULL DROP TABLE #TEMPFINAL
begin
SELECT DepartmentID, AccountID, TimeClassID, SUM(Units) as Units ,DateID, PayPeriodID  into #TEMPFINAL
FROM (
	SELECT stt.DepartmentID,stt.AccountID,DateID,TimeClassID,Units, stt.PayPeriodID
	from #TEMPSTATISTIC stt
	UNION ALL	
	SELECT stat.DepartmentID,stat.AccountID, stat.DateID, stat.TimeClassID, 0 as Units, stat.PayPeriodID
	from #StatisticsDaily stat 
	WHERE 	stat.Units != 0
) SubSelect
GROUP BY DepartmentID,AccountID,TimeClassID, DateID, PayPeriodID
end

	--push to fact table
	insert into fw.FactStatisticSampledDaily (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units)	
	select
		DepartmentID,
		AccountID,
		PayPeriodID,
		DateID,
		TimeClassID,
		SUM(Units)
	from
		#TEMPFINAL temp
    WHERE TimeClassID IS NOT NULL
	group by
		DepartmentID,
		AccountID,
		PayPeriodID,
		DateID,
		TimeClassID

delete from fw.FactStatisticSampledDaily where TimeClassID = 1 and Units = 0

IF OBJECT_ID('tempdb..#TEMPSTATISTIC') IS NOT NULL DROP TABLE #TEMPSTATISTIC
IF OBJECT_ID('tempdb..#StatisticsDaily') IS NOT NULL DROP TABLE #StatisticsDaily
IF OBJECT_ID('tempdb..#TEMPFINAL') IS NOT NULL DROP TABLE #TEMPFINAL
GO


---------------------------------------------

-- fw.procStatisticSampledInsertMonthly
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2014-09-03	MS		B-02863	Removing the parameter from the YTD proc call
** 2		2014-09-24	MS		B-02191	Removing the IsStat=1 filter so that Units loaded on GL accounts shared with Dollars can be pulled in
** 3		2014-10-15	GF		B-02951	Rollback CID 1 for backwards compatibility
** 4		2014-10-15	GF		B-02951	Re-apply CID 1 only if latest data model for MR
** 5		2016-08-09	AK		B-12405	Added merge with FactChargeBasedStatisticsByPostDate
** 6		2016-09-07	MH		B-12791	Updated FactChargeBasedStatisticsByPostDate table name to FactChargeBasedStatisticsMonthly
** 7		2016-09-22	AK		B-11845	Added procFactStatisticSampledBaselineTargetUpdate
** 8		2016-10-11	MH		TK-33892 Fixed merge statement
** 9		2016-12-13	NL		B-13759	Added fiscalYearID param and filtering
** 10		2017-02-20	GF		D-05545	Move duplicate record handling from YTD into sampling + general cleanup
** 11		2017-03-06	GF		B-14693	Added baseline target year filter
** 12		2017-05-24	IP		B-15086	Sampling Performance Improvements. Using temp tables insead of fw.FactStatisticSampledMonthly.
** 13		2017-06-15	IP		B-15086 Modify SP to use unique temp table
** 14		2017-07-19	IP		TK-45395 Fixed conditions of merge statement (include isSystemGenerated column)
** 15		2017-27-26	IP		B-16752	Added units Budget Adjustment
** 16		2017-08-02	IP		D-06232 Fixed generated stats for MR (include charge-based statistics)
** 17		2017-08-29 	ip		B-16798		Add using of Budget Adjustment.
** 18		2017-08-29 	ip		D-06508		Preventing appearing duplicate rows in staging table
*************************************************************/
CREATE proc [fw].[procStatisticSampledInsertMonthly] 
	@fiscalYearID smallint = 0
as	
	IF OBJECT_ID('tempdb..#StatisticSampledMonthlyStaging') IS NOT NULL  DROP TABLE ##StatisticSampledMonthlyStaging
	IF OBJECT_ID('fw.StatisticSampledMonthlyStagingWithCalcs') IS NOT NULL  DROP TABLE fw.StatisticSampledMonthlyStagingWithCalcs
	--run custom scripts
	exec client.procStatisticSampledInsertMonthlyPreprocess
	
	--push new data to fact table: statistics
	
	CREATE TABLE #StatisticSampledMonthlyStaging (RowID bigint identity(1,1),AccountID int, DepartmentID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Amount decimal(19,4), isDeleted bit, isSystemGenerated bit)		
	insert into #StatisticSampledMonthlyStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount)
	exec fw.PrepareStatistics @FiscalYearID,0

	--push new data to fact table: charge-based statistics
	merge 
		#StatisticSampledMonthlyStaging as fact
	using 
		(select DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value from fw.FactChargeBasedStatisticsMonthly where IsDeleted = 0 and Value != 0 and (FiscalYearID = @fiscalYearID OR @fiscalYearID = 0)) as source  -- CID 9, added fiscalYearID filter
	on
		fact.DepartmentID = source.DepartmentID and fact.AccountID = source.AccountID and fact.FiscalYearID = source.FiscalYearID and fact.FiscalMonthID = source.FiscalMonthID and fact.TimeClassID = 1 and (fact.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) -- CID 9, added fiscalYearID filter
	when not matched then
		insert (FiscalYearID, FiscalMonthID, DepartmentID, AccountID, TimeClassID, Amount) values (source.FiscalYearID, source.FiscalMonthID, source.DepartmentID, source.AccountID, 1, source.Value);		
		
	--run calculations
	exec fw.procFactMonthlyMergeDuplicates '#StatisticSampledMonthlyStaging', 'AccountID', 'Amount', @fiscalYearID, 0, 0
    exec fw.procFactStatisticSampledBaselineTargetUpdate @fiscalYearID = @fiscalYearID
	exec fw.procFactMonthlyYTDPriorYearUpdateStaging 'fw.FactStatisticSampledMonthly','#StatisticSampledMonthlyStaging', 'AccountID', 'Amount', @fiscalYearID, 0, 0
	
	IF @fiscalYearID = 0 
	BEGIN
	truncate table fw.FactStatisticSampledMonthly
	INSERT INTO fw.FactStatisticSampledMonthly With (TABLOCKX) (
			DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID,
			Amount,
			AmountYTD,
			AmountPriorYear,
			AmountPriorYTD,
			IsDeleted,
			IsSystemGenerated
			)
			SELECT 
			DepartmentID,
			AccountID,
			FiscalYearID,
			FiscalMonthID,
			TimeClassID,
			Amount=SUM(Amount),
			AmountYTD=SUM(AmountYTD),
			AmountPriorYear=SUM(AmountPriorYear),
			AmountPriorYTD=SUM(AmountPriorYTD),
			0 as isDeleted,
			isSystemGenerated=min(isnull(isSystemGenerated,0))
		FROM fw.StatisticSampledMonthlyStagingWithCalcs
		GROUP BY 
		DepartmentID,
			AccountID,
			FiscalYearID,
			FiscalMonthID,
			TimeClassID
	END
ELSE 
	BEGIN
		print 'Starting creating index --- '+convert(varchar(20),GETDATE(),113) 
		CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.StatisticSampledMonthlyStagingWithCalcs (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID)
		print 'Starting transaction --- '+convert(varchar(20),GETDATE(),113) 

		;With src as 
		(
		SELECT 
			DepartmentID,
			AccountID,
			FiscalYearID,
			FiscalMonthID,
			TimeClassID,
			Amount=SUM(Amount),
			AmountYTD=SUM(AmountYTD),
			AmountPriorYear=SUM(AmountPriorYear),
			AmountPriorYTD=SUM(AmountPriorYTD),
			isSystemGenerated=min(isSystemGenerated),
			FTEs=SUM(FTEs),
			FTEsYTD=SUM(FTEsYTD),
			FTEsPriorYear=SUM(FTEsPriorYear),
			FTEsPriorYTD=SUM(FTEsPriorYTD)
		FROM fw.StatisticSampledMonthlyStagingWithCalcs
		GROUP BY 
			DepartmentID,
			AccountID,
			FiscalYearID,
			FiscalMonthID,
			TimeClassID
		)

		MERGE fw.FactStatisticSampledMonthly With (TABLOCKX) AS target
		USING src AS source
			ON source.DepartmentID = target.DepartmentID
				AND source.AccountID = target.AccountID
				AND source.FiscalYearID = target.FiscalYearID
				AND source.FiscalMonthID = target.FiscalMonthID
				AND source.TimeClassID = target.TimeClassID
		WHEN MATCHED AND 
			(target.Amount <> source.Amount
			or target.AmountYTD <> source.AmountYTD
			or target.AmountPriorYear <> source.AmountPriorYear
			or target.AmountPriorYTD <> source.AmountPriorYTD
			or target.IsSystemGenerated <> source.IsSystemGenerated)
			THEN
				UPDATE
				SET target.Amount = source.Amount,
					target.AmountYTD = source.AmountYTD,
					target.AmountPriorYear = source.AmountPriorYear,
					target.AmountPriorYTD = source.AmountPriorYTD,
					target.IsSystemGenerated = source.IsSystemGenerated

		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID,
					Amount,
					AmountYTD,
					AmountPriorYear,
					AmountPriorYTD,
					IsDeleted,
					IsSystemGenerated
					)
				VALUES (
					source.DepartmentID,
					source.AccountID,
					source.FiscalYearID,
					source.FiscalMonthID,
					source.TimeClassID,
					source.Amount,
					source.AmountYTD,
					source.AmountPriorYear,
					source.AmountPriorYTD,
					0,
					isnull(IsSystemGenerated,0)
					)
		WHEN NOT MATCHED BY SOURCE
			AND Target.FiscalYearID = @fiscalYearID		
			THEN
				DELETE;

	END
	IF OBJECT_ID('tempdb..##StatisticSampledMonthlyStaging') IS NOT NULL  DROP TABLE ##StatisticSampledMonthlyStaging
	IF OBJECT_ID('fw.StatisticSampledMonthlyStagingWithCalcs') IS NOT NULL  DROP TABLE fw.StatisticSampledMonthlyStagingWithCalcs
GO


---------------------------------------------

-- fw.procStatisticSampledInsertPayPeriod
/**************************************************************
** Change History
**************************************************************
** CID      Date        Author  WI      Description
** 1        2013-10-03  RA              Changing source table to be [int].[FactStatisticsbyPayPeriod]
**                                      and removing unnecessary lines
** 2        2014-08-20  JG              Adding year filters for performance
** 3        2014-09-03  MS      B-02863 Removing the parameter from the YTD proc call
** 4        2015-02-11  JG              Adding Daily statistics
** 5        2016-01-22  MS      D-03856 Calculate PayPeriodID in Daily section
** 6        2016-01-22  MS      B-11082 Pull in Charge-based and Aggregated daily statistics and exclude GL statistics for these departments
** 7        2016-03-23  MS      B-11274 Exclude list of departments in charge-based mapping table when AccountID=0 and Weight=0
** 8        2016-04-28  AK      B-11864 Added IsPR check
** 9        2016-07-11  GF      B-12396 Handle stats that exist in multiple data sources (dupe handling)
** 10       2016-10-04  MH      B-13126 Added procFactStatisticSampledPayPeriodBaselineTargetUpdate
** 11       2016-12-13  MH      B-13783 Reversed actuals sampling order
** 12       2017-01-31  AK      B-13926 Added department filter
** 13		2017-02-08	GF		B-14308 Added year filter
** 14		2017-02-20	GF		D-05545 Move duplicate record handling from YTD into sampling
** 15		2017-05-01	GF		B-15551 Include non-PR driver departments in sampling
** 16		2017-05-02	GF		B-15551 Remove primary statistics join so that all statistics are sampled
** 17		2017-05-29 	ipetriv	B-15994	Refactored sampling process and implemented using of staging tables
** 18		2017-06-15	IP		B-15086 Modify SP to use unique temp table
** 19		2017-07-19	IP		TK-45395 Fixed conditions of merge statement (include isSystemGenerated column)
** 20		2017-27-26	IP		B-16752	Added units Budget Adjustment
** 21		2017-08-29 	ip		B-16798	Add using of Budget Adjustment.
** 22		2017-10-04 	GF		D-06489	Fix pay period select when running all years
** 23		2017-10-04 	IP		D-06489	Fix departments scope for cases when procedure run for one department (but adjustments could require more)
** 24		2018-02-22	IP 		D-06786	add department calculation for TC = 2 if dept is not in PR , Dept is in Budget Allocation
** 25		2018-05-17	IP 		D-07329	Returning fuctionality to include stats for departments using non-PR driver departments
** 26       2019-04-19  OV      B-20579   Filtered by new column 'TimeClassID' from int.FactSharedImportDailyStatistics
** 27		2020-03-20	vfay	D-08997	[fw].[PrepareStatisticsPayPeriod] is reporting incorrect adjustment amounts
** 28		2020-07-30	HV		JAZZ-2302	YTD PR Calculations Incorrect when Processing Current Year Only
** 29		2020-11-26	KF		JAZZ-7886 Stored procedure fw.procStatisticSampledInsertPayPeriod is timing out
** 30		2023-04-11	HV		JAZZ-52032	Create and fill caching table for charge-based statistics pay period data
** 31		2023-12-04	ishah		JAZZ-62485	Remove @departmentIDs param for procFactPayPeriodYTDPriorYearUpdate_Staging
*************************************************************/
CREATE proc [fw].[procStatisticSampledInsertPayPeriod]
	@fiscalYearID int = 0,
	@isPrMetricConfigurationOn BIT = 0
with recompile
as
	IF OBJECT_ID('fw.StatisticSampledPayPeriodWithCalcs') IS NOT NULL  DROP TABLE fw.StatisticSampledPayPeriodWithCalcs
	IF OBJECT_ID('tempdb..#StatisticSampledPayPeriod') IS NOT NULL DROP TABLE #StatisticSampledPayPeriod	

	create table #StatisticSampledPayPeriod (DepartmentID int, AccountID int, PayPeriodID int, TimeClassID int, Units decimal(18, 6),  isDeleted bit default 0, isSystemGenerated bit default 0)

	create clustered columnstore index cci on #StatisticSampledPayPeriod

	insert into #StatisticSampledPayPeriod (DepartmentID, AccountID, PayPeriodID, TimeClassID, Units)
    exec fw.PrepareStatisticsPayPeriod 	@FiscalYearID,null,0,@isPrMetricConfigurationOn -- Adding Adjustments!

	--run calculations
	exec fw.procFactPayPeriodMergeDuplicates '#StatisticSampledPayPeriod', 'AccountID', 'Units', @fiscalYearID, 0, 0, null
    exec fw.procFactStatisticSampledPayPeriodBaselineTargetUpdate @fiscalYearID = @fiscalYearID
	exec fw.procFactPayPeriodYTDPriorYearUpdate_Staging 'fw.FactStatisticSampledPayPeriod','#StatisticSampledPayPeriod','AccountID', 'Units', @fiscalYearID, 0, 0
	
	--Commented out due to D-07329
	/*	
	--!!!Removing all records where Department is not PR
	delete fact
	from fw.StatisticSampledPayPeriodWithCalcs fact
	inner join fw.dimDepartment d on d.DepartmentID = fact.DepartmentID and d.isPR = 0
	*/
	
	IF @fiscalYearID = 0
	BEGIN
	truncate table fw.FactStatisticSampledPayPeriod
	INSERT INTO fw.FactStatisticSampledPayPeriod With (TABLOCKX) (
			DepartmentID, AccountID, PayPeriodID, TimeClassID,
			Units,
			UnitsYTD,
			UnitsPriorYear,
			UnitsPriorYTD,
			IsDeleted,
			IsSystemGenerated
			)
		SELECT DepartmentID, AccountID, PayPeriodID, TimeClassID,
		Units,
		UnitsYTD,
		UnitsPriorYear,
		UnitsPriorYTD,
		0 as IsDeleted,
		isnull(IsSystemGenerated,0) as IsSystemGenerated
	FROM fw.StatisticSampledPayPeriodWithCalcs
	END
ELSE 
	BEGIN
		print 'Starting creating index --- '+convert(varchar(20),GETDATE(),113) 
		CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.StatisticSampledPayPeriodWithCalcs (DepartmentID, AccountID, PayPeriodID, TimeClassID)
		print 'Starting transaction --- '+convert(varchar(20),GETDATE(),113) 
		;WITH TGT AS (SELECT t.* FROM 
		fw.FactStatisticSampledPayPeriod t With (TABLOCKX)
		inner join fw.DimPayPeriod pp on t.PayPeriodId  = pp.PayPeriodID
		and (@fiscalYearID = 0 or pp.FiscalYearIDSecond = @fiscalYearID)
		and TimeclassID in (1,2,20)
		)
		
		MERGE 
		TGT AS target
		USING fw.StatisticSampledPayPeriodWithCalcs AS source
			ON source.DepartmentID = target.DepartmentID
				AND source.AccountID = target.AccountID
				AND source.PayPeriodID= target.PayPeriodID
				AND source.TimeClassID = target.TimeClassID
		WHEN MATCHED AND 
			(target.Units <> source.Units
			or target.UnitsYTD <> source.UnitsYTD
			or target.UnitsPriorYear <> source.UnitsPriorYear
			or target.UnitsPriorYTD <> source.UnitsPriorYTD
			or target.IsSystemGenerated <> source.IsSystemGenerated)
			THEN
				UPDATE
				SET target.Units = source.Units,
					target.UnitsYTD = source.UnitsYTD,
					target.UnitsPriorYear = source.UnitsPriorYear,
					target.UnitsPriorYTD = source.UnitsPriorYTD,
					target.IsSystemGenerated = source.IsSystemGenerated
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					DepartmentID, AccountID, PayPeriodID, TimeClassID,
					Units,
					UnitsYTD,
					UnitsPriorYear,
					UnitsPriorYTD,
					IsDeleted,
					IsSystemGenerated
					)
				VALUES (
					source.DepartmentID,
					source.AccountID,
					source.PayPeriodID,
					source.TimeClassID,
					source.Units,
					source.UnitsYTD,
					source.UnitsPriorYear,
					source.UnitsPriorYTD,
					0,
					isnull(IsSystemGenerated,0)
					)
		WHEN NOT MATCHED BY SOURCE
		THEN
				DELETE;
	END

	IF OBJECT_ID('fw.StatisticSampledPayPeriodWithCalcs') IS NOT NULL  DROP TABLE fw.StatisticSampledPayPeriodWithCalcs
	IF OBJECT_ID('tempdb..#StatisticSampledPayPeriod') IS NOT NULL DROP TABLE  #StatisticSampledPayPeriod
GO


---------------------------------------------

-- fw.procStatisticSecondarySampledAdjustedTargetMonthlyInsert
CREATE PROCEDURE [fw].[procStatisticSecondarySampledAdjustedTargetMonthlyInsert] (@FiscalYearID int = 0)
AS
BEGIN
/*
Proposal

If the client is not using flexing, this will be the target plus the efficiency factor
This should work regardless of the target basis (i.e. rolling avg or budget)
The factor will be applied after the inversion
If the factor type is percentage, the adjusted target will be the target*(1+factor)
i.e. if my target is 100 and my factor is 5%, the adjusted target will be 100*(1+0.05)=105
i.e. if my target is 100 and my factor is -5%, the adjusted target will be 100*(1+-0.05)=95
If the factor type is value, the adjusted value will be target + factor
i.e. if my target is 1000 and my factor is 200, the adjusted target will be will be 1000+200=1200
i.e. if my target is 1000 and my factor is -200, the adjusted target will be 1000-200=800
If there is more than one factor impacting a department and account or job code/pay code group combination, then the factors should layer on top of each other based on history order
If an efficiency factor does not exist for a particular account/job code, then the value in the new time class will be either flex or baseline target if flex is not used
This will happen after Flex is calculated
Include integration tests
*/
/*
**************************************************************
** Change History
**************************************************************
** CID		Date		  Author	 WI			  Description
** 1      2022-08-23  BC      JAZZ-11498  Change Table Variable to Temporary Tables 
************************************************************
*/
DECLARE @IsFlexingEnabled INT = (
		SELECT VALUE
		FROM [mr].[SystemSetting]
		WHERE NAME = 'Is Target Flexed'
		)
IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE #EfficiencyFactorScope	
CREATE TABLE #EfficiencyFactorScope (
	EfficiencyFactorGUID [uniqueidentifier] NOT NULL
	,[DepartmentID] [int] NOT NULL
	,[AccountID] [int] NOT NULL
	,[FiscalYearID] [smallint] NOT NULL
	,[FiscalMonthID] [tinyint] NOT NULL
	,Value NUMERIC(25, 6) NOT NULL
	,Type TINYINT
	,FactorType CHAR(1)
	,DateCreated DATETIME
	,UNIQUE CLUSTERED (
		FiscalYearID
		,FiscalMonthID
		,DepartmentID
		,AccountID
		,EfficiencyFactorGUID
		)
	);
IF EXISTS (SELECT TOP 1 * FROM [mr].[EfficiencyFactor]) BEGIN
WITH EfficiencyFactorScope
AS (
	SELECT *
		,rn = ROW_NUMBER() OVER (
			PARTITION BY FiscalYearID
			,FiscalMonthID
			,DepartmentID
			,AccountID
			,EfficiencyFactorGUID ORDER BY FiscalYearID
				,FiscalMonthID
				,DepartmentID
				,AccountID
				,EfficiencyFactorGUID
			)
	FROM (
		SELECT DISTINCT ef.EfficiencyFactorGUID
			,ef.FiscalYearID
			,efgd.FiscalMonthID
			,efd.DepartmentID
			,isnull(efgd.AccountID, da.AccountID) AS AccountID
			,CASE 
				WHEN isnull(efgd.AccountID, - 999) = da.AccountID
					THEN 0
				ELSE efgd.Value
				END AS Value
			,ef.Type
			,ef.FactorType
			,ef.DateCreated
		FROM mr.EfficiencyFactor ef
		INNER JOIN mr.EfficiencyFactorDepartment efd ON ef.EfficiencyFactorGUID = efd.EfficiencyFactorGUID
		INNER JOIN mr.EfficiencyFactorGLDetails efgd ON efgd.EfficiencyFactorGUID = ef.EfficiencyFactorGUID
		LEFT JOIN fw.DimAccount da ON efgd.OBFinancialReportingID = da.OBUnitsFinancialReportingID and efgd.AccountID IS NULL
		LEFT JOIN mr.EfficiencyFactorGLDetails efgd_exist ON efgd.EfficiencyFactorGUID = efgd_exist.EfficiencyFactorGUID and efgd_exist.AccountID = da.AccountID  and efgd_exist.FiscalMonthID = efgd.FiscalMonthID
		WHERE (@FiscalYearID = ef.FiscalYearID or @FiscalYearID = 0)  and (efgd_exist.AccountID is null or da.AccountID is null) AND ef.Type = 1 AND isnull(efgd.AccountID, da.AccountID) IS NOT NULL
		) X
	)
INSERT INTO #EfficiencyFactorScope (
	EfficiencyFactorGUID
	,[DepartmentID]
	,[AccountID]
	,[FiscalYearID]
	,[FiscalMonthID]
	,Value
	,Type
	,FactorType
	,DateCreated
	)
SELECT EfficiencyFactorGUID
	,[DepartmentID]
	,[AccountID]
	,[FiscalYearID]
	,[FiscalMonthID]
	,Value
	,Type
	,FactorType
	,DateCreated
FROM EfficiencyFactorScope
WHERE RN = 1

DELETE FROM fw.FactStatisticSecondarySampledMonthly WHERE (@FiscalYearID = FiscalYearID or @FiscalYearID = 0) and TimeClassID = 22

INSERT INTO fw.FactStatisticSecondarySampledMonthly (DepartmentID,
AccountID,
FiscalYearID,
FiscalMonthID,
TimeClassID,
IsDeleted,
Amount)
SELECT DepartmentID
	,AccountID
	,FiscalYearID
	,FiscalMonthID
	,22 as TimeClassID
	,0 as IsDeleted
	,SUM(Amount) as Amount
FROM (
SELECT isnull(fact.DepartmentID,ToApply.DepartmentID) as DepartmentID
	,isnull(fact.AccountID,toApply.AccountID) as AccountID
	,isnull(fact.FiscalYearID,toApply.FiscalYearID) as FiscalYearID
	,isnull(fact.FiscalMonthID,toApply.FiscalMonthID) as FiscalMonthID
	,Amount = CASE 
					WHEN FactorType = 'P'
						THEN isnull(fact.Amount,0.0) * isnull(Value,0.0) / 100.00
					WHEN FactorType = 'V'
						THEN isnull(Value,0.0)
					ELSE 0.0
					END
FROM #EfficiencyFactorScope ToApply
	INNER JOIN (SELECT distinct DepartmentID,AccountID from fw.FactStatisticSecondarySampledMonthly) GenCand on
			GenCand.DepartmentID	= ToApply.DepartmentID
		AND GenCand.AccountID		= ToApply.AccountID
	FULL JOIN fw.FactStatisticSecondarySampledMonthly fact ON 
		fact.DepartmentID = ToApply.DepartmentID
		AND fact.AccountID = ToApply.AccountID
		AND fact.FiscalYearID = ToApply.FiscalYearID
		AND fact.FiscalMonthID = ToApply.FiscalMonthID
	WHERE (
		(
			isnull(fact.TimeClassID,0) = 4
			AND @IsFlexingEnabled = 1
			)
		OR (
			isnull(fact.TimeClassID,0) = 20
			AND @IsFlexingEnabled = 0
			)
		)
	and (fact.FiscalYearID = @FiscalYearID or @FiscalYearID = 0)
UNION ALL
	
SELECT DepartmentID
	,AccountID
	,FiscalYearID
	,FiscalMonthID
	,Amount
FROM fw.FactStatisticSecondarySampledMonthly fact
WHERE (
		(
			isnull(fact.TimeClassID,0) = 4
			AND @IsFlexingEnabled = 1
			)
		OR (
			isnull(fact.TimeClassID,0) = 20
			AND @IsFlexingEnabled = 0
			)
		)
	and (fact.FiscalYearID = @FiscalYearID or @FiscalYearID = 0)
) X
GROUP BY DepartmentID
	,AccountID
	,FiscalYearID
	,FiscalMonthID

exec [fw].[procFactMonthlyYTDPriorYearUpdate] @factTableName = 'fw.FactStatisticSecondarySampledMonthly',@keyNameCSV = 'AccountID',@measureNameCSV = 'Amount',@fiscalYearID  = 0,@timeClassID = 22,@isDebugOnly = 0
END
END
IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE  #EfficiencyFactorScope
GO


---------------------------------------------

-- fw.procStatisticSecondarySampledInsertMonthly
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
** 1		2014-09-03	MS			B-02863	Removing the parameter from the YTD proc call
** 2		2016-09-22	AK			B-11845	Added procFactStatisticSecondarySampledBaselineTargetUpdate
** 3		2016-12-13	NL			B-13759	Adding fiscalYearID param and filtering
** 4		2017-02-20	GF			D-05545	Move duplicate record handling from YTD into sampling + general cleanup
** 5		2017-03-07	GF			B-14693	Added baseline target year filter
** 6		2017-05-24	IP			B-15086	Sampling Performance Improvements. Using temp tables insead of fw.FactPayrollSampledMonthlyDetailed.
** 7		2017-06-15	IP			B-15086 Modify SP to use unique temp table
** 8		2017-07-19	IP			TK-45395 Fixed conditions of merge statement (include isSystemGenerated column)
** 9		2017-27-26	ipetriv		B-16752		Added units Budget Adjustment
** 10		2017-08-29 	ip			B-16798		Add using of Budget Adjustment.
*************************************************************/
CREATE proc [fw].[procStatisticSecondarySampledInsertMonthly] 
	@fiscalYearID smallint = 0
as
	IF OBJECT_ID('tempdb..#StatisticSecondarySampledMonthlyStaging') IS NOT NULL  DROP TABLE #StatisticSecondarySampledMonthlyStaging
	IF OBJECT_ID('fw.StatisticSecondarySampledMonthlyStagingWithCalcs') IS NOT NULL  DROP TABLE fw.StatisticSecondarySampledMonthlyStagingWithCalcs
	
	CREATE TABLE #StatisticSecondarySampledMonthlyStaging (RowID bigint identity(1,1),AccountID int, DepartmentID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Amount decimal(19,4), isDeleted bit, isSystemGenerated bit)		
	--push new data to fact table
	insert into #StatisticSecondarySampledMonthlyStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount)
	exec fw.PrepareStatistics @fiscalYearID,@StatisticType  = 2
    
	--run calculations
	exec fw.procFactMonthlyMergeDuplicates '#StatisticSecondarySampledMonthlyStaging', 'AccountID', 'Amount', @fiscalYearID, 0, 0
    exec fw.procFactStatisticSecondarySampledBaselineTargetUpdate @fiscalYearID = @fiscalYearID
	exec fw.procFactMonthlyYTDPriorYearUpdateStaging 'fw.FactStatisticSecondarySampledMonthly','#StatisticSecondarySampledMonthlyStaging','AccountID', 'Amount', @fiscalYearID, 0, 0

	IF @fiscalYearID = 0 
	BEGIN
	truncate table fw.FactStatisticSecondarySampledMonthly
	INSERT INTO fw.FactStatisticSecondarySampledMonthly With (TABLOCKX) (
			DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID,
			Amount,
			AmountYTD,
			AmountPriorYear,
			AmountPriorYTD,
			IsDeleted,
			IsSystemGenerated
			)
		SELECT DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID,
		Amount,
		AmountYTD,
		AmountPriorYear,
		AmountPriorYTD,
		0 as IsDeleted,
		isnull(IsSystemGenerated,0) as IsSystemGenerated
	FROM fw.StatisticSecondarySampledMonthlyStagingWithCalcs
	END
ELSE 
	BEGIN
		print 'Starting creating index --- '+convert(varchar(20),GETDATE(),113) 
		CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.StatisticSecondarySampledMonthlyStagingWithCalcs (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID)
		print 'Starting transaction --- '+convert(varchar(20),GETDATE(),113) 
		MERGE fw.FactStatisticSecondarySampledMonthly With (TABLOCKX) AS target
		USING fw.StatisticSecondarySampledMonthlyStagingWithCalcs AS source
			ON source.DepartmentID = target.DepartmentID
				AND source.AccountID = target.AccountID
				AND source.FiscalYearID = target.FiscalYearID
				AND source.FiscalMonthID = target.FiscalMonthID
				AND source.TimeClassID = target.TimeClassID
		WHEN MATCHED AND 
			(target.Amount <> source.Amount
			or target.AmountYTD <> source.AmountYTD
			or target.AmountPriorYear <> source.AmountPriorYear
			or target.AmountPriorYTD <> source.AmountPriorYTD
			or target.IsSystemGenerated <> source.IsSystemGenerated)
			THEN
				UPDATE
				SET target.Amount = source.Amount,
					target.AmountYTD = source.AmountYTD,
					target.AmountPriorYear = source.AmountPriorYear,
					target.AmountPriorYTD = source.AmountPriorYTD,
					target.IsSystemGenerated = source.IsSystemGenerated
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID,
					Amount,
					AmountYTD,
					AmountPriorYear,
					AmountPriorYTD,
					IsDeleted,
					IsSystemGenerated
					)
				VALUES (
					source.DepartmentID,
					source.AccountID,
					source.FiscalYearID,
					source.FiscalMonthID,
					source.TimeClassID,
					source.Amount,
					source.AmountYTD,
					source.AmountPriorYear,
					source.AmountPriorYTD,
					0,
					isnull(IsSystemGenerated,0)
					)
		WHEN NOT MATCHED BY SOURCE
			AND Target.FiscalYearID = @fiscalYearID		
			THEN
				DELETE;
	END
	IF OBJECT_ID('tempdb..#StatisticSecondarySampledMonthlyStaging') IS NOT NULL  DROP TABLE #StatisticSecondarySampledMonthlyStaging
	IF OBJECT_ID('fw.StatisticSecondarySampledMonthlyStagingWithCalcs') IS NOT NULL  DROP TABLE fw.StatisticSecondarySampledMonthlyStagingWithCalcs
GO


---------------------------------------------

-- fw.procStatisticSecondarySampledInsertPayPeriod
/**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI	Description
** 1		2016-04-28	AK		B-11864	Added IsPR check
** 2		2017-01-31	AK		B-13926	Added department filter
** 3		2017-02-08	GF		B-14308 Added year filter
** 4		2017-02-20	GF		D-05545 Move duplicate record handling from YTD into sampling
** 5		2017-10-04 	GF		D-06489	Fix pay period select when running all years
*************************************************************/
CREATE proc [fw].[procStatisticSecondarySampledInsertPayPeriod]
	@isCalculatedYearMonth as bit = 1,
	@departmentIDs nvarchar(max) = null,
	@fiscalYearID int = 0
with recompile
as
	declare @departments table(val int primary key)
	insert into @departments select val from ConvertCSValuesToTable(@departmentIDs, ',')

	declare @payperiods table(val smallint primary key)
	insert into @payperiods select PayPeriodID from fw.DimPayPeriod where FiscalYearIDSecond = @fiscalYearID or @fiscalYearID = 0

	if @isCalculatedYearMonth = 1 begin
		--delete existing data
		if (@departmentIDs is null and @fiscalYearID = 0) begin
			truncate table fw.FactStatisticSecondarySampledbyPayPeriod
		end else begin
			while exists(select null from fw.FactStatisticSecondarySampledbyPayPeriod (nolock) where (@departmentIDs is null or DepartmentID in(select val from @departments)) and (@fiscalYearID = 0 or PayPeriodID in(select val from @payperiods))) begin
				delete top (10000) from fw.FactStatisticSecondarySampledbyPayPeriod where (@departmentIDs is null or DepartmentID in(select val from @departments)) and (@fiscalYearID = 0 or PayPeriodID in(select val from @payperiods))
			end
		end
		
		--sample rows with a valid pay period code, spreading across months
		insert into [fw].[FactStatisticSecondarySampledbyPayPeriod] (DepartmentID, AccountID, PayPeriodID, TimeClassID, Units)
		select
			STAT.DepartmentID,
			STAT.AccountID,
			STAT.PayPeriodID,
			STAT.TimeClassID,
			SUM(STAT.Value) AS Units
		from
			[int].[FactStatisticsbyPayPeriod] STAT
			inner join fw.DimAccount A on A.Accountid = STAT.Accountid
			inner join fw.DimDepartment D on D.Departmentid = STAT.Departmentid
			inner join [fw].[viewStatisticSecondaryConfiguration] V on V.AccountID=stat.AccountID and V.DepartmentID=stat.DepartmentID
		where
			STAT.Value != 0 and STAT.Isdeleted = 0 and STAT.PayPeriodID != 0 and A.IsStat=1
			and D.IsPR = 1
			and (@departmentIDs is null or STAT.DepartmentID in (select val from @departments))
			and (@fiscalYearID = 0 or STAT.PayPeriodID in(select val from @payperiods))
		group by
			STAT.DepartmentID,
			STAT.AccountID,
			STAT.PayPeriodID,
			STAT.TimeClassID
	end	else begin
		print 'NOT SUPPORTED YET'
	end

	--run calculations
	exec fw.procFactPayPeriodMergeDuplicates 'fw.FactStatisticSecondarySampledbyPayPeriod', 'AccountID', 'Units', @fiscalYearID, 0, 0, @departmentIDs
	exec fw.procFactPayPeriodYTDPriorYearUpdate 'fw.FactStatisticSecondarySampledbyPayPeriod', 'AccountID', 'Units', @fiscalYearID, 0, 0, @departmentIDs
GO


---------------------------------------------

-- fw.procTemplatePublishRequest_Insert
/************************************************************************************************************************
** Author: cbecker
** Create Date: 2016-01-14
** Description: Inserts template publish request and removes duplicates requests
** Last Modified: 2016-01-14
** GM Release: 2016.1.3
**************************************************************************************************************************
** Change History
**************************************************************************************************************************
**	CID		Date		Author	WI			Description
**	01		2016-03-15	cbb		n/a			Delete duplicate publish requests
**	02		2017-04-24	gjf		n/a			Trigger profile rebuilds on publish
**	03		2019-03-18	gjf		B-22412		Option to include template file
*************************************************************************************************************************/
CREATE proc [fw].[procTemplatePublishRequest_Insert]
	@frameworkID nvarchar(16)=0,
	@includeTemplates bit=0,
	@IsDebugOnly bit=0
as
begin
--------------------------------------------------------------------------------------------------
-- Logging
--------------------------------------------------------------------------------------------------
	declare @logdesc nvarchar(100)
	select 
		@logdesc = case @IsDebugOnly
					when 1 then 'Debug only - Insert template publish request for '
					else 'Insert template publish request for '
					end
					+fw.Name
	from [fw].[DimFramework] fw
	where FrameworkID=@frameworkID
	
	declare @higuid uniqueidentifier
	exec procLogScript @logdesc, @higuid output

	print N'select * from [dbo].[HistoryItem] where HISTORYITEMGUID='''
		+cast(@higuid as varchar(36))
		+N''''
		
--------------------------------------------------------------------------------------------------
-- Set @sql string for inserting template publish request
--------------------------------------------------------------------------------------------------
	declare @RequestGUID nvarchar(36) = newid()
	declare @IssuedAt nvarchar(36) = getdate()
	declare @sql nvarchar(max) = 
'
--Remove duplicate template publish requests
with duplicates
as
(
select 
	RequestGUID,
	FrameworkID,
	Num = row_number() over (PARTITION BY FrameworkID order by IssuedAt)
from [dbo].[TemplatePublishRequest]
)
delete 
from duplicates
where Num>1

--Insert template publish request
if not exists
(
select 1
from [dbo].[TemplatePublishRequest]
where FrameworkID='
+ @frameworkID
+ '
)
begin
insert into [dbo].[TemplatePublishRequest]
	([RequestGUID], [IssuedAt], [FrameworkID])
values
	('''
+ @RequestGUID
+ ''', '''
+ @IssuedAt
+ ''', '
+ @frameworkID
+')
end
'

--------------------------------------------------------------------------------------------------
-- Ensure that OB publishes do a full rebuild on expansion profiles
--------------------------------------------------------------------------------------------------
if (@frameworkID = 2) begin
	set @sql = @sql + '
--Ensure that OB publishes do a full rebuild on expansion profiles
update ob.SystemSetting set Value = ''1'' where Name = ''Template Publish Create Profiles'';
'
end

--------------------------------------------------------------------------------------------------
-- Optionally include template files
--------------------------------------------------------------------------------------------------
if (@includeTemplates = 1) begin
	set @sql = @sql + '
--Include template files
insert into TemplatePublishRequestData (RequestGUID, ModelTemplateGUID, LastModified, Data)
select
	''' + @RequestGUID + ''',
	mt.ModelTemplateGUID,
	getdate(),
	dp.Data
from 
	EMFModelTemplate mt
	inner join DataPathFile_ModelTemplate dp on dp.FileName = cast(mt.ModelTemplateGUID as nvarchar(36)) + ''.xlsx.TAWithMappingFormulas''
where
	' + @frameworkID + ' = (case when mt.Name like ''CAP %'' then 1 when mt.Name like ''OB %'' then 2 when mt.Name like ''SP %'' then 4 else 0 end)
	and mt.ModelTemplateGUID not in(select ChildModelTemplateGUID from MEScoreExpansionProfile)
'
end

--------------------------------------------------------------------------------------------------
-- Print or execute @sql
--------------------------------------------------------------------------------------------------
	if @IsDebugOnly=1
		begin
			print(@sql)
		end
	else
		begin
			exec(@sql)
		end
		
end
GO


---------------------------------------------

-- fw.procTransferStaffingToStaffingByPayPeriodCurrentYear
/**************************************************************  
** Change History  
**************************************************************  
** CID  Date         Author    WI        Description  
** 1    2018-08-07   VO        B-20238   Added condition where TimeClassID = 2  
** 2    2020-01-27   IH        TK-82801  Increase a deletion size from 10K to 100K  
** 3    2020-10-02   HV        JAZZ-1487 MR "Transfer Budget Data" filtering on currently year, not transferring correctly to first/last pay periods  
** 4    2022-12-12   BK        JAZZ-47041 MR "Transfer Budget Data" increase temp table column size to prevent failing when int.FactStaffing EmployeeCode is longer than 50 characters  
** 5	2024-06-14   SM        JAZZ-71536 change JobCodeID from smallint to int  
** 6	2024-09-13   SF        JAZZ-72743 PayCode from varchar(50) to varchar(100) - Extend Field String Limit for Pay Code for Kaiser EPMS
*************************************************************/  
-- !!! If you modifying this proc, check [int].[procTransferStaffingToStaffingByPayPeriodFiscalYear] for updates !!!  

CREATE   proc [fw].[procTransferStaffingToStaffingByPayPeriodCurrentYear] as  
  
 /********  Variable Declaration **********/  
 declare @TransactionID int = 1  
 DECLARE @FiscalYearId INT = (  
   SELECT setting  
   FROM dbsetting  
   WHERE NAME = 'Current_GL_YearID'  
   )  
  
 /********  Build Rows to Insert **********/  
  
 CREATE TABLE #TEMPSTAFFINGPAYPERIOD (  
  [DepartmentID] [int] NOT NULL,  
  [DepartmentCode] [varchar](50) NOT NULL,  
  [JobCodeID] [int] NOT NULL,  
  [JobCode] [varchar](50) NOT NULL,  
  [PayCodeID] [smallint] NOT NULL,  
  [PayCode] [varchar](100) NOT NULL,  
  [FiscalYearID] [smallint] NOT NULL,  
  [FiscalYearCode] [varchar](20) NOT NULL,  
  [TimeClassID] [tinyint] NOT NULL,  
  [TimeClassCode] [varchar](20) NOT NULL,  
  [UnitTypeID] [smallint] NOT NULL,  
  [UnitType] [varchar](20) NOT NULL,  
  [PayPeriodID] [smallint] NOT NULL,  
  [PayPeriodCode] [varchar](20) NOT NULL,  
  [Value] [decimal](19, 4) NOT NULL,  
  [EmployeeID] [int] NOT NULL,  
  [Employeecode] [varchar](2000) NOT NULL,  
  [TransactionID] [int] NULL  
 )  
  
  
 insert into #TEMPSTAFFINGPAYPERIOD ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [PayPeriodID], [PayPeriodCode], [Value], [EmployeeID], [Employeecode], [TransactionID])  
 select  
  fact.[DepartmentID],  
  fact.[DepartmentCode],  
  fact.[JobCodeID],  
  fact.[JobCode],  
  fact.[PayCodeID],  
  fact.[PayCode],  
  PP.[FiscalYearIDSecond],  
  PP.[FiscalYearIDSecond],  
  fact.[TimeClassID],  
  fact.[TimeClassCode],  
  fact.[UnitTypeID],  
  fact.[UnitType],  
  pp.[PayPeriodID],  
  pp.[PayPeriodCode],  
  SUM(cast(fact.value * PP.PeriodWeightStart as money)) AS Value,  
  fact.[EmployeeID],  
  fact.[Employeecode],  
  1 as TransactionID  
 from  
  [int].[FactStaffing] fact  
  inner join [fw].[DimDepartment] D on fact.DepartmentID=D.DepartmentID  
  inner join [fw].[DimPayPeriod] PP on fact.FiscalMonthID = PP.FiscalMonthIDStart and fact.FiscalYearID = PP.FiscalYearIDStart and PP.PayCycleID=D.PayCycleID  
 where  
  fact.value != 0  
  and fact.TimeclassID = 2  
  and PP.PeriodDaysStart > 0 and fact.IsDeleted = 0  
  --============= BEGIN CID 2 =================  
  and fact.TransactionID<>@TransactionID  
  --============= END CID 2 ===================    
  and PP.FiscalYearIDSecond = @FiscalYearId  
 GROUP BY  
  fact.[DepartmentID],  
  fact.[DepartmentCode],  
  fact.[JobCodeID],  
  fact.[JobCode],  
  fact.[PayCodeID],  
  fact.[PayCode],  
  PP.[FiscalYearIDSecond],  
  fact.[TimeClassID],  
  fact.[TimeClassCode],  
  fact.[UnitTypeID],  
  fact.[UnitType],  
  fact.[EmployeeID],  
  fact.[Employeecode],  
  pp.[PayPeriodID],  
  pp.[PayPeriodCode]  
    
 insert into #TEMPSTAFFINGPAYPERIOD ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [PayPeriodID], [PayPeriodCode], [Value], [EmployeeID], [Employeecode], [TransactionID])  
 select   
  fact.[DepartmentID],  
  fact.[DepartmentCode],  
  fact.[JobCodeID],  
  fact.[JobCode],  
  fact.[PayCodeID],  
  fact.[PayCode],  
  fact.[FiscalYearID],  
  fact.[FiscalYearCode],  
  fact.[TimeClassID],  
  fact.[TimeClassCode],  
  fact.[UnitTypeID],  
  fact.[UnitType],  
  pp.[PayPeriodID],  
  pp.[PayPeriodCode],  
  SUM(cast(fact.value * PP.PeriodWeightSecond as money)) AS Value,  
  fact.[EmployeeID],  
  fact.[Employeecode],  
  1 as TransactionID  
 from  
  [int].[FactStaffing] fact  
  inner join [fw].[DimDepartment] D on fact.DepartmentID=D.DepartmentID  
  inner join [fw].[DimPayPeriod] PP on fact.FiscalMonthID = PP.FiscalMonthIDSecond and fact.FiscalYearID = PP.FiscalYearIDSecond and PP.PayCycleID=D.PayCycleID  
 where  
  fact.value != 0  
  and fact.TimeclassID = 2  
  and PP.PeriodDaysSecond > 0 and fact.IsDeleted = 0  
  --============= BEGIN CID 2 =================  
  and fact.TransactionID<>@TransactionID  
  --============= END CID 2 ===================  
  and PP.FiscalYearIDSecond = @FiscalYearId  
 GROUP BY  
  fact.[DepartmentID],  
  fact.[DepartmentCode],  
  fact.[JobCodeID],  
  fact.[JobCode],  
  fact.[PayCodeID],  
  fact.[PayCode],  
  fact.[FiscalYearID],  
  fact.[FiscalYearCode],  
  fact.[TimeClassID],  
  fact.[TimeClassCode],  
  fact.[UnitTypeID],  
  fact.[UnitType],  
  fact.[EmployeeID],  
  fact.[Employeecode],  
  pp.[PayPeriodID],  
  pp.[PayPeriodCode]  
      
 /********  Delete previous transfered data **********/  
--============= BEGIN CID 3 =================   
 while exists (select null from [int].[FactStaffingByPayPeriod] where TransactionID=@TransactionID and FiscalYearID = @FiscalYearId and TimeClassID = 2)  
          delete top (100000) from [int].[FactStaffingByPayPeriod] where TransactionID=@TransactionID and FiscalYearID = @FiscalYearId  and TimeClassID = 2  
--============= END CID 3 ===================  
  
  
 /******** Insert into destination table *************/  
 insert into [int].[FactStaffingByPayPeriod] ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [PayPeriodID], [PayPeriodCode], [Value], [EmployeeID], [Employeecode], [TransactionID])  
 select   
   [DepartmentID],   
   [DepartmentCode],   
   [JobCodeID],   
   [JobCode],   
   [PayCodeID],   
   [PayCode],   
   [FiscalYearID],   
   [FiscalYearCode],   
   [TimeClassID],   
   [TimeClassCode],   
   [UnitTypeID],   
   [UnitType],   
   [PayPeriodID],   
   [PayPeriodCode],   
   SUM([Value]) AS VALUE,   
   [EmployeeID],   
   [Employeecode],   
   1 as TransactionID  
  from   
   #TEMPSTAFFINGPAYPERIOD  
  group by  
   [DepartmentID],   
   [DepartmentCode],   
   [JobCodeID],   
   [JobCode],   
   [PayCodeID],   
   [PayCode],   
   [FiscalYearID],   
   [FiscalYearCode],   
   [TimeClassID],   
   [TimeClassCode],   
   [UnitTypeID],   
   [UnitType],   
   [PayPeriodID],   
   [PayPeriodCode],  
   [EmployeeID],   
   [Employeecode]  
     
-- alter index all on [int].[FactStaffingbyPayPeriod] REBUILD WITH (FILLFACTOR=80)  
-- update statistics [int].[FactStaffingbyPayPeriod] WITH FULLSCAN  
  
--cleanup  
DROP TABLE #TEMPSTAFFINGPAYPERIOD  
  
  
 /********  Update record in IntTransaction **********/  
  --TODO: Make the way it inserts to the IntTranaction much better;
GO


---------------------------------------------

-- fw.procTransferStatisticsMonthlyToPayPeriodCurrentYear
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2018-08-07  VO      B-20238		added condition where TimeClassID = 2
** 2    2020-10-02  HV      JAZZ-1487	MR "Transfer Budget Data" filtering on currently year, not transferring correctly to first/last pay periods
*************************************************************/
CREATE proc [fw].[procTransferStatisticsMonthlyToPayPeriodCurrentYear] as
	/********  Variable Declaration **********/
	declare @TransactionID int = 1
	DECLARE @FiscalYearId INT = (
			SELECT setting
			FROM dbsetting
			WHERE NAME = 'Current_GL_YearID'
			)


	/********  Build Rows to Insert **********/

	CREATE TABLE #TEMPSTATISTICS (
		[AccountID] [int] NOT NULL,
		[DepartmentID] [int] NOT NULL,
		[FiscalYearID] [smallint] NOT NULL,
		[PayPeriodID] [smallint] NOT NULL,
		[TimeClassID] [tinyint] NOT NULL,
		[Value] [decimal](19, 4) NOT NULL,
		[AccountCode] [nvarchar](100) NOT NULL,
		[DepartmentCode] [nvarchar](100) NOT NULL,
		[FiscalYearCode] [nvarchar](100) NOT NULL,
		[PayPeriodCode] [nvarchar](100) NOT NULL,
		[TimeClassCode] [nvarchar](100) NOT NULL,
		[TransactionID] [int] NOT NULL,
	)

	insert into #TEMPSTATISTICS (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, PayPeriodID, PayPeriodCode, TimeClassID, TimeClassCode, Value, TransactionID)
	select
		fact.DepartmentID,
		fact.DepartmentCode,
		fact.AccountID,
		fact.AccountCode,
		PP.FiscalYearIDSecond,
		PP.FiscalYearIDSecond,
		PP.PayPeriodID,
		PP.PayPeriodCode,
		fact.TimeClassID,
		fact.TimeClassCode,
		SUM(cast(fact.value * PP.PeriodWeightStart as money)) AS Value,
		1 as TransactionID
	from
		[int].[FactStatistic] fact
		inner join [fw].[DimDepartment] D on fact.DepartmentID=D.DepartmentID
		inner join fw.DimPayPeriod PP on PP.FiscalMonthIDStart = fact.FiscalMonthID and PP.FiscalYearIDStart = fact.FiscalYearID and PP.PayCycleID=D.PayCycleID
	where
		fact.value != 0
		and fact.TimeClassID = 2
		and PP.PeriodDaysStart > 0
		--============= BEGIN CID 2 =================
		and fact.TransactionID<>@TransactionID
		--============= END CID 2 ===================	
		and PP.FiscalYearIDSecond = @FiscalYearId
	GROUP BY
		fact.DepartmentID,
		fact.DepartmentCode,
		fact.AccountID,
		fact.AccountCode,
		PP.FiscalYearIDSecond,
		PP.PayPeriodID,
		PP.PayPeriodCode,
		fact.TimeClassID,
		fact.TimeClassCode
		
	insert into #TEMPSTATISTICS (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, PayPeriodID, PayPeriodCode, TimeClassID, TimeClassCode, Value, TransactionID)
	select
		fact.DepartmentID,
		fact.DepartmentCode,
		fact.AccountID,
		fact.AccountCode,
		fact.FiscalYearID,
		fact.FiscalYearCode,
		PP.PayPeriodID,
		PP.PayPeriodCode,
		fact.TimeClassID,
		fact.TimeClassCode,
		SUM(cast(fact.value * PP.PeriodWeightSecond as money)) AS Value,
		1 as TransactionID
	from
		[int].[FactStatistic] fact
		inner join [fw].[DimDepartment] D on fact.DepartmentID=D.DepartmentID
		inner join fw.DimPayPeriod PP on PP.FiscalMonthIDSecond = fact.FiscalMonthID and PP.FiscalYearIDSecond = fact.FiscalYearID and PP.PayCycleID=D.PayCycleID
	where
		fact.value != 0
		and fact.TimeClassID = 2
		and PP.PeriodDaysSecond > 0
		--============= BEGIN CID 2 =================
		and fact.TransactionID<>@TransactionID
		--============= END CID 2 ===================	
		and fact.FiscalYearID = @FiscalYearId
	GROUP BY
		fact.DepartmentID,
		fact.DepartmentCode,
		fact.AccountID,
		fact.AccountCode,
		fact.FiscalYearID,
		fact.FiscalYearCode,
		PP.PayPeriodID,
		PP.PayPeriodCode,
		fact.TimeClassID,
		fact.TimeClassCode
				
	/********  Delete previous transfered data **********/
	delete from [int].[FactStatisticsbyPayPeriod] where TransactionID=@TransactionID and FiscalYearID = @FiscalYearId  and TimeClassID = 2


	/******** Insert into destination table *************/
	insert into [int].[FactStatisticsbyPayPeriod] (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, PayPeriodID, PayPeriodCode, TimeClassID, TimeClassCode, Value, TransactionID)
	select
			DepartmentID,
			DepartmentCode,
			AccountID,
			AccountCode,
			FiscalYearID,
			FiscalYearCode,
			PayPeriodID,
			PayPeriodCode,
			TimeClassID,
			TimeClassCode,
			sum(value),
			TransactionID
		from 
			#TEMPSTATISTICS
		group by
			DepartmentID,
			DepartmentCode,
			AccountID,
			AccountCode,
			FiscalYearID,
			FiscalYearCode,
			PayPeriodID,
			PayPeriodCode,
			TimeClassID,
			TimeClassCode,
			TransactionID
			
	alter index all on [int].[FactStatisticsbyPayPeriod] REBUILD WITH (FILLFACTOR=80)
	update statistics [int].[FactStatisticsbyPayPeriod] WITH FULLSCAN


	/********  Update record in IntTransaction **********/
		--TODO: Make the way it inserts to the IntTranaction much better
GO


---------------------------------------------

-- fw.procUpdateClientReportSectionAttributeFilter_PayPeriod
--Proc to set section attribute filter for Pay Periods--------------------------
CREATE PROC [fw].[procUpdateClientReportSectionAttributeFilter_PayPeriod]
	@TopCount int,
	@MaxPayPeriodID int,
	@ClientReportSectionAttributeGUID uniqueidentifier
AS

BEGIN
	CREATE TABLE #TempPeriods (PayPeriodID smallint, PayPeriodCode nvarchar(8))
	INSERT INTO #TempPeriods (PayPeriodID, PayPeriodCode)
		SELECT TOP (@TopCount)
		PayPeriodID, PayPeriodCode
		FROM [fw].[DimPayPeriod] 
		WHERE PayPeriodID <= @MaxPayPeriodID
		ORDER BY PayPeriodID DESC

		DECLARE @FilterMember nvarchar(100)
		SET @FilterMember = (
			SELECT STUFF((
			        select ','+ PayPeriodCode 
			        from #TempPeriods
					order by PayPeriodID asc
			        FOR XML PATH('')
			        )
			        ,1,1,'') AS SortOrder
			)	
		UPDATE [dbo].[REClientReportSectionAttribute] 
		SET FilterMemberCSV=@FilterMember, SortOrderValue='-1'
		WHERE ClientReportSectionAttributeGUID = @ClientReportSectionAttributeGUID
		
	DROP TABLE #TempPeriods	
END
GO


---------------------------------------------

-- fw.procUpdateDataStudio20ViewYearStructure
CREATE procedure [fw].[procUpdateDataStudio20ViewYearStructure]
(
	@FrameworkSchema Nvarchar(10) = 'sp',
	@YearShift int = 1,
	@isExecuting bit = 0
	--Schema= 'sp' or 'ob' (select SchemaName from fw.dimframework), YearShift #of Years to rollforward (positive integer) / back (negative integer), isExecuting 0 = print sql 1 = exec sql
)
AS

/************************************************************
** Author: blewis
** Create Date: 2015-01-23
** Description: Rolls SP / OB DS2.0 Views forward and backward
** Last Modified: 2015-01-23
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
*************************************************************/

DECLARE TableEditorConfigGUID CURSOR FOR 
	select distinct st.TableEditorConfigGUID 
	from [dbo].[ScoreTableEditorConfig] st
	inner join [dbo].[ScoreComposite] sc on st.DataSourceGUID=sc.CompositeGUID
	inner join [dbo].[ScoreTableEditorColumn] ec on st.TableEditorConfigGUID=ec.TableEditorConfigGUID
	inner join [fw].[DimFramework] fw on fw.FrameworkID=sc.FrameworkID
	where fw.FrameworkSchemaName=@FrameworkSchema and ec.Type=2

Declare @TableEditorConfig Nvarchar(200)
open TableEditorConfigGUID

FETCH NEXT FROM TableEditorConfigGUID 
	INTO @TableEditorConfig
WHILE (@@FETCH_STATUS = 0) 	
BEGIN

Declare @DSViewName Nvarchar(400) = (select '--' + FriendlyName from [dbo].[ScoreTableEditorConfig] where TableEditorConfigGUID=@TableEditorConfig)
Print''
Print'-------------------------------------------------------------------------------------------------------------------------------------------'
PRINT '--' + @DSViewName
PRINT '--'''+@TableEditorConfig+''' -TableEditorConfigGuid'
Print'-------------------------------------------------------------------------------------------------------------------------------------------'

		DECLARE @sqli varchar(max)
		
		DECLARE @TableEditorFirstColumnGuid Nvarchar(200) = 
			(select TableEditorColumnGUID
			from [dbo].[ScoreTableEditorColumn] 
			where TableEditorConfigGUID=@TableEditorConfig and DisplayOrder=
				(select Min(DisplayOrder)
				from [dbo].[ScoreTableEditorColumn] 
				where Type=2 and  TableEditorConfigGUID=@TableEditorConfig))
		 

		DECLARE @XML Nvarchar(MAX) = (Select Cast(MetaData as nvarchar(max)) from [dbo].[ScoreTableEditorColumn]  where TableEditorColumnGUID=@TableEditorFirstColumnGuid)
		DECLARE @Start int = (select CharIndex('FISCAL_YEARFiscalYearID',@XML) + Len('FISCAL_YEARFiscalYearID')+1) 
		DECLARE @FiscalYear NvarChar(4) = Substring(@XML,@Start,4)
		
		IF IsNull(
		     (Select Case When CharIndex('.', @FiscalYear) > 0 
		                  Then Case When Convert(int, ParseName(@FiscalYear, 1)) <> 0
		                            Then 0
		                            Else 1
		                            End
		                  Else 1
		                  End
		      Where IsNumeric(@FiscalYear + 'e0') = 1), 0) = 1 Begin

				DECLARE TableEditorColumns CURSOR FOR 
					select TableEditorColumnGUID
						from [dbo].[ScoreTableEditorColumn] e
				where e.TableEditorConfigGUID=@TableEditorConfig and e.Type=2
				order by e.DisplayOrder

				Declare @TableEditorCol Nvarchar(200)

				open TableEditorColumns

				FETCH NEXT FROM TableEditorColumns 
					INTO @TableEditorCol
				WHILE (@@FETCH_STATUS = 0) 
					BEGIN TRY
						SET @sqli = 
						'Update [dbo].[ScoreTableEditorColumn] set DisplayName=Replace(DisplayName,'+Cast(@FiscalYear as Nvarchar(4))+','+Cast((@FiscalYear + @YearShift) as Nvarchar(4))+'), MetaData = Replace(Cast(Metadata as Nvarchar(max)),' + Cast(@FiscalYear as Nvarchar(4)) + ','+ Cast((@FiscalYear + @YearShift) as Nvarchar(4))+') where TableEditorColumnGUID=''' + @TableEditorCol +''''
						
						SET @FiscalYear= (Select @FiscalYear + 1)
						
						if @isExecuting = 1 begin
							exec(@sqli)
						end else begin
							print @sqli
						end

						FETCH NEXT FROM TableEditorColumns INTO @TableEditorCol
					END TRY
					Begin Catch
					PRINT '--Error'
					PRINT @sqli
					PRINT '''' + @TableEditorCol +'''' +'--ErrorColumnGUID'
					PRINT ''
					End Catch
				CLOSE TableEditorColumns
				DEALLOCATE TableEditorColumns
		
				SET @sqli = 		
				'Update [dbo].[ScoreTableEditorFilter]
					set HierarchyPath = Replace(HierarchyPath,Cast(RIGHT(HierarchyPath,4)as INT),Cast(RIGHT(HierarchyPath,4)as INT)+' + Cast(@YearShift as Nvarchar(4)) + '),
					FriendlyName=Replace(FriendlyName,Cast(RIGHT(FriendlyName,4)as INT),Cast(RIGHT(FriendlyName,4)as INT)+' + Cast(@YearShift as Nvarchar(4)) + ')
				where TableEditorConfigGUID='''+@TableEditorConfig+''' and KeyGUID=''84f7adb1-e680-4a23-b1ea-638120fbeadb'''
				
				if @isExecuting = 1 begin
					exec(@sqli)
				end else begin
					print @sqli
				end

		End	
		

FETCH NEXT FROM TableEditorConfigGUID INTO @TableEditorConfig
END
CLOSE TableEditorConfigGUID
DEALLOCATE TableEditorConfigGUID
GO


---------------------------------------------

-- fw.procUpdateMinimumStaffingFlexPayrollSampledDaily
CREATE PROCEDURE [fw].[procUpdateMinimumStaffingFlexPayrollSampledDaily]
	@fiscalYearID smallint = 0,
	@onePayPeriodOnlyDate datetime = null
AS	

/*
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2022-08-05	BS		JAZZ-41378		Daily Flexing - Payroll Minimum Staffing 
************************************************************
*/
IF OBJECT_ID('tempdb..#inputPayPeriods') IS NOT NULL DROP TABLE #inputPayPeriods

SELECT fp.PayPeriodID, COUNT(*) AS RecordsCount, 0 AS BatchID INTO #inputPayPeriods
FROM fw.FactPayrollSampledDaily fp 
INNER JOIN pi.MinimumStaffingFlex ms ON fp.DepartmentID = ms.DepartmentID AND fp.JobCodeID = ms.JobCodeID AND fp.PayCodeGroupID = ms.PayCodeGroupID
INNER JOIN fw.DimPayPeriod pp ON fp.PayPeriodID = pp.PayPeriodID
WHERE fp.TimeClassID = 4 AND fp.Hours < ms.Hours AND
((@onePayPeriodOnlyDate IS NOT NULL AND @onePayPeriodOnlyDate BETWEEN pp.PeriodStartCalendarDate AND pp.PeriodEndCalendarDate)
OR 
(@onePayPeriodOnlyDate IS NULL AND (pp.FiscalYearIDSecond = @fiscalYearID OR @fiscalYearID = 0)))
GROUP BY fp.PayPeriodID

DECLARE @BatchSize INT = 30000000

-- Split data into batches
WHILE EXISTS (SELECT TOP 1 1 FROM #inputPayPeriods WHERE BatchID = 0)
BEGIN
	;WITH PayPeriodInfo AS 
	(
		SELECT DM.PayPeriodID, ROW_NUMBER() OVER (ORDER BY DM.PayPeriodID) AS RowNumber, SUM(RecordsCount) OVER (ORDER BY DM.PayPeriodID) AS Total, M.MaxBatchID+1 AS BatchID
		FROM #inputPayPeriods IPP
		INNER JOIN fw.DimPayPeriod DM ON DM.PayPeriodID = IPP.PayPeriodID
		CROSS JOIN (SELECT MAX(BatchID) AS MaxBatchID FROM #inputPayPeriods) M
		WHERE IPP.BatchID = 0
	)
	UPDATE IPP
	SET IPP.BatchID = MI.BatchID
	FROM #inputPayPeriods IPP
	INNER JOIN PayPeriodInfo MI ON MI.PayPeriodID = IPP.PayPeriodID
	WHERE MI.Total <= @BatchSize OR MI.RowNumber = 1
END

DECLARE @BatchID INT, @MaxBatchID INT
SELECT @MaxBatchID = MAX(BatchID) FROM #inputPayPeriods

-- Loop thru batches and insert data
SET @BatchID = 1
WHILE @BatchID <= @MaxBatchID
BEGIN  	
	UPDATE fp
	SET
		Hours = h.Hours
	FROM 
		fw.FactPayrollSampledDaily fp
		INNER JOIN pi.MinimumStaffingFlex h ON fp.DepartmentID = h.DepartmentID AND fp.JobCodeID = h.JobCodeID AND fp.PayCodeGroupID = h.PayCodeGroupID
		INNER JOIN #inputPayPeriods IPP ON IPP.PayPeriodID = fp.PayPeriodID
		WHERE fp.TimeClassID = 4 AND IPP.BatchID = @BatchID AND fp.Hours < h.Hours
SET @BatchID = @BatchID + 1
END
GO


---------------------------------------------

-- fw.procUpdateMinimumStaffingFlexPayrollSampledPayPeriod
CREATE   PROCEDURE [fw].[procUpdateMinimumStaffingFlexPayrollSampledPayPeriod]
	@fiscalYearID smallint = 0
AS	
/*
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2020-10-27	HV		JAZZ-8174		PR | Minimum Staffing Flex 
************************************************************
*/
	;WITH PayPeriodHours AS
	(
		SELECT fp.DepartmentID, fp.JobCodeID, fp.PayCodeGroupID, fp.PayPeriodID, fp.TimeClassID, ms.Hours * pc.PeriodDays AS PayPeriodHours
		FROM fw.FactPayrollSampledPayPeriod fp 
		INNER JOIN pi.MinimumStaffingFlex ms ON fp.DepartmentID = ms.DepartmentID AND fp.JobCodeID = ms.JobCodeID AND fp.PayCodeGroupID = ms.PayCodeGroupID
		INNER JOIN fw.DimPayPeriod pp ON fp.PayPeriodID = pp.PayPeriodID
		INNER JOIN fw.DimPayCycle pc ON pc.PayCycleID = pp.PayCycleID
		WHERE fp.TimeClassID = 4 AND (pp.FiscalYearIDSecond = @fiscalYearID OR @fiscalYearID = 0)
	)
	UPDATE fp
		SET
			Hours = h.PayPeriodHours
		FROM 
			fw.FactPayrollSampledPayPeriod fp
			INNER JOIN PayPeriodHours h ON fp.DepartmentID = h.DepartmentID AND fp.JobCodeID = h.JobCodeID AND fp.PayCodeGroupID = h.PayCodeGroupID AND fp.PayPeriodID = h.PayPeriodID AND fp.TimeClassID = h.TimeClassID
			WHERE fp.Hours < h.PayPeriodHours
GO


---------------------------------------------

-- fw.procValidateClientSchema
CREATE proc fw.procValidateClientSchema as

exec procValidateColumnsExists 'client', 'viewFactGLImport', 'DepartmentCode'
exec procValidateColumnsExists 'client', 'viewFactGLImport', 'AccountCode'
exec procValidateColumnsExists 'client', 'viewFactGLImport', 'FiscalYearID'
exec procValidateColumnsExists 'client', 'viewFactGLImport', 'FiscalMonthCode'
exec procValidateColumnsExists 'client', 'viewFactGLImport', 'TimeClassCode'
exec procValidateColumnsExists 'client', 'viewFactGLImport', 'Dollars'
exec procValidateColumnsExists 'client', 'viewFactGLImport', 'Units'

/*
create view client.viewFactStatisticImportMonthly as
	select
		DepartmentCode,
		AccountCode,
		FiscalYearID,
		FiscalMonthCode,
		TimeClassCode,
		Amount
	from
		client.FactStatisticImportMonthly
*/
exec procValidateColumnsExists 'client', 'viewFactStatisticImportMonthly', 'DepartmentCode'
exec procValidateColumnsExists 'client', 'viewFactStatisticImportMonthly', 'AccountCode'
exec procValidateColumnsExists 'client', 'viewFactStatisticImportMonthly', 'FiscalYearID'
exec procValidateColumnsExists 'client', 'viewFactStatisticImportMonthly', 'FiscalMonthCode'
exec procValidateColumnsExists 'client', 'viewFactStatisticImportMonthly', 'TimeClassCode'
exec procValidateColumnsExists 'client', 'viewFactStatisticImportMonthly', 'Amount'

/*
create view client.viewFactStatisticImportPayPeriod as
select
	DepartmentCode,
	AccountCode,
	PayPeriodCode,
	TimeClassCode,
	ChargeCode,
	PayCode,
	FiscalYearID,
	FiscalMonthCode,
	Amount
from
	client.FactStatisticImportPayPeriod
*/
exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'DepartmentCode'
exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'AccountCode'
exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'PayPeriodCode'
exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'TimeClassCode'
exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'ChargeCode'
exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'PayCode'
exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'FiscalYearID'
exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'FiscalMonthCode'
exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'Amount'

/*
create view client.viewFactPayrollImport as
select
	DepartmentCode,
	JobCode,
	PayCode,
	PayPeriodCode,
	TimeClassCode,
	Hours,
	Dollars
from
	client.FactPayrollImport
*/
exec procValidateColumnsExists 'client', 'viewFactPayrollImport', 'DepartmentCode'
exec procValidateColumnsExists 'client', 'viewFactPayrollImport', 'JobCode'
exec procValidateColumnsExists 'client', 'viewFactPayrollImport', 'PayCode'
exec procValidateColumnsExists 'client', 'viewFactPayrollImport', 'PayPeriodCode'
exec procValidateColumnsExists 'client', 'viewFactPayrollImport', 'TimeClassCode'
exec procValidateColumnsExists 'client', 'viewFactPayrollImport', 'Hours'
exec procValidateColumnsExists 'client', 'viewFactPayrollImport', 'Dollars'
GO


---------------------------------------------

---------------------------------------------
--  FUNCTIONS
---------------------------------------------

-- fw.GetCurrentDataPayPeriodID
CREATE FUNCTION [fw].[GetCurrentDataPayPeriodID]()
RETURNS smallint
AS
BEGIN


declare @currentPayPeriod int;
declare @currentPayPeriodStr nvarchar(4000);

set @currentPayPeriodStr = (
	select setting from dbsetting where name = 'Current_Payroll_PayPeriodID'
)

if ((@currentPayPeriodStr = '') or (@currentPayPeriodStr is null))
	set @currentPayPeriod = 0
else
	set @currentPayPeriod = ( select cast(@currentPayPeriodStr as int))

return @currentPayPeriod


END
GO


---------------------------------------------

-- fw.GetCurrentGLMonthID
CREATE FUNCTION [fw].[GetCurrentGLMonthID]()
RETURNS int
AS
BEGIN

declare @currentMonth int;
declare @currentMonthStr nvarchar(4000);

set @currentMonthStr = (
	select setting from dbsetting where name = 'Current_GL_MonthID'
)

if ((@currentMonthStr = '') or (@currentMonthStr is null))
	set @currentMonth = 0
else
	set @currentMonth = ( select cast(@currentMonthStr as int))

return @currentMonth

END
GO


---------------------------------------------

-- fw.GetCurrentGLYearID
CREATE FUNCTION [fw].[GetCurrentGLYearID]()
RETURNS int
AS
BEGIN

declare @currentYear int;
declare @currentYearStr nvarchar(4000);

set @currentYearStr = (
	select setting from dbsetting where name = 'Current_GL_YearID'
)

if ((@currentYearStr = '') or (@currentYearStr is null))
	set @currentYear = 0
else
	set @currentYear = ( select cast(@currentYearStr as int))

return @currentYear


END
GO


---------------------------------------------

-- fw.GetCurrentPayPeriodID
CREATE FUNCTION [fw].[GetCurrentPayPeriodID]()
RETURNS smallint
AS
BEGIN


declare @Today datetime;
set @Today = GETDATE();

declare @CurrentPayPeriod smallint;
select  @CurrentPayPeriod =  PayPeriodID from fw.DimPayPeriod
	where 
		@Today > PeriodStartCalendarDate 
		and
		@Today < PeriodEndCalendarDate
	order by PeriodStartCalendarDate DESC

if (@CurrentPayPeriod is null)
	set @CurrentPayPeriod = 0;
	
return @CurrentPayPeriod

END
GO


---------------------------------------------

-- fw.GetPayPeriodSamplingYear
/***************************************************************
** CID		Date		Author		WI			Description
** 1		2018-09-11	kzhuk		D-07649		PR Daily custom action calls procedures for wrong year
**************************************************************/
CREATE FUNCTION [fw].[GetPayPeriodSamplingYear](@fiscalYearID int, @isCalcDaily bit)
RETURNS int
AS
BEGIN

declare @previousDay DATE = DATEADD(DAY,-1,CAST(GETDATE() as DATE))
declare @yearOfSampling int = CASE WHEN @isCalcDaily = 0 then @fiscalYearID else (SELECT MAX(FiscalYearIDSecond) 
FROM fw.dimPayPeriod WHERE DATEADD(DAY,-1,CAST(GETDATE() as DATE)) BETWEEN PeriodStartCalendarDate and @previousDay) END
/*
	@isCalcDaily = 0 & @fiscalYearID int = 0 == > @yearOfSampling = 0
	@isCalcDaily = 1 & @fiscalYearID int = 0 == > @yearOfSampling = 'CalendarYear'
	@isCalcDaily = 1 & @fiscalYearID int = '1234' == > @yearOfSampling = 'CalendarYear'
	@isCalcDaily = 0 & @fiscalYearID int = '1234' == > @yearOfSampling = '1234'
	*/
	
RETURN @yearOfSampling
 
END
GO


---------------------------------------------

-- fw.GetUserRoleAssignmentCSV
CREATE FUNCTION [fw].[GetUserRoleAssignmentCSV] ( 
		@LootID nvarchar(200), 
		@RoleID int)
    RETURNS NVARCHAR(MAX)
AS
BEGIN

DECLARE @csv NVARCHAR(MAX)
SET @csv = ''
DECLARE @count int
SET @count = 0
declare crsCursor CURSOR LOCAL FAST_FORWARD FOR

select distinct
	UP.NameFull
from
	S3RoleAssignment RA (readuncommitted)
	inner join S3IdentityLink IL (readuncommitted)
		on RA.IdentityGUID = IL.GroupingGUID
	inner join UserProfile UP (readuncommitted)
		on IL.MemberGUID = UP.UserGUID
where
	RA.RoleID = @RoleID
	and RA.LootGroupID = @LootID

order by NameFull
open crsCursor;

DECLARE @NameFull nvarchar(100)

FETCH NEXT FROM crsCursor into @NameFull
WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		
		IF (@count = 0) BEGIN
		select @csv = @csv + @NameFull
		END ELSE BEGIN
		select @csv = @csv + '; ' + @NameFull
		END
		set @count = @count +1
		FETCH NEXT FROM crsCursor into @NameFull
		
	END
close crsCursor;
DEALLOCATE crsCursor;

	RETURN @csv
END
GO


---------------------------------------------

-- fw.GetYTDDaysInMonth
CREATE FUNCTION [fw].[GetYTDDaysInMonth](@monthID int)
RETURNS int
AS
BEGIN

declare @sortOrder int = (select sortOrder from fw.dimfiscalmonth where FiscalMonthID = @monthID)

declare @ytdDays int = (select sum(DaysInMonth) from fw.dimfiscalmonth where sortorder <= @sortOrder)

return @ytdDays

END
GO


---------------------------------------------

