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

		SELECT	i.invrisvct_invoice_id							AS invoice_id,
				i.invrisvct_risk_situation_id					AS risk_situation_id,
				i.invrisvct_variable_id							AS variable_id,
				i.invrisvct_tax_id								AS tax_id,
				isnull(pv.prdv_company_id, p.pol_company_id)	AS company_id,
				i.invrisvct_tax_value							AS tax_value
		FROM	acc_invoices_risks_variables_commission_taxes i
				INNER JOIN ris_risks_situations ps			ON	ps.riss_risk_situation_id = i.invrisvct_risk_situation_id
				INNER JOIN pol_policies p					ON	p.pol_policy_id = ps.riss_policy_id
				INNER JOIN pr_products_variables pv			ON pv.prdv_variable_id = i.invrisvct_variable_id

		WHERE	NOT EXISTS	(
							SELECT	1
							FROM	acc_invoices_risks_variables_commission_taxes_cies ir
							WHERE	ir.invrisvctc_invoice_id = i.invrisvct_invoice_id
							AND		ir.invrisvctc_risk_situation_id = i.invrisvct_risk_situation_id
							AND		ir.invrisvctc_variable_id = i.invrisvct_variable_id
							AND		ir.invrisvctc_tax_id = i.invrisvct_tax_id
							)

		UNION ALL

		SELECT	ir.invrisvctc_invoice_id, 
				ir.invrisvctc_risk_situation_id,
				ir.invrisvctc_variable_id,
				ir.invrisvctc_tax_id,
				ir.invrisvctc_company_id,
				ir.invrisvctc_tax_value
		FROM	acc_invoices_risks_variables_commission_taxes_cies ir

GO
