SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE VIEW [dbo].[vw_acc_invoices_risks_variables_taxes]
AS
	WITH cte_union
	AS	(
			SELECT	t.invrisvt_invoice_id				AS invoice_id,
					t.invrisvt_risk_situation_id		AS risk_situation_id,
					t.invrisvt_variable_id				AS variable_id,
					t.invrisvt_tax_id					AS tax_id,
					t.invrisvt_tax_value				AS tax_value
			FROM	acc_invoices_risks_variables_taxes t

			UNION ALL

			SELECT	ct.invrisvct_invoice_id, 
					ct.invrisvct_risk_situation_id,
					ct.invrisvct_variable_id, 
					ct.invrisvct_tax_id, 
					ct.invrisvct_tax_value
			FROM	acc_invoices_risks_variables_commission_taxes ct
		),
	cte_group
	AS	(
		SELECT	u.invoice_id, u.risk_situation_id, u.variable_id, u.tax_id,
				SUM(u.tax_value) AS tax_value
		FROM	cte_union u
		GROUP BY u.invoice_id, u.risk_situation_id, u.variable_id, u.tax_id
		)
	SELECT	g.invoice_id, g.risk_situation_id, g.variable_id, g.tax_id, g.tax_value
	FROM	cte_group g



GO
