-- SA. View for Top 5 Projects Performance
USE [envisage]
Go

if exists (select * from sys.views where name='VW_ProjectPerformance')
begin
  drop view VW_ProjectPerformance
end
GO

CREATE VIEW 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 