﻿---------------------------------------------
-- VIEW dati riassuntivi livello Trend
---------------------------------------------

CREATE OR ALTER VIEW [dbo].[v_TrendData]
AS

WITH cteTratt AS
(
	SELECT	doc.Anno as YearRef
			,MONTH(doc.DataIns) AS MonthRef
			,CAST(SUM(res.FinalPrice) AS DECIMAL(18,6)) AS Trattato
	FROM	Docs doc
		INNER JOIN Resources res ON doc.DocId=res.DocId
	WHERE	doc.IsActive = 1 AND doc.IsDraft=0
	GROUP BY doc.Anno, MONTH(doc.DataIns)
),
cteOrd AS
(
	SELECT	o.YearRef
			,MONTH(o.DateIns) AS MonthRef
			,CAST(SUM(ISNULL(r.FinalPrice,0)) AS DECIMAL(18,6)) AS Ordinato
	FROM	Orders o
		LEFT OUTER JOIN dbo.OrderRes AS r ON o.OrdId = r.OrdId
	GROUP BY o.YearRef,  MONTH(o.DateIns)
),
cteFatt AS
(
	SELECT	b.YearRef
			,MONTH(b.DateIns) AS MonthRef
			,CAST(SUM(ISNULL(f.Amount,0)) AS DECIMAL(18,6)) AS Fatturato
			,CAST(SUM(ISNULL(f.Paid,0)) AS DECIMAL(18,6)) AS Incassato
	FROM	BillingExt b
		LEFT OUTER JOIN dbo.AccMov AS f ON b.IdxBillExt = f.IdxBillExt
	GROUP BY b.YearRef,  MONTH(b.DateIns)
)
SELECT	  t.YearRef
		, t.MonthRef
		, ISNULL(t.Trattato,0) AS Trattato
		, ISNULL(o.Ordinato,0) AS Ordinato
		, ISNULL(f.Fatturato,0) AS Fatturato
		, ISNULL(f.Incassato,0) AS Incassato
FROM	cteTratt t
	LEFT OUTER JOIN cteOrd o ON t.YearRef = o.YearRef AND t.MonthRef = o.MonthRef
	LEFT OUTER JOIN cteFatt f ON t.YearRef = f.YearRef AND t.MonthRef = f.MonthRef
--ORDER BY YearRef, MonthRef

GO


