-- SA. View for Top 5 Projects Performance (UPDATE)
USE [EnVisage]
GO

ALTER VIEW [dbo].[VW_ScenarioPseudoActuals] AS
SELECT /* M.Id, */ O.ForecastScenarioId, M.ParentID as ActualsScenarioId, M.ExpenditureCategoryId, M.WeekEndingDate, M.Quantity,
	M.Cost, 0 AS IsForecast 
FROM ScenarioDetail M
INNER JOIN Scenario N ON (M.ParentID = N.Id)
INNER JOIN VW_ScenarioRelations O ON (M.ParentID = O.ActualsScenarioId)
WHERE N.[Type] = 9
UNION ALL
(
SELECT /* A.Id, */ A.ParentID AS ForecastScenarioId, C.ActualsScenarioId, A.ExpenditureCategoryId, A.WeekEndingDate, A.Quantity,
	A.Cost, 1 AS IsForecast  
FROM ScenarioDetail A
INNER JOIN VW_ScenarioActualsReplacePoints B ON (A.ParentID = B.ForecastScenarioId)
	AND (A.ExpenditureCategoryId = B.ExpenditureCategoryId)
	AND (A.WeekEndingDate = B.WeekEndingDate)
INNER JOIN VW_ScenarioRelations C ON (A.ParentID = C.ForecastScenarioId)
)
GO

ALTER VIEW [dbo].[VW_ScenarioActualsTotalCost] AS
SELECT A.ForecastScenarioId, A.ActualsScenarioId, SUM(A.Cost) AS TotalCost 
FROM VW_ScenarioPseudoActuals A
GROUP BY A.ForecastScenarioId, A.ActualsScenarioId
GO

ALTER VIEW [dbo].[VW_ScenarioPerformance] AS
SELECT A.ForecastScenarioId, A.ActualsScenarioId, A.ForecastScenarioType, 
	B.TotalCost AS ForecastTotalCost, C.TotalCost AS ActualsTotalCost,
	(CASE B.TotalCost
		WHEN 0 THEN NULL
		ELSE ABS((B.TotalCost - C.TotalCost) / B.TotalCost)
		END) AS VariationPercent
FROM VW_ScenarioRelations A
LEFT JOIN VW_ScenarioForecastTotalCost B ON (A.ForecastScenarioId = B.ForecastScenarioId)
LEFT JOIN VW_ScenarioActualsTotalCost C ON ((A.ForecastScenarioId = C.ForecastScenarioId) 
	AND (A.ActualsScenarioId = C.ActualsScenarioId))
GO

ALTER VIEW [dbo].[VW_ProjectPerformance] AS
SELECT A.*, C.Id AS ProjectId, C.Name AS ProjectName, B.Status, B.BUDirectCosts, B.EndDate AS ScenarioEndDate,
C.TypeId AS ProjectTypeId, D.Name AS ProjectTypeName, C.Priority AS ProjectPriority,
(B.BUDirectCosts - A.ForecastTotalCost + A.ActualsTotalCost) AS ActualsCostForecasted,
(A.ActualsTotalCost - A.ForecastTotalCost) AS ActualsCostVariation,
(B.BUDirectCosts / C.Priority) AS ProjectWeight,
E.Id AS FiscalPeriodId
FROM VW_ScenarioPerformance A
INNER JOIN Scenario B ON (A.ForecastScenarioId = B.Id)
INNER JOIN Project C ON (B.ParentId = C.Id)
INNER JOIN [Type] D ON (C.TypeId = D.Id)
INNER JOIN FiscalCalendar E ON ((B.EndDate >= E.StartDate) AND (B.EndDate <= E.EndDate))
where (B.Status = 1) AND (B.[Type] <> 9) AND (E.[Type] = 2)
GO



