SELECT ROUND(SUM(r.qtd_linha_ocupada),0) AS qtd_linha_ocupada
FROM(
SELECT	COALESCE(SUM(CASE WHEN (LENGTH(i.denominacao)) <= 30 THEN 1
		WHEN (LENGTH(i.denominacao)) BETWEEN 31 AND 60 THEN 1.51
		WHEN (LENGTH(i.denominacao)) BETWEEN 61 AND 90 THEN 2.01
		ELSE 2.51 END),0) AS qtd_linha_ocupada
FROM	item_nfs AS infs
        INNER JOIN nota_fiscal_saida AS nfs ON (nfs.id_nota_fiscal_saida = infs.id_nota_fiscal_saida)
	INNER JOIN item AS i ON (i.id_item = infs.id_item)
	INNER JOIN item_empresa AS ie ON (ie.id_item = i.id_item AND ie.id_empresa = nfs.id_empresa)
	INNER JOIN cfop ON (cfop.id_cfop = infs.id_cfop)
	INNER JOIN unidade_medida AS u ON (u.id_unidade_medida = infs.id_unidade_medida)
	INNER JOIN tipo_unidade_medida AS tu ON (tu.id_tipo_unidade_medida = u.id_tipo_unidade_medida)
	LEFT OUTER JOIN local_estoque AS le ON (le.id_local_estoque = infs.id_local_estoque)
	LEFT OUTER JOIN cst AS cst_icms ON (cst_icms.id_cst = infs.id_cst_icms)
	INNER JOIN cst AS cst_pis ON (cst_pis.id_cst = infs.id_cst_pis)
	INNER JOIN cst AS cst_cofins ON (cst_cofins.id_cst = infs.id_cst_cofins)
WHERE	infs.id_nota_fiscal_saida = :Id
AND	EXISTS(SELECT 1 FROM item_nfs AS i1 INNER JOIN cfop AS c1 ON (c1.id_cfop = i1.id_cfop)
		WHERE id_nota_fiscal_saida = nfs.id_nota_fiscal_saida AND c1.entrada_saida = 2)

UNION ALL

SELECT	COALESCE(SUM(CASE WHEN (LENGTH(i.denominacao)) <= 30 THEN 1
		WHEN (LENGTH(i.denominacao)) BETWEEN 31 AND 60 THEN 1.51
		WHEN (LENGTH(i.denominacao)) BETWEEN 61 AND 90 THEN 2.01
		ELSE 2.51 END),0) AS qtd_linha_ocupada
FROM	item_nfe AS infe
	INNER JOIN nota_fiscal_entrada AS nfe ON (nfe.id_nota_fiscal_entrada = infe.id_nota_fiscal_entrada)
	INNER JOIN modelo_documento_fiscal AS mdf ON (mdf.id_modelo_documento_fiscal = nfe.id_modelo_documento_fiscal)
	INNER JOIN item AS i ON (i.id_item = infe.id_item)
	INNER JOIN item_empresa AS ie ON (ie.id_item = i.id_item AND ie.id_empresa = nfe.id_empresa)
	INNER JOIN cfop ON (cfop.id_cfop = infe.id_cfop)
	INNER JOIN unidade_medida AS u ON (u.id_unidade_medida = infe.id_unidade_medida)
	INNER JOIN tipo_unidade_medida AS tu ON (tu.id_tipo_unidade_medida = u.id_tipo_unidade_medida)
	INNER JOIN local_estoque AS le ON (le.id_local_estoque = infe.id_local_estoque)
	LEFT OUTER JOIN cst AS cst_icms ON (cst_icms.id_cst = infe.id_cst_icms)
	INNER JOIN cst AS cst_pis ON (cst_pis.id_cst = infe.id_cst_pis)
	INNER JOIN cst AS cst_cofins ON (cst_cofins.id_cst = infe.id_cst_cofins)
	INNER JOIN tipo_tributacao AS tt ON (tt.id_tipo_tributacao = infe.id_tipo_tributacao)
WHERE	infe.id_nota_fiscal_entrada = :Id
AND	EXISTS(SELECT 1 FROM item_nfe AS i1 INNER JOIN cfop AS c1 ON (c1.id_cfop = i1.id_cfop)
		WHERE id_nota_fiscal_entrada = nfe.id_nota_fiscal_entrada AND c1.entrada_saida = 1)) AS r