-- To get comments and questions about this script contact SA
USE [EnVisage]
GO

begin transaction

-- Insert teams to scenarios from their projects (project parts)
INSERT INTO Team2Scenario (ScenarioId, TeamId, Allocation)
SELECT C.Id, A.TeamId, 0 FROM Team2Project A
INNER JOIN Project B ON (A.ProjectId = B.Id)
INNER JOIN Scenario C ON (B.Id = C.ParentId)
WHERE (C.Type <> 9) AND
(NOT EXISTS(SELECT 1 FROM Team2Scenario D 
	WHERE (D.ScenarioId = C.Id) AND (D.TeamId = A.TeamId))
)

-- Set 100% allocation to the added into scenario teams, if the scenario has single team with allocation = 0%
UPDATE Team2Scenario SET Allocation=100
WHERE Team2Scenario.ScenarioId IN
(
SELECT A.ScenarioId FROM Team2Scenario A
GROUP BY A.ScenarioId
HAVING (COUNT(1) = 1) AND SUM(A.Allocation) = 0
)

-- Set 50% allocation to the added into scenario teams, if the there where added 2 teams to scenario (both 0% alloc)
UPDATE Team2Scenario SET Allocation=50
WHERE Team2Scenario.ScenarioId IN
(
SELECT A.ScenarioId FROM Team2Scenario A
GROUP BY A.ScenarioId
HAVING (COUNT(1) = 2) AND SUM(A.Allocation) = 0
)

commit transaction
