CREATE VIEW OR REPLACE vw_custo_nf
 AS
SELECT
	D.EMPRES_CODIGO AS EMPRES_CODIGO,
	D.FILIAL_CODIGO AS FILIAL_CODIGO,
	D.DOCTIP_CODIGO AS DOCTIP_CODIGO,
	D.DOCCAB_NUMERO AS DOCCAB_NUMERO,
	D.DOCCAB_STATUS AS DOCCAB_STATUS,
	I.PRDCAD_CODIGO AS PRDCAD_CODIGO,
	D.CLIFOR_CODIGO AS CLIFOR_CODIGO,
	C.CLIFOR_RAZAO AS CLIFOR_RAZAO,
	C.CLIFOR_FANTASIA AS CLIFOR_FANTASIA,
	SUM(I.DOCITM_QDE) * P.PRDCAD_CUSTO AS CUSTO,
	DT.DOCTIP_MOVIMENTO AS DOCTIP_MOVIMENTO,
	D.DOCCAB_DATAFATURAMENTO AS DOCCAB_DATAFATURAMENTO
FROM doccab D
LEFT JOIN docitm I ON (D.DOCCAB_SEQ = I.DOCCAB_SEQ)
LEFT JOIN prdcad P ON (
	I.EMPRES_CODIGO = P.EMPRES_CODIGO AND
	I.FILIAL_CODIGO = P.FILIAL_CODIGO AND
	I.PRDCAD_CODIGO = P.PRDCAD_CODIGO
)
LEFT JOIN doctip DT ON (D.DOCTIP_CODIGO = DT.DOCTIP_CODIGO)
LEFT JOIN clifor C ON (
	D.EMPRES_CODIGO = C.EMPRES_CODIGO AND
	D.FILIAL_CODIGO = C.FILIAL_CODIGO AND
	D.CLIFOR_CODIGO = C.CLIFOR_CODIGO AND
	C.CLFTIP_CODIGO = 'CLIENTE'
)
GROUP BY
	D.EMPRES_CODIGO,
	D.FILIAL_CODIGO,
	D.DOCTIP_CODIGO,
	D.DOCCAB_NUMERO,
	I.PRDCAD_CODIGO,
	P.PRDCAD_CUSTO,
	D.CLIFOR_CODIGO,
	C.CLIFOR_RAZAO,
	C.CLIFOR_FANTASIA,
	D.DOCCAB_STATUS,
	DT.DOCTIP_MOVIMENTO,
	D.DOCCAB_DATAFATURAMENTO


