Difficulty creating summation column in mysql

Asked

Viewed 427 times

0

I am making a committee report, but a doubt has arisen, I want to bring some totals at the end of the report such as the gross value of all committees, which would be the vl_comis - desc_comis. Anyway, how do I create a column called total_valor_bruto that returns the sum of all gross values of the commission table?

SELECT 
a.id,
a.nf,
a.data_lcto,
a.data_prog,
a.data_pgto,
a.vl_comis,
a.desc_comis,
a.ir_comis, 
a.vl_pgto,
a.pedido_comis,
b.Empresa as emp,
b.RazaoSocial as razao,
c.cod, 
c.Representante as representante,
d.PeriodoID as periodo_comissao,
d.Periodo_inicial as inicial,
d.Periodo_final as final
FROM (((Comissoes a
INNER JOIN Empresas b ON a.EmpresaID = b.EmpresaID)
INNER JOIN Representantes c ON a.RepresentanteID = c.RepresentanteID)
INNER JOIN Periodos d ON a.PeriodoID = d.PeriodoID)
WHERE d.PeriodoID ='".$_COOKIE["cpr"]."' ORDER BY a.created"); 

2 answers

1

First you have to put the calculation you want to be done in the query (a.vl_comis - a.desc_comis) as total_valor_bruto with the function sum which is to sum up all the results and put the group by to aggregate results in columns that have no calculation.

SELECT 
  a.id,
  a.nf,
  a.data_lcto,
  a.data_prog,
  a.data_pgto,
  a.vl_comis,
  a.desc_comis,
  a.ir_comis, 
  a.vl_pgto,
  a.pedido_comis,
  b.Empresa as emp,
  b.RazaoSocial as razao,
  c.cod, 
  c.Representante as representante,
  d.PeriodoID as periodo_comissao,
  sum(a.vl_comis - a.desc_comis) as total_valor_bruto,
  d.Periodo_inicial as inicial,
  d.Periodo_final as final
FROM (((Comissoes a
INNER JOIN Empresas b ON a.EmpresaID = b.EmpresaID)
INNER JOIN Representantes c ON a.RepresentanteID = c.RepresentanteID)
INNER JOIN Periodos d ON a.PeriodoID = d.PeriodoID)
WHERE d.PeriodoID ='".$_COOKIE["cpr"]."'
GROUP BY
  a.id,
  a.nf,
  a.data_lcto,
  a.data_prog,
  a.data_pgto,
  a.vl_comis,
  a.desc_comis,
  a.ir_comis, 
  a.vl_pgto,
  a.pedido_comis,
  b.Empresa,
  b.RazaoSocial,
  c.cod, 
  c.Representante,
  d.PeriodoID,
  d.Periodo_inicial,
  d.Periodo_final
ORDER BY
  a.created; 
  • Without the group by it until it returns the raw value but only 1 record, with the group by is giving this error: #1064 - You have an error in your SQL syntax; check the manual that Corresponds to your Mysql server version for the right syntax to use near 'GROUP BY a.id, a.nf, a.data_lcto, a.data_prog, a.data_pgto, a.vl_comis, a.desc_c' at line 25

  • You copied the query from your code and forgot to take the ); from the end, so I got confused. now it should be OK.

  • This answer helped you @Smokerohden, if yes accept it as shown in this image

0

If I understand the question correctly just use the following query and change for your use:

select sum(a.vl_comis + a.ir_comis) as total_valor_bruto

If that’s not the answer, explain it to me a little better please?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.