SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE VIEW [dbo].[vw_acc_invoices_policies_variables_taxes_cies]
AS

		SELECT	i.invpolvt_invoice_id							AS invoice_id,
				i.invpolvt_policy_situation_id					AS policy_situation_id,
				i.invpolvt_variable_id							AS variable_id,
				i.invpolvt_tax_id								AS tax_id,
				isnull(pv.prdv_company_id, p.pol_company_id)	AS company_id,
				i.invpolvt_tax_value							AS tax_value
		FROM	acc_invoices_policies_variables_taxes i
				INNER JOIN pol_policies_situations ps		ON	ps.pols_policy_situation_id = i.invpolvt_policy_situation_id
				INNER JOIN pol_policies p					ON	p.pol_policy_id = ps.pols_policy_id
				INNER JOIN pr_products_variables pv			ON pv.prdv_variable_id = i.invpolvt_variable_id

		WHERE	NOT EXISTS	(
							SELECT	1
							FROM	acc_invoices_policies_variables_taxes_cies ir
							WHERE	ir.invpolvtc_invoice_id = i.invpolvt_invoice_id
							AND		ir.invpolvtc_policy_situation_id = i.invpolvt_policy_situation_id
							AND		ir.invpolvtc_variable_id = i.invpolvt_variable_id
							AND		ir.invpolvtc_tax_id = i.invpolvt_tax_id
							)

		UNION ALL

		SELECT	ir.invpolvtc_invoice_id, 
				ir.invpolvtc_policy_situation_id,
				ir.invpolvtc_variable_id,
				ir.invpolvtc_tax_id,
				ir.invpolvtc_company_id,
				ir.invpolvtc_tax_value
		FROM	acc_invoices_policies_variables_taxes_cies ir

GO
