IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[V_INTEGRA_BENNER_RESUMO]'))
	DROP VIEW [dbo].[V_INTEGRA_BENNER_RESUMO]
GO

CREATE VIEW [dbo].[V_INTEGRA_BENNER_RESUMO]  
AS
SELECT
	newid()	AS ID,
	0 AS ID_SITUACAO,
	TOPICO.ID AS TOPICO_ID,
	COUNT(*) AS QTD
FROM
	DBO.INTEGRA_BENNER_EVENTOS EVENTO
INNER JOIN 
	DBO.INTEGRA_BENNER_TOPICO TOPICO
	ON EVENTO.TOPICO = TOPICO.ID
WHERE
	EVENTO.ST_EVENTO = 0
GROUP BY
	EVENTO.ST_EVENTO, TOPICO.ID

UNION ALL

SELECT
	newid()	AS ID,
	1 AS ID_SITUACAO,
	TOPICO.ID AS TOPICO_ID,
	COUNT(*) AS QTD
FROM
	DBO.INTEGRA_BENNER_EVENTOS EVENTO
INNER JOIN 
	DBO.INTEGRA_BENNER_TOPICO TOPICO
	ON EVENTO.TOPICO = TOPICO.ID
WHERE
	EVENTO.ST_EVENTO = 1
GROUP BY
	EVENTO.ST_EVENTO, TOPICO.ID

UNION ALL

SELECT
	newid()	AS ID,
	2 AS ID_SITUACAO,
	TOPICO.ID AS TOPICO_ID,
	COUNT(*) AS QTD
FROM
	DBO.INTEGRA_BENNER_EVENTOS EVENTO
INNER JOIN 
	DBO.INTEGRA_BENNER_TOPICO TOPICO
	ON EVENTO.TOPICO = TOPICO.ID
WHERE
	EVENTO.ST_EVENTO = 2
GROUP BY
	EVENTO.ST_EVENTO, TOPICO.ID
	
UNION ALL

SELECT
	newid()	AS ID,
	3 AS ID_SITUACAO,
	TOPICO.ID AS TOPICO_ID,
	COUNT(*) AS QTD
FROM
	DBO.INTEGRA_BENNER_EVENTOS EVENTO
INNER JOIN 
	DBO.INTEGRA_BENNER_TOPICO TOPICO
	ON EVENTO.TOPICO = TOPICO.ID
WHERE
	EVENTO.ST_EVENTO = 3
GROUP BY
	EVENTO.ST_EVENTO, TOPICO.ID

UNION ALL

SELECT
	newid()	AS ID,
	4 AS ID_SITUACAO,
	TOPICO.ID AS TOPICO_ID,
	COUNT(*) AS QTD
FROM
	DBO.INTEGRA_BENNER_EVENTOS EVENTO
INNER JOIN 
	DBO.INTEGRA_BENNER_TOPICO TOPICO
	ON EVENTO.TOPICO = TOPICO.ID
WHERE
	EVENTO.ST_EVENTO IN (2,3)
GROUP BY
	EVENTO.ST_EVENTO, TOPICO.ID
	
UNION ALL

SELECT
	newid()	AS ID,
	5 AS ID_SITUACAO,
	TOPICO.ID AS TOPICO_ID,
	COUNT(*) AS QTD
FROM
	DBO.INTEGRA_BENNER_EVENTOS EVENTO
INNER JOIN 
	DBO.INTEGRA_BENNER_TOPICO TOPICO
	ON EVENTO.TOPICO = TOPICO.ID
WHERE
	EVENTO.ST_EVENTO <> 4
GROUP BY 
	TOPICO.ID;