0

I have a table with the following columns: codigo_receita VARCHAR, valor_orcamento NUMERIC(30,2) and exercicio_orcamento INTEGER.

I created a query that works, but I would like to optimize it, without repeating code.

How do I assign the value of each query to a variable?

In order to get something like this:

SELECT
(query_1 - query_2) / query_2
AS changes

The query I created:

SELECT
((SELECT
    SUM(valor_orcamento)
FROM orcamento
WHERE exercicio_orcamento = 2021
GROUP BY exercicio_orcamento)
-
(SELECT
    SUM(valor_orcamento)
FROM orcamento
WHERE exercicio_orcamento = 2020
GROUP BY exercicio_orcamento))
/
(SELECT
    SUM(valor_orcamento)
FROM orcamento
WHERE exercicio_orcamento = 2020
GROUP BY exercicio_orcamento) AS change

1 Answer 1

1

You can do that in a single statement. You probably want to cast the result of the sum() to numeric otherwise the division would be an integer division:

SELECT (
         SUM(valor_orcamento) filter (WHERE exercicio_orcamento = 2021) 
         - 
         SUM(valor_orcamento) filter (WHERE exercicio_orcamento = 2020)
       )::numeric
       / 
       SUM(valor_orcamento) filter (WHERE exercicio_orcamento = 2020)
FROM orcamento
WHERE exercicio_orcamento IN (2020, 2021)
GROUP BY exercicio_orcamento
Sign up to request clarification or add additional context in comments.

2 Comments

Better than I could even imagine, I didn't know the filter, but I didn't understand why it's necessary to use the sentence "WHERE exercicio_orcamento IN (2020, 2021)" after "from". Considering that the records already been filtered after each SUM() And just for curiosity, to learn more one thing. Is it possible to do that like I was trying? Assigning to a variable the output of a query? If so, how could I do that?
@JoãoPedroReisSilva: it's mainly a performance optimization so it doesn't need to read all years just to calculate the result for two.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.