add and split results in the same query by taking the result of the first sum

Asked

Viewed 174 times

1

I need two information I make the first sum

SELECT 
FORMAT(ROUND(SUM(CASE WHEN MONTH(periodo) IN (12) AND classificacao = '3.6' THEN IFNULL(debito-credito,NULL)  ELSE  0 END)) ,2) AS custo_1, 

Right below I need to take the result above and divide by another SUM

FORMAT(ROUND(SUM(CASE WHEN MONTH(periodo) IN (1)  AND classificacao = '3.6' THEN IFNULL(debito-credito,NULL)  ELSE  0 END)) ,2) 
/
FORMAT(ROUND(SUM(CASE WHEN MONTH(periodo) IN (1)  AND classificacao = '3.1.01.01' THEN IFNULL(debito-credito,NULL)  ELSE  0 END)) - ROUND(SUM(CASE WHEN MONTH(periodo) IN (1)  AND classificacao = '3.2.01.01.01' THEN IFNULL(debito-credito,NULL)  ELSE  0 END)),2)  AS peso_custo_1

FROM tbl_balancete;

How can I use the result of the first sum so I don’t need to use any cost sum code again ?

1 answer

0

Try using a subselect:

Select Sum(Tabela.campoN+retSql.PrimeiraSoma) 
  From (select suatabela.periodo AS PrimeiraSoma
             , suatabela.classificacao
          from suatabela
       ) AS retSql
 Inner Join Tabela ON Tabela.classificacao = retSqsl.classificacao

This way, you can do only 1 select with the first value (you don’t even need to sum in) to be able to take advantage of any other piece of the query. Here add the sort field only to make Join with the 'external' table only to exemplify, Join has to be done with the corresponding field. I hope I’ve helped.

  • 1

    Could I explain a little better how I can apply in my code, where I would split ? I didn’t get it right

  • Now, looking at your code, I would make the temporary table select 3 times passing in the Where its ranking and out, would make the sum and division.

  • The little guy responded heavily.

Browser other questions tagged

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