USE EnVisage
GO

IF OBJECT_ID('VW_Holidays2Expenditures') IS NOT NULL
	DROP VIEW dbo.VW_Holidays2Expenditures
GO

CREATE VIEW [dbo].[VW_Holidays2Expenditures] AS
(
	-- Holidays for specified ECs
	SELECT H.HolidayGroupId, EC.Id as ExpenditureCategoryId
	FROM Holiday H
	JOIN Holiday2ExpenditureCategory H2E ON (H2E.HolidayId = H.Id)
	JOIN ExpenditureCategory EC on EC.Id = H2E.ExpenditureCategoryId
	WHERE (H.CompanyImpact = 0) AND (H.IsInclude = 1) AND (H.WorkingDays = 0)

	UNION

	-- Holidays for all company resources
	SELECT H.HolidayGroupId, EC.Id as ExpenditureCategoryId
	FROM Holiday H
	LEFT 
	JOIN ExpenditureCategory EC ON (1 = 1)
	WHERE (H.CompanyImpact = 1) AND (H.WorkingDays = 0)

	UNION

	-- Holidays for all resources, except specified resources, teams and ECs
	SELECT H.HolidayGroupId, EC.Id as ExpenditureCategoryId
	FROM Holiday H
	LEFT JOIN ExpenditureCategory EC ON (1 = 1)
	WHERE (H.CompanyImpact = 0) AND (H.IsInclude = 0) AND (H.WorkingDays = 0)
)

EXCEPT

SELECT H.HolidayGroupId, H2E.ExpenditureCategoryId
FROM Holiday H
INNER 
JOIN Holiday2ExpenditureCategory H2E ON (H2E.HolidayId = H.Id)
WHERE (H.CompanyImpact = 0) AND (H.IsInclude = 0) AND (H.WorkingDays = 0)