3
Having the following SELECT consulting a dynamic table from a subselect, I get the result of the query correctly but with records divided in the following example:
cod_representante | ... | VALOR_TOTAL_MERCEARIA | VALOR_TOTAL_PC_MP
123 | ... | 59000 | 0
123 | ... | 0 | 2000
When should I group it only by cod_representante
:
cod_representante | ... | VALOR_TOTAL_MERCEARIA | VALOR_TOTAL_PC_MP
123 | ... | 59000 | 2000
O Select:
SELECT codFunc,
regional AS gerente,
nome_gerente AS supervisor,
cod_representante,
nome_representante,
SUM(valor_total_seca) AS VALOR_TOTAL_MERCEARIA,
SUM(valor_total_liquida) AS VALOR_TOTAL_PC_MP,
ISNULL(valor_total_seca,0) + ISNULL(valor_total_liquida,0) AS TOTAL_GERAL,
ISNULL(valor_rateio,0) AS VALOR_DAS_DEVOLUCOES,
CASE
WHEN valor_rateio IS NULL THEN (ISNULL(valor_total_seca,0) + ISNULL(valor_total_liquida,0))
ELSE (ISNULL(valor_total_seca,0) + ISNULL(valor_total_liquida,0)) - ISNULL(valor_rateio,0)
END AS TOTAL_SEM_DEV,
ISNULL(comissao, 0) AS PERCENTUAL_COMISSAO,
((ISNULL(valor_total_seca,0) + ISNULL(valor_total_liquida,0)) - ISNULL(valor_rateio,0)) * ISNULL(comissao,0) AS VALOR_DA_COMISSAO
FROM ...
THE GROUP BY:
GROUP BY regional,
cod_gerente,
nome_gerente,
cod_representante,
codFunc,
nome_representante,
valor_total_seca ,
valor_total_liquida,
valor_rateio,
comissao
If I do not include the fields being manipulated in the arithmetic operation, in the section below,
ISNULL(valor_total_seca,0) + ISNULL(valor_total_liquida,0) AS TOTAL_GERAL,
ISNULL(valor_rateio,0) AS VALOR_DAS_DEVOLUCOES,
CASE
WHEN valor_rateio IS NULL THEN (ISNULL(valor_total_seca,0) + ISNULL(valor_total_liquida,0))
ELSE (ISNULL(valor_total_seca,0) + ISNULL(valor_total_liquida,0)) - ISNULL(valor_rateio,0)
END AS TOTAL_SEM_DEV,
ISNULL(comissao, 0) AS PERCENTUAL_COMISSAO,
((ISNULL(valor_total_seca,0) + ISNULL(valor_total_liquida,0)) - ISNULL(valor_rateio,0)) * ISNULL(comissao,0) AS VALOR_DA_COMISSAO
i get the following error:
Msg 8120, Level 16, State 1, Line 13 Column’t. valor_total_seca' is invalid in the select list because it is not contained in either an Aggregate Function or the GROUP BY clause.
Msg 8120, Level 16, State 1, Line 13 Column’t. valor_total_liquida' is invalid in the select list because it is not contained in either an Aggregate Function or the GROUP BY clause.
Ricardo, using the proposed solution even works if I just take these columns, but I need to display all the columns of the first SELECT shown. Consequently I am obliged to group them again by SQL and the values end up being separated as before.
– Marcelo de Andrade
But then you group them all, except the two, provided that in select have the sum in them it will group, it will not?
– Ricardo
With some amendments, there was a brief solution.
– Marcelo de Andrade