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

		SELECT	i.invpolvct_invoice_id							AS invoice_id,
				i.invpolvct_policy_situation_id					AS policy_situation_id,
				i.invpolvct_variable_id							AS variable_id,
				i.invpolvct_tax_id								AS tax_id,
				isnull(pv.prdv_company_id, p.pol_company_id)	AS company_id,
				i.invpolvct_tax_value							AS tax_value
		FROM	acc_invoices_policies_variables_commission_taxes i
				INNER JOIN pol_policies_situations ps		ON	ps.pols_policy_situation_id = i.invpolvct_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.invpolvct_variable_id

		WHERE	NOT EXISTS	(
							SELECT	1
							FROM	acc_invoices_policies_variables_commission_taxes_cies ir
							WHERE	ir.invpolvctc_invoice_id = i.invpolvct_invoice_id
							AND		ir.invpolvctc_policy_situation_id = i.invpolvct_policy_situation_id
							AND		ir.invpolvctc_variable_id = i.invpolvct_variable_id
							AND		ir.invpolvctc_tax_id = i.invpolvct_tax_id
							)

		UNION ALL

		SELECT	ir.invpolvctc_invoice_id, 
				ir.invpolvctc_policy_situation_id,
				ir.invpolvctc_variable_id,
				ir.invpolvctc_tax_id,
				ir.invpolvctc_company_id,
				ir.invpolvctc_tax_value
		FROM	acc_invoices_policies_variables_commission_taxes_cies ir

GO
